Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(autopilot): scheduled/triggered automations for AI agents (#1028)
Jiayuan Zhangd88fe2608ef2
diff --git a/apps/desktop/src/renderer/src/pages/autopilot-detail-page.tsx b/apps/desktop/src/renderer/src/pages/autopilot-detail-page.tsxnew file mode 100644index 0000000000..5c0c4e5f08--- /dev/null+++ b/apps/desktop/src/renderer/src/pages/autopilot-detail-page.tsx@@ -0,0 +1,17 @@+import { useParams } from "react-router-dom";+import { useQuery } from "@tanstack/react-query";+import { AutopilotDetailPage as AutopilotDetail } from "@multica/views/autopilots/components";+import { useWorkspaceId } from "@multica/core/hooks";+import { autopilotDetailOptions } from "@multica/core/autopilots/queries";+import { useDocumentTitle } from "@/hooks/use-document-title";++export function AutopilotDetailPage() {+ const { id } = useParams<{ id: string }>();+ const wsId = useWorkspaceId();+ const { data } = useQuery(autopilotDetailOptions(wsId, id!));++ useDocumentTitle(data ? `⚡ ${data.autopilot.title}` : "Autopilot");++ if (!id) return null;+ return <AutopilotDetail autopilotId={id} />;+}diff --git a/apps/desktop/src/renderer/src/routes.tsx b/apps/desktop/src/renderer/src/routes.tsxindex 0c5d76061f..33431f4c34 100644--- a/apps/desktop/src/renderer/src/routes.tsx+++ b/apps/desktop/src/renderer/src/routes.tsx@@ -8,8 +8,10 @@ import {import type { RouteObject } from "react-router-dom";import { IssueDetailPage } from "./pages/issue-detail-page";import { ProjectDetailPage } from "./pages/project-detail-page";+import { AutopilotDetailPage } from "./pages/autopilot-detail-page";import { IssuesPage } from "@multica/views/issues/components";import { ProjectsPage } from "@multica/views/projects/components";+import { AutopilotsPage } from "@multica/views/autopilots/components";import { MyIssuesPage } from "@multica/views/my-issues";import { RuntimesPage } from "@multica/views/runtimes";import { SkillsPage } from "@multica/views/skills";@@ -87,6 +89,16 @@ export const appRoutes: RouteObject[] = [element: <ProjectDetailPage />,handle: { title: "Project" },},+ {+ path: "autopilots",+ element: <AutopilotsPage />,+ handle: { title: "Autopilot" },+ },+ {+ path: "autopilots/:id",+ element: <AutopilotDetailPage />,+ handle: { title: "Autopilot" },+ },{path: "my-issues",element: <MyIssuesPage />,diff --git a/apps/web/app/(dashboard)/autopilots/[id]/page.tsx b/apps/web/app/(dashboard)/autopilots/[id]/page.tsxnew file mode 100644index 0000000000..85b73faabe--- /dev/null+++ b/apps/web/app/(dashboard)/autopilots/[id]/page.tsx@@ -0,0 +1,13 @@+"use client";++import { use } from "react";+import { AutopilotDetailPage } from "@multica/views/autopilots/components";++export default function Page({+ params,+}: {+ params: Promise<{ id: string }>;+}) {+ const { id } = use(params);+ return <AutopilotDetailPage autopilotId={id} />;+}diff --git a/apps/web/app/(dashboard)/autopilots/page.tsx b/apps/web/app/(dashboard)/autopilots/page.tsxnew file mode 100644index 0000000000..8fc168199f--- /dev/null+++ b/apps/web/app/(dashboard)/autopilots/page.tsx@@ -0,0 +1,7 @@+"use client";++import { AutopilotsPage } from "@multica/views/autopilots/components";++export default function Page() {+ return <AutopilotsPage />;+}diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex ca21ea7466..1d10dd81fc 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -32,4 +32,78 @@ describe("ApiClient", () => {});}});++ it("uses the expected HTTP contract for autopilot endpoints", async () => {+ const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(+ new Response(JSON.stringify({ autopilots: [], runs: [], total: 0 }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ ));+ vi.stubGlobal("fetch", fetchMock);++ const client = new ApiClient("https://api.example.test");++ await client.listAutopilots({ status: "active" });+ await client.getAutopilot("ap-1");+ await client.createAutopilot({+ title: "Daily triage",+ assignee_id: "agent-1",+ execution_mode: "create_issue",+ });+ await client.updateAutopilot("ap-1", { status: "paused" });+ await client.deleteAutopilot("ap-1");+ await client.triggerAutopilot("ap-1");+ await client.listAutopilotRuns("ap-1", { limit: 10, offset: 20 });+ await client.createAutopilotTrigger("ap-1", {+ kind: "schedule",+ cron_expression: "0 9 * * *",+ timezone: "UTC",+ });+ await client.updateAutopilotTrigger("ap-1", "tr-1", { enabled: false });+ await client.deleteAutopilotTrigger("ap-1", "tr-1");++ const calls = fetchMock.mock.calls.map(([url, init]) => ({+ url,+ method: init?.method ?? "GET",+ body: init?.body,+ }));++ expect(calls).toMatchObject([+ { url: "https://api.example.test/api/autopilots?status=active", method: "GET" },+ { url: "https://api.example.test/api/autopilots/ap-1", method: "GET" },+ {+ url: "https://api.example.test/api/autopilots",+ method: "POST",+ body: JSON.stringify({+ title: "Daily triage",+ assignee_id: "agent-1",+ execution_mode: "create_issue",+ }),+ },+ {+ url: "https://api.example.test/api/autopilots/ap-1",+ method: "PATCH",+ body: JSON.stringify({ status: "paused" }),+ },+ { url: "https://api.example.test/api/autopilots/ap-1", method: "DELETE" },+ { url: "https://api.example.test/api/autopilots/ap-1/trigger", method: "POST" },+ { url: "https://api.example.test/api/autopilots/ap-1/runs?limit=10&offset=20", method: "GET" },+ {+ url: "https://api.example.test/api/autopilots/ap-1/triggers",+ method: "POST",+ body: JSON.stringify({+ kind: "schedule",+ cron_expression: "0 9 * * *",+ timezone: "UTC",+ }),+ },+ {+ url: "https://api.example.test/api/autopilots/ap-1/triggers/tr-1",+ method: "PATCH",+ body: JSON.stringify({ enabled: false }),+ },+ { url: "https://api.example.test/api/autopilots/ap-1/triggers/tr-1", method: "DELETE" },+ ]);+ });});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex e8ab8bd1c9..2f672f6553 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -53,6 +53,16 @@ import type {PinnedItemType,ReorderPinsRequest,Invitation,+ Autopilot,+ AutopilotTrigger,+ AutopilotRun,+ CreateAutopilotRequest,+ UpdateAutopilotRequest,+ CreateAutopilotTriggerRequest,+ UpdateAutopilotTriggerRequest,+ ListAutopilotsResponse,+ GetAutopilotResponse,+ ListAutopilotRunsResponse,} from "../types";import { type Logger, noopLogger } from "../logger";import { createRequestId } from "../utils";@@ -814,4 +824,62 @@ export class ApiClient {body: JSON.stringify(data),});}++ // Autopilots+ async listAutopilots(params?: { status?: string }): Promise<ListAutopilotsResponse> {+ const search = new URLSearchParams();+ if (params?.status) search.set("status", params.status);+ return this.fetch(`/api/autopilots?${search}`);+ }++ async getAutopilot(id: string): Promise<GetAutopilotResponse> {+ return this.fetch(`/api/autopilots/${id}`);+ }++ async createAutopilot(data: CreateAutopilotRequest): Promise<Autopilot> {+ return this.fetch("/api/autopilots", {+ method: "POST",+ body: JSON.stringify(data),+ });+ }++ async updateAutopilot(id: string, data: UpdateAutopilotRequest): Promise<Autopilot> {+ return this.fetch(`/api/autopilots/${id}`, {+ method: "PATCH",+ body: JSON.stringify(data),+ });+ }++ async deleteAutopilot(id: string): Promise<void> {+ await this.fetch(`/api/autopilots/${id}`, { method: "DELETE" });+ }++ async triggerAutopilot(id: string): Promise<AutopilotRun> {+ return this.fetch(`/api/autopilots/${id}/trigger`, { method: "POST" });+ }++ async listAutopilotRuns(id: string, params?: { limit?: number; offset?: number }): Promise<ListAutopilotRunsResponse> {+ const search = new URLSearchParams();+ if (params?.limit) search.set("limit", params.limit.toString());+ if (params?.offset) search.set("offset", params.offset.toString());+ return this.fetch(`/api/autopilots/${id}/runs?${search}`);+ }++ async createAutopilotTrigger(autopilotId: string, data: CreateAutopilotTriggerRequest): Promise<AutopilotTrigger> {+ return this.fetch(`/api/autopilots/${autopilotId}/triggers`, {+ method: "POST",+ body: JSON.stringify(data),+ });+ }++ async updateAutopilotTrigger(autopilotId: string, triggerId: string, data: UpdateAutopilotTriggerRequest): Promise<AutopilotTrigger> {+ return this.fetch(`/api/autopilots/${autopilotId}/triggers/${triggerId}`, {+ method: "PATCH",+ body: JSON.stringify(data),+ });+ }++ async deleteAutopilotTrigger(autopilotId: string, triggerId: string): Promise<void> {+ await this.fetch(`/api/autopilots/${autopilotId}/triggers/${triggerId}`, { method: "DELETE" });+ }}diff --git a/packages/core/autopilots/index.ts b/packages/core/autopilots/index.tsnew file mode 100644index 0000000000..753ba417b5--- /dev/null+++ b/packages/core/autopilots/index.ts@@ -0,0 +1,10 @@+export { autopilotKeys, autopilotListOptions, autopilotDetailOptions, autopilotRunsOptions } from "./queries";+export {+ useCreateAutopilot,+ useUpdateAutopilot,+ useDeleteAutopilot,+ useTriggerAutopilot,+ useCreateAutopilotTrigger,+ useUpdateAutopilotTrigger,+ useDeleteAutopilotTrigger,+} from "./mutations";diff --git a/packages/core/autopilots/mutations.ts b/packages/core/autopilots/mutations.tsnew file mode 100644index 0000000000..62bc86a887--- /dev/null+++ b/packages/core/autopilots/mutations.ts@@ -0,0 +1,130 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { api } from "../api";+import { autopilotKeys } from "./queries";+import { useWorkspaceId } from "../hooks";+import type {+ CreateAutopilotRequest,+ UpdateAutopilotRequest,+ ListAutopilotsResponse,+ GetAutopilotResponse,+ CreateAutopilotTriggerRequest,+ UpdateAutopilotTriggerRequest,+} from "../types";++export function useCreateAutopilot() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ mutationFn: (data: CreateAutopilotRequest) => api.createAutopilot(data),+ onSuccess: (newAutopilot) => {+ qc.setQueryData<ListAutopilotsResponse>(autopilotKeys.list(wsId), (old) =>+ old && !old.autopilots.some((a) => a.id === newAutopilot.id)+ ? { ...old, autopilots: [...old.autopilots, newAutopilot], total: old.total + 1 }+ : old,+ );+ },+ onSettled: () => {+ qc.invalidateQueries({ queryKey: autopilotKeys.list(wsId) });+ },+ });+}++export function useUpdateAutopilot() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ mutationFn: ({ id, ...data }: { id: string } & UpdateAutopilotRequest) =>+ api.updateAutopilot(id, data),+ onMutate: ({ id, ...data }) => {+ qc.cancelQueries({ queryKey: autopilotKeys.list(wsId) });+ const prevList = qc.getQueryData<ListAutopilotsResponse>(autopilotKeys.list(wsId));+ const prevDetail = qc.getQueryData<GetAutopilotResponse>(autopilotKeys.detail(wsId, id));+ qc.setQueryData<ListAutopilotsResponse>(autopilotKeys.list(wsId), (old) =>+ old ? { ...old, autopilots: old.autopilots.map((a) => (a.id === id ? { ...a, ...data } : a)) } : old,+ );+ qc.setQueryData<GetAutopilotResponse>(autopilotKeys.detail(wsId, id), (old) =>+ old ? { ...old, autopilot: { ...old.autopilot, ...data } } : old,+ );+ return { prevList, prevDetail, id };+ },+ onError: (_err, _vars, ctx) => {+ if (ctx?.prevList) qc.setQueryData(autopilotKeys.list(wsId), ctx.prevList);+ if (ctx?.prevDetail) qc.setQueryData(autopilotKeys.detail(wsId, ctx.id), ctx.prevDetail);+ },+ onSettled: (_data, _err, vars) => {+ qc.invalidateQueries({ queryKey: autopilotKeys.detail(wsId, vars.id) });+ qc.invalidateQueries({ queryKey: autopilotKeys.list(wsId) });+ },+ });+}++export function useDeleteAutopilot() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ mutationFn: (id: string) => api.deleteAutopilot(id),+ onMutate: async (id) => {+ await qc.cancelQueries({ queryKey: autopilotKeys.list(wsId) });+ const prevList = qc.getQueryData<ListAutopilotsResponse>(autopilotKeys.list(wsId));+ qc.setQueryData<ListAutopilotsResponse>(autopilotKeys.list(wsId), (old) =>+ old ? { ...old, autopilots: old.autopilots.filter((a) => a.id !== id), total: old.total - 1 } : old,+ );+ qc.removeQueries({ queryKey: autopilotKeys.detail(wsId, id) });+ return { prevList };+ },+ onError: (_err, _id, ctx) => {+ if (ctx?.prevList) qc.setQueryData(autopilotKeys.list(wsId), ctx.prevList);+ },+ onSettled: () => {+ qc.invalidateQueries({ queryKey: autopilotKeys.list(wsId) });+ },+ });+}++export function useTriggerAutopilot() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ mutationFn: (id: string) => api.triggerAutopilot(id),+ onSettled: (_data, _err, id) => {+ qc.invalidateQueries({ queryKey: autopilotKeys.runs(wsId, id) });+ qc.invalidateQueries({ queryKey: autopilotKeys.detail(wsId, id) });+ },+ });+}++export function useCreateAutopilotTrigger() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ mutationFn: ({ autopilotId, ...data }: { autopilotId: string } & CreateAutopilotTriggerRequest) =>+ api.createAutopilotTrigger(autopilotId, data),+ onSettled: (_data, _err, vars) => {+ qc.invalidateQueries({ queryKey: autopilotKeys.detail(wsId, vars.autopilotId) });+ },+ });+}++export function useUpdateAutopilotTrigger() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ mutationFn: ({ autopilotId, triggerId, ...data }: { autopilotId: string; triggerId: string } & UpdateAutopilotTriggerRequest) =>+ api.updateAutopilotTrigger(autopilotId, triggerId, data),+ onSettled: (_data, _err, vars) => {+ qc.invalidateQueries({ queryKey: autopilotKeys.detail(wsId, vars.autopilotId) });+ },+ });+}++export function useDeleteAutopilotTrigger() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ mutationFn: ({ autopilotId, triggerId }: { autopilotId: string; triggerId: string }) =>+ api.deleteAutopilotTrigger(autopilotId, triggerId),+ onSettled: (_data, _err, vars) => {+ qc.invalidateQueries({ queryKey: autopilotKeys.detail(wsId, vars.autopilotId) });+ },+ });+}diff --git a/packages/core/autopilots/queries.ts b/packages/core/autopilots/queries.tsnew file mode 100644index 0000000000..17235b5bdd--- /dev/null+++ b/packages/core/autopilots/queries.ts@@ -0,0 +1,34 @@+import { queryOptions } from "@tanstack/react-query";+import { api } from "../api";++export const autopilotKeys = {+ all: (wsId: string) => ["autopilots", wsId] as const,+ list: (wsId: string) => [...autopilotKeys.all(wsId), "list"] as const,+ detail: (wsId: string, id: string) =>+ [...autopilotKeys.all(wsId), "detail", id] as const,+ runs: (wsId: string, id: string) =>+ [...autopilotKeys.all(wsId), "runs", id] as const,+};++export function autopilotListOptions(wsId: string) {+ return queryOptions({+ queryKey: autopilotKeys.list(wsId),+ queryFn: () => api.listAutopilots(),+ select: (data) => data.autopilots,+ });+}++export function autopilotDetailOptions(wsId: string, id: string) {+ return queryOptions({+ queryKey: autopilotKeys.detail(wsId, id),+ queryFn: () => api.getAutopilot(id),+ });+}++export function autopilotRunsOptions(wsId: string, id: string) {+ return queryOptions({+ queryKey: autopilotKeys.runs(wsId, id),+ queryFn: () => api.listAutopilotRuns(id),+ select: (data) => data.runs,+ });+}diff --git a/packages/core/package.json b/packages/core/package.jsonindex 22ed5246aa..706784cab3 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -45,6 +45,9 @@"./projects/queries": "./projects/queries.ts","./projects/mutations": "./projects/mutations.ts","./projects/config": "./projects/config.ts",+ "./autopilots": "./autopilots/index.ts",+ "./autopilots/queries": "./autopilots/queries.ts",+ "./autopilots/mutations": "./autopilots/mutations.ts","./pins": "./pins/index.ts","./pins/queries": "./pins/queries.ts","./pins/mutations": "./pins/mutations.ts",diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 3108207b2e..f6d3babc52 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -12,6 +12,7 @@ import { defaultStorage } from "../platform/storage";import { issueKeys } from "../issues/queries";import { projectKeys } from "../projects/queries";import { pinKeys } from "../pins/queries";+import { autopilotKeys } from "../autopilots/queries";import { runtimeKeys } from "../runtimes/queries";import {onIssueCreated,@@ -117,6 +118,10 @@ export function useRealtimeSync(const wsId = workspaceStore.getState().workspace?.id;if (wsId) qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });},+ autopilot: () => {+ const wsId = workspaceStore.getState().workspace?.id;+ if (wsId) qc.invalidateQueries({ queryKey: autopilotKeys.all(wsId) });+ },};const timers = new Map<string, ReturnType<typeof setTimeout>>();@@ -470,6 +475,7 @@ export function useRealtimeSync(qc.invalidateQueries({ queryKey: workspaceKeys.skills(wsId) });qc.invalidateQueries({ queryKey: projectKeys.all(wsId) });qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });+ qc.invalidateQueries({ queryKey: autopilotKeys.all(wsId) });}qc.invalidateQueries({ queryKey: workspaceKeys.list() });} catch (e) {diff --git a/packages/core/types/autopilot.ts b/packages/core/types/autopilot.tsnew file mode 100644index 0000000000..86c96ca9d4--- /dev/null+++ b/packages/core/types/autopilot.ts@@ -0,0 +1,113 @@+export type AutopilotStatus = "active" | "paused" | "archived";++export type AutopilotExecutionMode = "create_issue" | "run_only";++export type AutopilotConcurrencyPolicy = "skip" | "queue" | "replace";++export type AutopilotTriggerKind = "schedule" | "webhook" | "api";++export type AutopilotRunStatus = "pending" | "issue_created" | "running" | "skipped" | "completed" | "failed";++export type AutopilotRunSource = "schedule" | "manual" | "webhook" | "api";++export interface Autopilot {+ id: string;+ workspace_id: string;+ project_id: string | null;+ title: string;+ description: string | null;+ assignee_id: string;+ priority: string;+ status: AutopilotStatus;+ execution_mode: AutopilotExecutionMode;+ issue_title_template: string | null;+ concurrency_policy: AutopilotConcurrencyPolicy;+ created_by_type: string;+ created_by_id: string;+ last_run_at: string | null;+ created_at: string;+ updated_at: string;+}++export interface AutopilotTrigger {+ id: string;+ autopilot_id: string;+ kind: AutopilotTriggerKind;+ enabled: boolean;+ cron_expression: string | null;+ timezone: string | null;+ next_run_at: string | null;+ webhook_token: string | null;+ label: string | null;+ last_fired_at: string | null;+ created_at: string;+ updated_at: string;+}++export interface AutopilotRun {+ id: string;+ autopilot_id: string;+ trigger_id: string | null;+ source: AutopilotRunSource;+ status: AutopilotRunStatus;+ issue_id: string | null;+ task_id: string | null;+ triggered_at: string;+ completed_at: string | null;+ failure_reason: string | null;+ trigger_payload: unknown;+ result: unknown;+ created_at: string;+}++export interface CreateAutopilotRequest {+ title: string;+ description?: string;+ assignee_id: string;+ project_id?: string;+ priority?: string;+ execution_mode: AutopilotExecutionMode;+ concurrency_policy?: AutopilotConcurrencyPolicy;+ issue_title_template?: string;+}++export interface UpdateAutopilotRequest {+ title?: string;+ description?: string | null;+ assignee_id?: string;+ project_id?: string | null;+ priority?: string;+ status?: AutopilotStatus;+ execution_mode?: AutopilotExecutionMode;+ concurrency_policy?: AutopilotConcurrencyPolicy;+ issue_title_template?: string | null;+}++export interface CreateAutopilotTriggerRequest {+ kind: AutopilotTriggerKind;+ cron_expression?: string;+ timezone?: string;+ label?: string;+}++export interface UpdateAutopilotTriggerRequest {+ enabled?: boolean;+ cron_expression?: string;+ timezone?: string;+ label?: string;+}++export interface ListAutopilotsResponse {+ autopilots: Autopilot[];+ total: number;+}++export interface GetAutopilotResponse {+ autopilot: Autopilot;+ triggers: AutopilotTrigger[];+}++export interface ListAutopilotRunsResponse {+ runs: AutopilotRun[];+ total: number;+}diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 5cac45d092..28e81ccbe4 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -34,3 +34,21 @@ export type { ChatSession, ChatMessage, ChatPendingTask, PendingChatTaskItem, Peexport type { StorageAdapter } from "./storage";export type { Project, ProjectStatus, ProjectPriority, CreateProjectRequest, UpdateProjectRequest, ListProjectsResponse } from "./project";export type { PinnedItem, PinnedItemType, CreatePinRequest, ReorderPinsRequest } from "./pin";+export type {+ Autopilot,+ AutopilotStatus,+ AutopilotExecutionMode,+ AutopilotConcurrencyPolicy,+ AutopilotTrigger,+ AutopilotTriggerKind,+ AutopilotRun,+ AutopilotRunStatus,+ AutopilotRunSource,+ CreateAutopilotRequest,+ UpdateAutopilotRequest,+ CreateAutopilotTriggerRequest,+ UpdateAutopilotTriggerRequest,+ ListAutopilotsResponse,+ GetAutopilotResponse,+ ListAutopilotRunsResponse,+} from "./autopilot";diff --git a/packages/views/autopilots/components/autopilot-detail-page.tsx b/packages/views/autopilots/components/autopilot-detail-page.tsxnew file mode 100644index 0000000000..e0ace0128f--- /dev/null+++ b/packages/views/autopilots/components/autopilot-detail-page.tsx@@ -0,0 +1,558 @@+"use client";++import { useState, useEffect } from "react";+import { Zap, Play, Pause, Clock, Plus, Trash2, CheckCircle2, XCircle, SkipForward, Loader2, Pencil } from "lucide-react";+import { useQuery } from "@tanstack/react-query";+import { autopilotDetailOptions, autopilotRunsOptions } from "@multica/core/autopilots/queries";+import {+ useUpdateAutopilot,+ useDeleteAutopilot,+ useTriggerAutopilot,+ useCreateAutopilotTrigger,+ useDeleteAutopilotTrigger,+} from "@multica/core/autopilots/mutations";+import { agentListOptions } from "@multica/core/workspace/queries";+import { useWorkspaceId } from "@multica/core/hooks";+import { useActorName } from "@multica/core/workspace/hooks";+import { useNavigation, AppLink } from "../../navigation";+import { ActorAvatar } from "../../common/actor-avatar";+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 type { AutopilotRun, AutopilotTrigger } from "@multica/core/types";++function formatDate(date: string): string {+ return new Date(date).toLocaleString(undefined, {+ month: "short",+ day: "numeric",+ hour: "2-digit",+ minute: "2-digit",+ });+}++const RUN_STATUS_CONFIG: Record<string, { label: string; color: string; icon: typeof CheckCircle2 }> = {+ pending: { label: "Pending", color: "text-blue-500", icon: Clock },+ issue_created: { label: "Issue Created", color: "text-blue-500", icon: Clock },+ running: { label: "Running", color: "text-blue-500", icon: Loader2 },+ completed: { label: "Completed", color: "text-emerald-500", icon: CheckCircle2 },+ failed: { label: "Failed", color: "text-destructive", icon: XCircle },+ skipped: { label: "Skipped", color: "text-muted-foreground", icon: SkipForward },+};++function RunRow({ run }: { run: AutopilotRun }) {+ const cfg = (RUN_STATUS_CONFIG[run.status] ?? RUN_STATUS_CONFIG["pending"])!;+ const StatusIcon = cfg.icon;++ return (+ <div className="flex items-center gap-3 px-4 py-2.5 text-sm hover:bg-accent/30 transition-colors">+ <StatusIcon className={cn("h-4 w-4 shrink-0", cfg.color)} />+ <span className={cn("w-24 shrink-0 text-xs font-medium", cfg.color)}>{cfg.label}</span>+ <span className="w-16 shrink-0 text-xs text-muted-foreground capitalize">{run.source}</span>+ <span className="flex-1 min-w-0 text-xs text-muted-foreground truncate">+ {run.issue_id ? (+ <AppLink href={`/issues/${run.issue_id}`} className="hover:underline">+ Issue linked+ </AppLink>+ ) : run.failure_reason ? (+ <span className="text-destructive">{run.failure_reason}</span>+ ) : null}+ </span>+ <span className="w-32 shrink-0 text-right text-xs text-muted-foreground tabular-nums">+ {formatDate(run.triggered_at || run.created_at)}+ </span>+ </div>+ );+}++function TriggerRow({ trigger, autopilotId }: { trigger: AutopilotTrigger; autopilotId: string }) {+ const deleteTrigger = useDeleteAutopilotTrigger();++ return (+ <div className="flex items-center gap-3 rounded-md border px-3 py-2">+ <Clock className="h-4 w-4 shrink-0 text-muted-foreground" />+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium capitalize">{trigger.kind}</span>+ {trigger.label && (+ <span className="text-xs text-muted-foreground">({trigger.label})</span>+ )}+ {!trigger.enabled && (+ <span className="text-xs bg-muted px-1.5 py-0.5 rounded">Disabled</span>+ )}+ </div>+ {trigger.cron_expression && (+ <div className="text-xs text-muted-foreground mt-0.5">+ {trigger.cron_expression}+ {trigger.timezone && ` (${trigger.timezone})`}+ </div>+ )}+ {trigger.next_run_at && (+ <div className="text-xs text-muted-foreground">+ Next: {formatDate(trigger.next_run_at)}+ </div>+ )}+ </div>+ <Button+ size="icon"+ variant="ghost"+ className="h-7 w-7 shrink-0"+ onClick={() => {+ deleteTrigger.mutate({ autopilotId, triggerId: trigger.id });+ toast.success("Trigger deleted");+ }}+ >+ <Trash2 className="h-3.5 w-3.5 text-muted-foreground" />+ </Button>+ </div>+ );+}++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,+ autopilotId,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ autopilotId: string;+}) {+ const createTrigger = useCreateAutopilotTrigger();+ const [config, setConfig] = useState<TriggerConfig>(getDefaultTriggerConfig);+ const [label, setLabel] = useState("");+ const [submitting, setSubmitting] = useState(false);++ const handleSubmit = async () => {+ if (submitting) return;+ const cronExpr = toCronExpression(config);+ if (!cronExpr.trim()) return;+ setSubmitting(true);+ try {+ await createTrigger.mutateAsync({+ autopilotId,+ kind: "schedule",+ cron_expression: cronExpr,+ timezone: config.timezone || undefined,+ label: label.trim() || undefined,+ });+ onOpenChange(false);+ setConfig(getDefaultTriggerConfig());+ setLabel("");+ toast.success("Trigger added");+ } catch {+ toast.error("Failed to add trigger");+ } finally {+ setSubmitting(false);+ }+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-sm">+ <DialogTitle>Add Trigger</DialogTitle>+ <div className="space-y-4 pt-2">+ <TriggerConfigSection config={config} onChange={setConfig} />+ <div>+ <label className="text-xs font-medium text-muted-foreground">Label (optional)</label>+ <input+ type="text"+ value={label}+ onChange={(e) => setLabel(e.target.value)}+ placeholder="e.g. Weekday morning"+ className="mt-1 w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring"+ />+ </div>+ <div className="flex justify-end pt-1">+ <Button size="sm" onClick={handleSubmit} disabled={submitting}>+ {submitting ? "Adding..." : "Add trigger"}+ </Button>+ </div>+ </div>+ </DialogContent>+ </Dialog>+ );+}++export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {+ const wsId = useWorkspaceId();+ const router = useNavigation();+ const { getActorName } = useActorName();++ 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();++ const [triggerDialogOpen, setTriggerDialogOpen] = useState(false);+ const [editDialogOpen, setEditDialogOpen] = useState(false);++ if (isLoading) {+ return (+ <div className="p-6 space-y-4">+ <Skeleton className="h-8 w-64" />+ <Skeleton className="h-40 w-full" />+ </div>+ );+ }++ if (!data) {+ return (+ <div className="flex items-center justify-center h-full text-muted-foreground">+ Autopilot not found+ </div>+ );+ }++ const { autopilot, triggers } = data;++ const handleRunNow = async () => {+ try {+ await triggerAutopilot.mutateAsync(autopilotId);+ toast.success("Autopilot triggered");+ } catch (e: any) {+ toast.error(e?.message || "Failed to trigger autopilot");+ }+ };++ const handleDelete = async () => {+ try {+ await deleteAutopilot.mutateAsync(autopilotId);+ toast.success("Autopilot deleted");+ router.push("/autopilots");+ } catch {+ toast.error("Failed to delete autopilot");+ }+ };++ const handleToggleStatus = () => {+ const newStatus = autopilot.status === "active" ? "paused" : "active";+ updateAutopilot.mutate({ id: autopilotId, status: newStatus });+ };++ return (+ <div className="flex h-full flex-col">+ {/* Header */}+ <div className="flex h-12 shrink-0 items-center justify-between border-b px-5">+ <div className="flex items-center gap-2">+ <AppLink href="/autopilots" className="text-muted-foreground hover:text-foreground transition-colors">+ <Zap className="h-4 w-4" />+ </AppLink>+ <span className="text-muted-foreground">/</span>+ <h1 className="text-sm font-medium truncate">{autopilot.title}</h1>+ <span className={cn(+ "ml-1 inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs font-medium",+ autopilot.status === "active" ? "bg-emerald-500/10 text-emerald-500" :+ autopilot.status === "paused" ? "bg-amber-500/10 text-amber-500" :+ "bg-muted text-muted-foreground",+ )}>+ {autopilot.status}+ </span>+ </div>+ <div className="flex items-center gap-2">+ <Button size="sm" variant="outline" onClick={() => setEditDialogOpen(true)}>+ <Pencil className="h-3.5 w-3.5 mr-1" />+ Edit+ </Button>+ <Button size="sm" variant="outline" onClick={handleToggleStatus}>+ {autopilot.status === "active" ? (+ <><Pause className="h-3.5 w-3.5 mr-1" /> Pause</>+ ) : (+ <><Play className="h-3.5 w-3.5 mr-1" /> Activate</>+ )}+ </Button>+ <Button size="sm" onClick={handleRunNow} disabled={autopilot.status !== "active" || triggerAutopilot.isPending}>+ <Play className="h-3.5 w-3.5 mr-1" />+ {triggerAutopilot.isPending ? "Running..." : "Run now"}+ </Button>+ </div>+ </div>++ <div className="flex-1 overflow-y-auto">+ <div className="max-w-4xl mx-auto p-6 space-y-8">+ {/* Properties */}+ <section className="space-y-4">+ <h2 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">Properties</h2>+ <div className="grid grid-cols-2 gap-4 text-sm">+ <div>+ <label className="text-xs text-muted-foreground">Agent</label>+ <div className="mt-1 flex items-center gap-2">+ <ActorAvatar actorType="agent" actorId={autopilot.assignee_id} size={20} />+ <span>{getActorName("agent", autopilot.assignee_id)}</span>+ </div>+ </div>+ <div>+ <label className="text-xs text-muted-foreground">Priority</label>+ <div className="mt-1 capitalize">{autopilot.priority}</div>+ </div>+ <div>+ <label className="text-xs text-muted-foreground">Execution Mode</label>+ <div className="mt-1">+ {autopilot.execution_mode === "create_issue" ? "Create Issue" : "Run Only"}+ </div>+ </div>+ <div>+ <label className="text-xs text-muted-foreground">Concurrency</label>+ <div className="mt-1 capitalize">{autopilot.concurrency_policy}</div>+ </div>+ {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>+ )}+ </div>+ </section>++ {/* Triggers */}+ <section className="space-y-3">+ <div className="flex items-center justify-between">+ <h2 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">Triggers</h2>+ <Button size="sm" variant="outline" onClick={() => setTriggerDialogOpen(true)}>+ <Plus className="h-3.5 w-3.5 mr-1" />+ Add trigger+ </Button>+ </div>+ {triggers.length === 0 ? (+ <div className="rounded-md border border-dashed p-4 text-center text-sm text-muted-foreground">+ No triggers configured. Add a schedule to run automatically.+ </div>+ ) : (+ <div className="space-y-2">+ {triggers.map((t) => (+ <TriggerRow key={t.id} trigger={t} autopilotId={autopilotId} />+ ))}+ </div>+ )}+ </section>++ {/* Run History */}+ <section className="space-y-3">+ <h2 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">Run History</h2>+ {runsLoading ? (+ <div className="space-y-1">+ {Array.from({ length: 3 }).map((_, i) => (+ <Skeleton key={i} className="h-10 w-full" />+ ))}+ </div>+ ) : runs.length === 0 ? (+ <div className="rounded-md border border-dashed p-4 text-center text-sm text-muted-foreground">+ No runs yet. Click "Run now" to trigger manually.+ </div>+ ) : (+ <div className="rounded-md border overflow-hidden">+ {runs.map((run) => (+ <RunRow key={run.id} run={run} />+ ))}+ </div>+ )}+ </section>++ {/* Danger zone */}+ <section className="space-y-3 pt-4 border-t">+ <h2 className="text-sm font-medium text-destructive uppercase tracking-wider">Danger Zone</h2>+ <Button size="sm" variant="destructive" onClick={handleDelete}>+ <Trash2 className="h-3.5 w-3.5 mr-1" />+ Delete autopilot+ </Button>+ </section>+ </div>+ </div>++ <AddTriggerDialog+ open={triggerDialogOpen}+ onOpenChange={setTriggerDialogOpen}+ autopilotId={autopilotId}+ />+ <EditAutopilotDialog+ open={editDialogOpen}+ onOpenChange={setEditDialogOpen}+ autopilot={autopilot}+ agents={agents}+ />+ </div>+ );+}diff --git a/packages/views/autopilots/components/autopilots-page.tsx b/packages/views/autopilots/components/autopilots-page.tsxnew file mode 100644index 0000000000..771c955e3a--- /dev/null+++ b/packages/views/autopilots/components/autopilots-page.tsx@@ -0,0 +1,424 @@+"use client";++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 { useActorName } from "@multica/core/workspace/hooks";+import { AppLink } from "../../navigation";+import { ActorAvatar } from "../../common/actor-avatar";+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 type { Autopilot } from "@multica/core/types";+import type { TriggerFrequency } from "./trigger-config";++interface AutopilotTemplate {+ title: string;+ prompt: string;+ summary: string;+ icon: typeof Zap;+ frequency: TriggerFrequency;+ time: string;+}++const TEMPLATES: AutopilotTemplate[] = [+ {+ title: "Daily news digest",+ summary: "Search and summarize today's news for the team",+ prompt: `1. Search the web for news and announcements published today only (strictly today's date)+2. Filter for topics relevant to our team and industry+3. For each item, write a short summary including: title, source, key takeaways+4. Compile everything into a single digest post+5. Post the digest as a comment on this issue and @mention all workspace members`,+ icon: Newspaper,+ frequency: "daily",+ time: "09:00",+ },+ {+ title: "PR review reminder",+ summary: "Flag stale pull requests that need review",+ prompt: `1. List all open pull requests in the repository+2. Identify PRs that have been open for more than 24 hours without a review+3. For each stale PR, note the author, age, and a one-line summary of the change+4. Post a comment on this issue listing all stale PRs with links+5. @mention the team to remind them to review`,+ icon: GitPullRequest,+ frequency: "weekdays",+ time: "10:00",+ },+ {+ title: "Bug triage",+ summary: "Assess and prioritize new bug reports",+ prompt: `1. List all issues with status "triage" or "backlog" that have not been prioritized+2. For each issue, read the description and any attached logs or screenshots+3. Assess severity (critical / high / medium / low) based on user impact and scope+4. Set the priority field on the issue accordingly+5. Add a comment explaining your assessment and suggested next steps`,+ icon: Bug,+ frequency: "weekdays",+ time: "09:00",+ },+ {+ title: "Weekly progress report",+ summary: "Compile a weekly summary of team progress",+ prompt: `1. Gather all issues completed (status "done") in the past 7 days+2. Gather all issues currently in progress+3. Identify any blocked issues and their blockers+4. Calculate key metrics: issues closed, issues opened, net change+5. Write a structured weekly report with sections: Completed, In Progress, Blocked, Metrics+6. Post the report as a comment on this issue`,+ icon: BarChart3,+ frequency: "weekly",+ time: "17:00",+ },+ {+ title: "Dependency audit",+ summary: "Scan for security vulnerabilities and outdated packages",+ prompt: `1. Run dependency audit tools on the project (npm audit, go vuln check, etc.)+2. Identify any packages with known security vulnerabilities+3. List outdated packages that are more than 2 major versions behind+4. For each finding, note the severity, affected package, and recommended fix+5. Post a summary report as a comment with actionable items`,+ icon: Shield,+ frequency: "weekly",+ time: "08:00",+ },+ {+ title: "Documentation check",+ summary: "Review recent changes for documentation gaps",+ prompt: `1. List all code changes merged in the past 7 days (via git log)+2. For each significant change, check if related documentation was updated+3. Identify any new APIs, config options, or features missing documentation+4. Create a list of documentation gaps with file paths and suggested content+5. Post the findings as a comment on this issue`,+ icon: FileSearch,+ frequency: "weekly",+ time: "14:00",+ },+];++function formatRelativeDate(date: string): string {+ const diff = Date.now() - new Date(date).getTime();+ const days = Math.floor(diff / (1000 * 60 * 60 * 24));+ if (days < 1) return "Today";+ if (days === 1) return "1d ago";+ if (days < 30) return `${days}d ago`;+ const months = Math.floor(days / 30);+ return `${months}mo ago`;+}++const STATUS_CONFIG: Record<string, { label: string; color: string; icon: typeof Zap }> = {+ active: { label: "Active", color: "text-emerald-500", icon: Play },+ paused: { label: "Paused", color: "text-amber-500", icon: Pause },+ archived: { label: "Archived", color: "text-muted-foreground", icon: AlertCircle },+};++const EXECUTION_MODE_LABELS: Record<string, string> = {+ create_issue: "Create Issue",+ run_only: "Run Only",+};++function AutopilotRow({ autopilot }: { autopilot: Autopilot }) {+ const { getActorName } = useActorName();+ const statusCfg = (STATUS_CONFIG[autopilot.status] ?? STATUS_CONFIG["active"])!;+ const StatusIcon = statusCfg.icon;++ return (+ <div className="group/row flex h-11 items-center gap-2 px-5 text-sm transition-colors hover:bg-accent/40">+ <AppLink+ href={`/autopilots/${autopilot.id}`}+ className="flex min-w-0 flex-1 items-center gap-2"+ >+ <Zap className="h-4 w-4 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1 truncate font-medium">{autopilot.title}</span>+ </AppLink>++ {/* Agent */}+ <span className="flex w-32 items-center gap-1.5 shrink-0">+ <ActorAvatar actorType="agent" actorId={autopilot.assignee_id} size={18} />+ <span className="truncate text-xs text-muted-foreground">+ {getActorName("agent", autopilot.assignee_id)}+ </span>+ </span>++ {/* Mode */}+ <span className="w-24 shrink-0 text-center text-xs text-muted-foreground">+ {EXECUTION_MODE_LABELS[autopilot.execution_mode] ?? autopilot.execution_mode}+ </span>++ {/* Status */}+ <span className={cn("flex w-20 items-center justify-center gap-1 shrink-0 text-xs", statusCfg.color)}>+ <StatusIcon className="h-3 w-3" />+ {statusCfg.label}+ </span>++ {/* Last run */}+ <span className="w-20 shrink-0 text-right text-xs text-muted-foreground tabular-nums">+ {autopilot.last_run_at ? formatRelativeDate(autopilot.last_run_at) : "--"}+ </span>+ </div>+ );+}++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",+ concurrency_policy: "skip",+ });++ // 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));+ const [createOpen, setCreateOpen] = useState(false);+ const [selectedTemplate, setSelectedTemplate] = useState<AutopilotTemplate | null>(null);++ const openCreate = (template?: AutopilotTemplate) => {+ setSelectedTemplate(template ?? null);+ setCreateOpen(true);+ };++ return (+ <div className="flex h-full flex-col">+ {/* Header */}+ <div className="flex h-12 shrink-0 items-center justify-between border-b px-5">+ <div className="flex items-center gap-2">+ <Zap className="h-4 w-4 text-muted-foreground" />+ <h1 className="text-sm font-medium">Autopilot</h1>+ {!isLoading && autopilots.length > 0 && (+ <span className="text-xs text-muted-foreground tabular-nums">{autopilots.length}</span>+ )}+ </div>+ <Button size="sm" variant="outline" onClick={() => openCreate()}>+ <Plus className="h-3.5 w-3.5 mr-1" />+ New autopilot+ </Button>+ </div>++ {/* Table */}+ <div className="flex-1 overflow-y-auto">+ {isLoading ? (+ <div className="p-5 space-y-1">+ {Array.from({ length: 4 }).map((_, i) => (+ <Skeleton key={i} className="h-11 w-full" />+ ))}+ </div>+ ) : autopilots.length === 0 ? (+ <div className="flex flex-col items-center py-16 px-5">+ <Zap className="h-10 w-10 mb-3 text-muted-foreground opacity-30" />+ <p className="text-sm text-muted-foreground">No autopilots yet</p>+ <p className="text-xs text-muted-foreground mt-1 mb-6">+ Schedule recurring tasks for your AI agents. Pick a template or start from scratch.+ </p>+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 w-full max-w-3xl">+ {TEMPLATES.map((t) => {+ const Icon = t.icon;+ return (+ <button+ key={t.title}+ type="button"+ className="flex items-start gap-3 rounded-lg border p-3 text-left transition-colors hover:bg-accent/40"+ onClick={() => openCreate(t)}+ >+ <Icon className="h-5 w-5 shrink-0 text-muted-foreground mt-0.5" />+ <div className="min-w-0">+ <div className="text-sm font-medium">{t.title}</div>+ <div className="text-xs text-muted-foreground mt-0.5 line-clamp-2">{t.summary}</div>+ </div>+ </button>+ );+ })}+ </div>+ <Button size="sm" variant="outline" className="mt-4" onClick={() => openCreate()}>+ <Plus className="h-3.5 w-3.5 mr-1" />+ Start from scratch+ </Button>+ </div>+ ) : (+ <>+ {/* Column headers */}+ <div className="sticky top-0 z-[1] flex h-8 items-center gap-2 border-b bg-muted/30 px-5 text-xs font-medium text-muted-foreground">+ <span className="shrink-0 w-4" />+ <span className="min-w-0 flex-1">Name</span>+ <span className="w-32 shrink-0">Agent</span>+ <span className="w-24 text-center shrink-0">Mode</span>+ <span className="w-20 text-center shrink-0">Status</span>+ <span className="w-20 text-right shrink-0">Last run</span>+ </div>+ {autopilots.map((autopilot) => (+ <AutopilotRow key={autopilot.id} autopilot={autopilot} />+ ))}+ </>+ )}+ </div>++ <CreateAutopilotDialog open={createOpen} onOpenChange={setCreateOpen} template={selectedTemplate} />+ </div>+ );+}diff --git a/packages/views/autopilots/components/index.ts b/packages/views/autopilots/components/index.tsnew file mode 100644index 0000000000..543951fad8--- /dev/null+++ b/packages/views/autopilots/components/index.ts@@ -0,0 +1,2 @@+export { AutopilotsPage } from "./autopilots-page";+export { AutopilotDetailPage } from "./autopilot-detail-page";diff --git a/packages/views/autopilots/components/trigger-config.tsx b/packages/views/autopilots/components/trigger-config.tsxnew file mode 100644index 0000000000..a9d827bab7--- /dev/null+++ b/packages/views/autopilots/components/trigger-config.tsx@@ -0,0 +1,284 @@+"use client";++import { useMemo } from "react";+import { cn } from "@multica/ui/lib/utils";+import {+ Select,+ SelectTrigger,+ SelectValue,+ SelectContent,+ SelectItem,+} from "@multica/ui/components/ui/select";++export type TriggerFrequency = "hourly" | "daily" | "weekdays" | "weekly" | "custom";++export interface TriggerConfig {+ frequency: TriggerFrequency;+ time: string; // HH:MM+ dayOfWeek: number; // 0=Sun … 6=Sat+ cronExpression: string; // only used when frequency === "custom"+ timezone: string; // IANA+}++// ---------------------------------------------------------------------------+// Constants+// ---------------------------------------------------------------------------++const FREQUENCIES: { value: TriggerFrequency; label: string }[] = [+ { value: "hourly", label: "Hourly" },+ { value: "daily", label: "Daily" },+ { value: "weekdays", label: "Weekdays" },+ { value: "weekly", label: "Weekly" },+ { value: "custom", label: "Custom" },+];++const DAYS_OF_WEEK = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];++const COMMON_TIMEZONES = [+ "UTC",+ "America/New_York",+ "America/Chicago",+ "America/Denver",+ "America/Los_Angeles",+ "America/Sao_Paulo",+ "Europe/London",+ "Europe/Paris",+ "Europe/Berlin",+ "Europe/Moscow",+ "Asia/Dubai",+ "Asia/Kolkata",+ "Asia/Singapore",+ "Asia/Shanghai",+ "Asia/Tokyo",+ "Asia/Seoul",+ "Australia/Sydney",+ "Pacific/Auckland",+];++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++export function getLocalTimezone(): string {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone;+ } catch {+ return "UTC";+ }+}++function getTimezoneOffset(tz: string): string {+ if (tz === "UTC") return "UTC";+ try {+ const parts = new Intl.DateTimeFormat("en-US", {+ timeZone: tz,+ timeZoneName: "shortOffset",+ }).formatToParts(new Date());+ return parts.find((p) => p.type === "timeZoneName")?.value ?? tz;+ } catch {+ return tz;+ }+}++function getTimezoneLabel(tz: string): string {+ if (tz === "UTC") return "UTC";+ const city = tz.split("/").pop()?.replace(/_/g, " ") ?? tz;+ return `${city} (${getTimezoneOffset(tz)})`;+}++function formatTime12h(time: string): string {+ const [h, m] = time.split(":");+ const hour = parseInt(h ?? "9", 10);+ const min = parseInt(m ?? "0", 10);+ const ampm = hour >= 12 ? "PM" : "AM";+ return `${hour % 12 || 12}:${min.toString().padStart(2, "0")} ${ampm}`;+}++// ---------------------------------------------------------------------------+// Public helpers+// ---------------------------------------------------------------------------++export function getDefaultTriggerConfig(): TriggerConfig {+ return {+ frequency: "daily",+ time: "09:00",+ dayOfWeek: 1,+ cronExpression: "0 9 * * 1-5",+ timezone: getLocalTimezone(),+ };+}++export function toCronExpression(cfg: TriggerConfig): string {+ const [h, m] = cfg.time.split(":");+ const hour = parseInt(h ?? "9", 10);+ const min = parseInt(m ?? "0", 10);+ switch (cfg.frequency) {+ case "hourly":+ return `${min} * * * *`;+ case "daily":+ return `${min} ${hour} * * *`;+ case "weekdays":+ return `${min} ${hour} * * 1-5`;+ case "weekly":+ return `${min} ${hour} * * ${cfg.dayOfWeek}`;+ case "custom":+ return cfg.cronExpression;+ }+}++export function describeTrigger(cfg: TriggerConfig): string {+ const offset = getTimezoneOffset(cfg.timezone);+ switch (cfg.frequency) {+ case "hourly": {+ const min = parseInt(cfg.time.split(":")[1] ?? "0", 10);+ return `Runs every hour at :${min.toString().padStart(2, "0")}`;+ }+ case "daily":+ return `Runs daily at ${formatTime12h(cfg.time)} ${offset}`;+ case "weekdays":+ return `Runs weekdays at ${formatTime12h(cfg.time)} ${offset}`;+ case "weekly":+ return `Runs every ${DAYS_OF_WEEK[cfg.dayOfWeek]} at ${formatTime12h(cfg.time)} ${offset}`;+ case "custom":+ return `Custom schedule: ${cfg.cronExpression}`;+ }+}++// ---------------------------------------------------------------------------+// Component+// ---------------------------------------------------------------------------++export function TriggerConfigSection({+ config,+ onChange,+}: {+ config: TriggerConfig;+ onChange: (config: TriggerConfig) => void;+}) {+ const timezones = useMemo(() => {+ const local = getLocalTimezone();+ const set = new Set(COMMON_TIMEZONES);+ return set.has(local) ? COMMON_TIMEZONES : [local, ...COMMON_TIMEZONES];+ }, []);++ return (+ <div className="space-y-3">+ {/* Frequency tabs */}+ <div className="flex flex-wrap gap-1">+ {FREQUENCIES.map((f) => (+ <button+ key={f.value}+ type="button"+ className={cn(+ "rounded-md px-3 py-1.5 text-xs font-medium transition-colors",+ config.frequency === f.value+ ? "bg-foreground text-background"+ : "bg-muted text-muted-foreground hover:text-foreground",+ )}+ onClick={() => onChange({ ...config, frequency: f.value })}+ >+ {f.label}+ </button>+ ))}+ </div>++ {config.frequency === "custom" ? (+ /* Custom cron input */+ <div>+ <label className="text-xs text-muted-foreground">Cron Expression</label>+ <input+ type="text"+ value={config.cronExpression}+ onChange={(e) => onChange({ ...config, cronExpression: e.target.value })}+ placeholder="0 9 * * 1-5"+ className="mt-1 w-full rounded-md border bg-background px-3 py-2 text-sm font-mono outline-none focus:ring-1 focus:ring-ring"+ />+ <p className="text-xs text-muted-foreground mt-1">+ Standard 5-field cron (min hour dom month dow)+ </p>+ </div>+ ) : (+ <>+ {/* Time + Timezone row */}+ <div className="flex gap-3">+ {config.frequency === "hourly" ? (+ <div className="w-24">+ <label className="text-xs text-muted-foreground">Minute</label>+ <input+ type="number"+ min={0}+ max={59}+ value={parseInt(config.time.split(":")[1] ?? "0", 10)}+ onChange={(e) => {+ const min = Math.max(0, Math.min(59, parseInt(e.target.value) || 0));+ onChange({ ...config, time: `00:${min.toString().padStart(2, "0")}` });+ }}+ className="mt-1 w-full rounded-md border bg-background px-3 py-2 text-sm font-mono outline-none focus:ring-1 focus:ring-ring"+ />+ </div>+ ) : (+ <>+ <div className="w-28">+ <label className="text-xs text-muted-foreground">Time</label>+ <input+ type="time"+ value={config.time}+ onChange={(e) => onChange({ ...config, time: e.target.value || config.time })}+ className="mt-1 w-full rounded-md border bg-background px-3 py-2 text-sm font-mono outline-none focus:ring-1 focus:ring-ring"+ />+ </div>+ <div className="flex-1 min-w-0">+ <label className="text-xs text-muted-foreground">Timezone</label>+ <Select+ value={config.timezone}+ onValueChange={(v) => v && onChange({ ...config, timezone: v })}+ >+ <SelectTrigger className="mt-1 w-full">+ <SelectValue>+ {() => getTimezoneLabel(config.timezone)}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {timezones.map((tz) => (+ <SelectItem key={tz} value={tz}>+ {getTimezoneLabel(tz)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ </>+ )}+ </div>++ {/* Day-of-week selector for weekly */}+ {config.frequency === "weekly" && (+ <div>+ <label className="text-xs text-muted-foreground">Day</label>+ <div className="flex gap-1 mt-1">+ {DAYS_OF_WEEK.map((day, i) => (+ <button+ key={day}+ type="button"+ className={cn(+ "rounded-md px-2.5 py-1 text-xs font-medium transition-colors",+ config.dayOfWeek === i+ ? "bg-foreground text-background"+ : "bg-muted text-muted-foreground hover:text-foreground",+ )}+ onClick={() => onChange({ ...config, dayOfWeek: i })}+ >+ {day}+ </button>+ ))}+ </div>+ </div>+ )}+ </>+ )}++ {/* Human-readable preview */}+ <p className="text-xs text-muted-foreground">{describeTrigger(config)}</p>+ </div>+ );+}diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsxindex fc77e31b72..c1bf4d6104 100644--- a/packages/views/layout/app-sidebar.tsx+++ b/packages/views/layout/app-sidebar.tsx@@ -29,6 +29,7 @@ import {FolderKanban,Ellipsis,PinOff,+ Zap,} from "lucide-react";import { WorkspaceAvatar } from "../workspace/workspace-avatar";import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";@@ -76,6 +77,7 @@ const personalNav = [const workspaceNav = [{ href: "/issues", label: "Issues", icon: ListTodo },{ href: "/projects", label: "Projects", icon: FolderKanban },+ { href: "/autopilots", label: "Autopilot", icon: Zap },{ href: "/agents", label: "Agents", icon: Bot },];diff --git a/packages/views/package.json b/packages/views/package.jsonindex aeb535846f..d28f4a7218 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -19,6 +19,7 @@"./issues/utils/sort": "./issues/utils/sort.ts","./issues/utils/redact": "./issues/utils/redact.ts","./projects/components": "./projects/components/index.ts",+ "./autopilots/components": "./autopilots/components/index.ts","./modals/registry": "./modals/registry.tsx","./modals/create-issue": "./modals/create-issue.tsx","./my-issues": "./my-issues/index.ts",diff --git a/server/cmd/server/autopilot_listeners.go b/server/cmd/server/autopilot_listeners.gonew file mode 100644index 0000000000..e3e328e192--- /dev/null+++ b/server/cmd/server/autopilot_listeners.go@@ -0,0 +1,75 @@+package main++import (+ "context"+ "log/slog"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/handler"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// registerAutopilotListeners hooks into issue and task events to keep+// autopilot runs in sync with their linked issues and tasks.+func registerAutopilotListeners(bus *events.Bus, svc *service.AutopilotService) {+ ctx := context.Background()++ // When an issue with origin_type='autopilot' reaches a terminal status,+ // update the corresponding autopilot run.+ bus.Subscribe(protocol.EventIssueUpdated, func(e events.Event) {+ payload, ok := e.Payload.(map[string]any)+ if !ok {+ return+ }+ statusChanged, _ := payload["status_changed"].(bool)+ if !statusChanged {+ return+ }+ issue, ok := payload["issue"].(handler.IssueResponse)+ if !ok {+ return+ }+ // Only handle terminal statuses.+ if issue.Status != "done" && issue.Status != "cancelled" && issue.Status != "blocked" {+ return+ }+ // Load the full issue from DB to check origin_type.+ dbIssue, err := svc.Queries.GetIssue(ctx, parseUUID(issue.ID))+ if err != nil {+ slog.Debug("autopilot listener: failed to load issue", "issue_id", issue.ID, "error", err)+ return+ }+ svc.SyncRunFromIssue(ctx, dbIssue)+ })++ // When a task completes or fails, check if it's an autopilot run_only task.+ bus.Subscribe(protocol.EventTaskCompleted, func(e events.Event) {+ syncRunFromTaskEvent(ctx, svc, e)+ })+ bus.Subscribe(protocol.EventTaskFailed, func(e events.Event) {+ syncRunFromTaskEvent(ctx, svc, e)+ })+ bus.Subscribe(protocol.EventTaskCancelled, func(e events.Event) {+ syncRunFromTaskEvent(ctx, svc, e)+ })+}++func syncRunFromTaskEvent(ctx context.Context, svc *service.AutopilotService, e events.Event) {+ payload, ok := e.Payload.(map[string]any)+ if !ok {+ return+ }+ taskID, ok := payload["task_id"].(string)+ if !ok || taskID == "" {+ return+ }+ task, err := svc.Queries.GetAgentTask(ctx, parseUUID(taskID))+ if err != nil {+ return+ }+ if !task.AutopilotRunID.Valid {+ return+ }+ svc.SyncRunFromTask(ctx, task)+}diff --git a/server/cmd/server/autopilot_scheduler.go b/server/cmd/server/autopilot_scheduler.gonew file mode 100644index 0000000000..9c74da9515--- /dev/null+++ b/server/cmd/server/autopilot_scheduler.go@@ -0,0 +1,99 @@+package main++import (+ "context"+ "log/slog"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++const schedulerInterval = 30 * time.Second++// runAutopilotScheduler polls for due schedule triggers and dispatches them.+func runAutopilotScheduler(ctx context.Context, queries *db.Queries, svc *service.AutopilotService) {+ ticker := time.NewTicker(schedulerInterval)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ tickScheduledAutopilots(ctx, queries, svc)+ }+ }+}++// tickScheduledAutopilots claims all due triggers and dispatches each one.+func tickScheduledAutopilots(ctx context.Context, queries *db.Queries, svc *service.AutopilotService) {+ triggers, err := queries.ClaimDueScheduleTriggers(ctx)+ if err != nil {+ slog.Warn("autopilot scheduler: failed to claim due triggers", "error", err)+ return+ }+ if len(triggers) == 0 {+ return+ }++ slog.Info("autopilot scheduler: claimed due triggers", "count", len(triggers))++ for _, t := range triggers {+ autopilot, err := queries.GetAutopilot(ctx, t.AutopilotID)+ if err != nil {+ slog.Warn("autopilot scheduler: failed to load autopilot",+ "trigger_id", util.UUIDToString(t.ID),+ "autopilot_id", util.UUIDToString(t.AutopilotID),+ "error", err,+ )+ continue+ }++ // Dispatch the autopilot run.+ if _, err := svc.DispatchAutopilot(ctx, autopilot, t.ID, "schedule", nil); err != nil {+ slog.Warn("autopilot scheduler: dispatch failed",+ "autopilot_id", util.UUIDToString(autopilot.ID),+ "trigger_id", util.UUIDToString(t.ID),+ "error", err,+ )+ }++ // Advance next_run_at for this trigger.+ advanceNextRun(ctx, queries, t)+ }+}++// advanceNextRun computes the next fire time and updates the trigger.+func advanceNextRun(ctx context.Context, queries *db.Queries, t db.ClaimDueScheduleTriggersRow) {+ if !t.CronExpression.Valid || t.CronExpression.String == "" {+ return+ }++ tz := "UTC"+ if t.Timezone.Valid && t.Timezone.String != "" {+ tz = t.Timezone.String+ }++ next, err := service.ComputeNextRun(t.CronExpression.String, tz)+ if err != nil {+ slog.Warn("autopilot scheduler: failed to compute next run",+ "trigger_id", util.UUIDToString(t.ID),+ "cron", t.CronExpression.String,+ "error", err,+ )+ return+ }++ if err := queries.AdvanceTriggerNextRun(ctx, db.AdvanceTriggerNextRunParams{+ ID: t.ID,+ NextRunAt: pgtype.Timestamptz{Time: next, Valid: true},+ }); err != nil {+ slog.Warn("autopilot scheduler: failed to advance next_run_at",+ "trigger_id", util.UUIDToString(t.ID),+ "error", err,+ )+ }+}diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex 6f4ddc64f8..754dd320df 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -14,6 +14,7 @@ import ("github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/logger""github.com/multica-ai/multica/server/internal/realtime"+ "github.com/multica-ai/multica/server/internal/service"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -73,9 +74,16 @@ func main() {Handler: r,}- // Start background sweeper to mark stale runtimes as offline.+ // Start background workers.sweepCtx, sweepCancel := context.WithCancel(context.Background())+ autopilotCtx, autopilotCancel := context.WithCancel(context.Background())+ taskSvc := service.NewTaskService(queries, hub, bus)+ autopilotSvc := service.NewAutopilotService(queries, pool, bus, taskSvc)+ registerAutopilotListeners(bus, autopilotSvc)++ // Start background sweeper to mark stale runtimes as offline.go runRuntimeSweeper(sweepCtx, queries, bus)+ go runAutopilotScheduler(autopilotCtx, queries, autopilotSvc)// Graceful shutdowngo func() {@@ -92,6 +100,7 @@ func main() {slog.Info("shutting down server")sweepCancel()+ autopilotCancel()shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 9e5abe2acc..fed3c63b8e 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -248,6 +248,24 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus) chi.Route})})+ // Autopilots+ r.Route("/api/autopilots", func(r chi.Router) {+ r.Get("/", h.ListAutopilots)+ r.Post("/", h.CreateAutopilot)+ r.Route("/{id}", func(r chi.Router) {+ r.Get("/", h.GetAutopilot)+ r.Patch("/", h.UpdateAutopilot)+ r.Delete("/", h.DeleteAutopilot)+ r.Post("/trigger", h.TriggerAutopilot)+ r.Get("/runs", h.ListAutopilotRuns)+ r.Post("/triggers", h.CreateAutopilotTrigger)+ r.Route("/triggers/{triggerId}", func(r chi.Router) {+ r.Patch("/", h.UpdateAutopilotTrigger)+ r.Delete("/", h.DeleteAutopilotTrigger)+ })+ })+ })+// Pinsr.Route("/api/pins", func(r chi.Router) {r.Get("/", h.ListPins)diff --git a/server/go.mod b/server/go.modindex c46a511cf3..7cc78866c1 100644--- a/server/go.mod+++ b/server/go.mod@@ -42,6 +42,7 @@ require (github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirectgithub.com/jackc/puddle/v2 v2.2.2 // indirectgithub.com/microcosm-cc/bluemonday v1.0.27 // indirect+ github.com/robfig/cron/v3 v3.0.1 // indirectgithub.com/spf13/pflag v1.0.9 // indirectgolang.org/x/net v0.26.0 // indirectgolang.org/x/sync v0.20.0 // indirectdiff --git a/server/go.sum b/server/go.sumindex 815fdc2541..9abc1ab39e 100644--- a/server/go.sum+++ b/server/go.sum@@ -74,6 +74,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbgithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/resend/resend-go/v2 v2.28.0 h1:ttM1/VZR4fApBv3xI1TneSKi1pbfFsVrq7fXFlHKtj4=github.com/resend/resend-go/v2 v2.28.0/go.mod h1:3YCb8c8+pLiqhtRFXTyFwlLvfjQtluxOr9HEh2BwCkQ=+github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=+github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.gonew file mode 100644index 0000000000..19cf9c29d8--- /dev/null+++ b/server/internal/handler/autopilot.go@@ -0,0 +1,683 @@+package handler++import (+ "encoding/json"+ "io"+ "net/http"+ "strconv"+ "time"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// computeNextRun delegates to the shared cron helper in the service package.+func computeNextRun(cronExpr, timezone string) (time.Time, error) {+ return service.ComputeNextRun(cronExpr, timezone)+}++// ── Response types ──────────────────────────────────────────────────────────++type AutopilotResponse struct {+ ID string `json:"id"`+ WorkspaceID string `json:"workspace_id"`+ ProjectID *string `json:"project_id"`+ Title string `json:"title"`+ Description *string `json:"description"`+ AssigneeID string `json:"assignee_id"`+ Priority string `json:"priority"`+ Status string `json:"status"`+ ExecutionMode string `json:"execution_mode"`+ IssueTitleTemplate *string `json:"issue_title_template"`+ ConcurrencyPolicy string `json:"concurrency_policy"`+ CreatedByType string `json:"created_by_type"`+ CreatedByID string `json:"created_by_id"`+ LastRunAt *string `json:"last_run_at"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`+}++type AutopilotTriggerResponse struct {+ ID string `json:"id"`+ AutopilotID string `json:"autopilot_id"`+ Kind string `json:"kind"`+ Enabled bool `json:"enabled"`+ CronExpression *string `json:"cron_expression"`+ Timezone *string `json:"timezone"`+ NextRunAt *string `json:"next_run_at"`+ WebhookToken *string `json:"webhook_token"`+ Label *string `json:"label"`+ LastFiredAt *string `json:"last_fired_at"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`+}++type AutopilotRunResponse struct {+ ID string `json:"id"`+ AutopilotID string `json:"autopilot_id"`+ TriggerID *string `json:"trigger_id"`+ Source string `json:"source"`+ Status string `json:"status"`+ IssueID *string `json:"issue_id"`+ TaskID *string `json:"task_id"`+ TriggeredAt string `json:"triggered_at"`+ CompletedAt *string `json:"completed_at"`+ FailureReason *string `json:"failure_reason"`+ TriggerPayload any `json:"trigger_payload"`+ Result any `json:"result"`+ CreatedAt string `json:"created_at"`+}++// ── Converters ──────────────────────────────────────────────────────────────++func autopilotToResponse(a db.Autopilot) AutopilotResponse {+ return AutopilotResponse{+ ID: uuidToString(a.ID),+ WorkspaceID: uuidToString(a.WorkspaceID),+ ProjectID: uuidToPtr(a.ProjectID),+ Title: a.Title,+ Description: textToPtr(a.Description),+ AssigneeID: uuidToString(a.AssigneeID),+ Priority: a.Priority,+ Status: a.Status,+ ExecutionMode: a.ExecutionMode,+ IssueTitleTemplate: textToPtr(a.IssueTitleTemplate),+ ConcurrencyPolicy: a.ConcurrencyPolicy,+ CreatedByType: a.CreatedByType,+ CreatedByID: uuidToString(a.CreatedByID),+ LastRunAt: timestampToPtr(a.LastRunAt),+ CreatedAt: timestampToString(a.CreatedAt),+ UpdatedAt: timestampToString(a.UpdatedAt),+ }+}++func triggerToResponse(t db.AutopilotTrigger) AutopilotTriggerResponse {+ return AutopilotTriggerResponse{+ ID: uuidToString(t.ID),+ AutopilotID: uuidToString(t.AutopilotID),+ Kind: t.Kind,+ Enabled: t.Enabled,+ CronExpression: textToPtr(t.CronExpression),+ Timezone: textToPtr(t.Timezone),+ NextRunAt: timestampToPtr(t.NextRunAt),+ WebhookToken: textToPtr(t.WebhookToken),+ Label: textToPtr(t.Label),+ LastFiredAt: timestampToPtr(t.LastFiredAt),+ CreatedAt: timestampToString(t.CreatedAt),+ UpdatedAt: timestampToString(t.UpdatedAt),+ }+}++func runToResponse(r db.AutopilotRun) AutopilotRunResponse {+ var payload any+ if r.TriggerPayload != nil {+ json.Unmarshal(r.TriggerPayload, &payload)+ }+ var result any+ if r.Result != nil {+ json.Unmarshal(r.Result, &result)+ }+ return AutopilotRunResponse{+ ID: uuidToString(r.ID),+ AutopilotID: uuidToString(r.AutopilotID),+ TriggerID: uuidToPtr(r.TriggerID),+ Source: r.Source,+ Status: r.Status,+ IssueID: uuidToPtr(r.IssueID),+ TaskID: uuidToPtr(r.TaskID),+ TriggeredAt: timestampToString(r.TriggeredAt),+ CompletedAt: timestampToPtr(r.CompletedAt),+ FailureReason: textToPtr(r.FailureReason),+ TriggerPayload: payload,+ Result: result,+ CreatedAt: timestampToString(r.CreatedAt),+ }+}++// ── Request types ───────────────────────────────────────────────────────────++type CreateAutopilotRequest struct {+ Title string `json:"title"`+ Description *string `json:"description"`+ AssigneeID string `json:"assignee_id"`+ ProjectID *string `json:"project_id"`+ Priority string `json:"priority"`+ ExecutionMode string `json:"execution_mode"`+ ConcurrencyPolicy string `json:"concurrency_policy"`+ IssueTitleTemplate *string `json:"issue_title_template"`+}++type UpdateAutopilotRequest struct {+ Title *string `json:"title"`+ Description *string `json:"description"`+ AssigneeID *string `json:"assignee_id"`+ ProjectID *string `json:"project_id"`+ Priority *string `json:"priority"`+ Status *string `json:"status"`+ ExecutionMode *string `json:"execution_mode"`+ ConcurrencyPolicy *string `json:"concurrency_policy"`+ IssueTitleTemplate *string `json:"issue_title_template"`+}++type CreateAutopilotTriggerRequest struct {+ Kind string `json:"kind"`+ CronExpression *string `json:"cron_expression"`+ Timezone *string `json:"timezone"`+ Label *string `json:"label"`+}++type UpdateAutopilotTriggerRequest struct {+ Enabled *bool `json:"enabled"`+ CronExpression *string `json:"cron_expression"`+ Timezone *string `json:"timezone"`+ Label *string `json:"label"`+}++// ── Handlers ────────────────────────────────────────────────────────────────++func (h *Handler) ListAutopilots(w http.ResponseWriter, r *http.Request) {+ workspaceID := resolveWorkspaceID(r)++ var statusFilter pgtype.Text+ if s := r.URL.Query().Get("status"); s != "" {+ statusFilter = pgtype.Text{String: s, Valid: true}+ }++ autopilots, err := h.Queries.ListAutopilots(r.Context(), db.ListAutopilotsParams{+ WorkspaceID: parseUUID(workspaceID),+ Status: statusFilter,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list autopilots")+ return+ }++ resp := make([]AutopilotResponse, len(autopilots))+ for i, a := range autopilots {+ resp[i] = autopilotToResponse(a)+ }+ writeJSON(w, http.StatusOK, map[string]any{"autopilots": resp, "total": len(resp)})+}++func (h *Handler) GetAutopilot(w http.ResponseWriter, r *http.Request) {+ id := chi.URLParam(r, "id")+ workspaceID := resolveWorkspaceID(r)++ autopilot, err := h.Queries.GetAutopilotInWorkspace(r.Context(), db.GetAutopilotInWorkspaceParams{+ ID: parseUUID(id),+ WorkspaceID: parseUUID(workspaceID),+ })+ if err != nil {+ writeError(w, http.StatusNotFound, "autopilot not found")+ return+ }++ resp := autopilotToResponse(autopilot)++ // Include triggers.+ triggers, err := h.Queries.ListAutopilotTriggers(r.Context(), autopilot.ID)+ if err != nil {+ triggers = nil+ }+ triggerResp := make([]AutopilotTriggerResponse, len(triggers))+ for i, t := range triggers {+ triggerResp[i] = triggerToResponse(t)+ }++ writeJSON(w, http.StatusOK, map[string]any{+ "autopilot": resp,+ "triggers": triggerResp,+ })+}++func (h *Handler) CreateAutopilot(w http.ResponseWriter, r *http.Request) {+ var req CreateAutopilotRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if req.Title == "" {+ writeError(w, http.StatusBadRequest, "title is required")+ return+ }+ if req.AssigneeID == "" {+ writeError(w, http.StatusBadRequest, "assignee_id is required")+ return+ }+ if req.ExecutionMode == "" {+ writeError(w, http.StatusBadRequest, "execution_mode is required")+ return+ }+ if req.ExecutionMode != "create_issue" && req.ExecutionMode != "run_only" {+ writeError(w, http.StatusBadRequest, "execution_mode must be create_issue or run_only")+ return+ }++ workspaceID := resolveWorkspaceID(r)+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }++ // Validate assignee is an agent in the workspace.+ _, err := h.Queries.GetAgentInWorkspace(r.Context(), db.GetAgentInWorkspaceParams{+ ID: parseUUID(req.AssigneeID),+ WorkspaceID: parseUUID(workspaceID),+ })+ if err != nil {+ writeError(w, http.StatusBadRequest, "assignee must be a valid agent in this workspace")+ return+ }++ priority := req.Priority+ if priority == "" {+ priority = "none"+ }+ concurrencyPolicy := req.ConcurrencyPolicy+ if concurrencyPolicy == "" {+ concurrencyPolicy = "skip"+ }++ var projectID pgtype.UUID+ if req.ProjectID != nil {+ projectID = parseUUID(*req.ProjectID)+ }++ autopilot, err := h.Queries.CreateAutopilot(r.Context(), db.CreateAutopilotParams{+ WorkspaceID: parseUUID(workspaceID),+ Title: req.Title,+ AssigneeID: parseUUID(req.AssigneeID),+ Priority: priority,+ Status: "active",+ ExecutionMode: req.ExecutionMode,+ ConcurrencyPolicy: concurrencyPolicy,+ CreatedByType: "member",+ CreatedByID: parseUUID(userID),+ ProjectID: projectID,+ Description: ptrToText(req.Description),+ IssueTitleTemplate: ptrToText(req.IssueTitleTemplate),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to create autopilot")+ return+ }++ resp := autopilotToResponse(autopilot)+ h.publish(protocol.EventAutopilotCreated, workspaceID, "member", userID, map[string]any{"autopilot": resp})+ writeJSON(w, http.StatusCreated, resp)+}++func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {+ id := chi.URLParam(r, "id")+ workspaceID := resolveWorkspaceID(r)++ prev, err := h.Queries.GetAutopilotInWorkspace(r.Context(), db.GetAutopilotInWorkspaceParams{+ ID: parseUUID(id),+ WorkspaceID: parseUUID(workspaceID),+ })+ if err != nil {+ writeError(w, http.StatusNotFound, "autopilot not found")+ return+ }++ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }++ bodyBytes, err := io.ReadAll(r.Body)+ if err != nil {+ writeError(w, http.StatusBadRequest, "failed to read request body")+ return+ }+ var req UpdateAutopilotRequest+ if err := json.Unmarshal(bodyBytes, &req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ var rawFields map[string]json.RawMessage+ json.Unmarshal(bodyBytes, &rawFields)++ params := db.UpdateAutopilotParams{+ ID: prev.ID,+ Description: prev.Description,+ AssigneeID: prev.AssigneeID,+ ProjectID: prev.ProjectID,+ IssueTitleTemplate: prev.IssueTitleTemplate,+ }+ if req.Title != nil {+ params.Title = pgtype.Text{String: *req.Title, Valid: true}+ }+ if req.Priority != nil {+ params.Priority = pgtype.Text{String: *req.Priority, Valid: true}+ }+ if req.Status != nil {+ params.Status = pgtype.Text{String: *req.Status, Valid: true}+ }+ if req.ExecutionMode != nil {+ params.ExecutionMode = pgtype.Text{String: *req.ExecutionMode, Valid: true}+ }+ if req.ConcurrencyPolicy != nil {+ params.ConcurrencyPolicy = pgtype.Text{String: *req.ConcurrencyPolicy, Valid: true}+ }+ if _, ok := rawFields["description"]; ok {+ params.Description = ptrToText(req.Description)+ }+ if _, ok := rawFields["issue_title_template"]; ok {+ params.IssueTitleTemplate = ptrToText(req.IssueTitleTemplate)+ }+ if _, ok := rawFields["assignee_id"]; ok {+ if req.AssigneeID != nil {+ params.AssigneeID = parseUUID(*req.AssigneeID)+ }+ }+ if _, ok := rawFields["project_id"]; ok {+ if req.ProjectID != nil {+ params.ProjectID = parseUUID(*req.ProjectID)+ } else {+ params.ProjectID = pgtype.UUID{Valid: false}+ }+ }++ autopilot, err := h.Queries.UpdateAutopilot(r.Context(), params)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to update autopilot")+ return+ }++ resp := autopilotToResponse(autopilot)+ h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", userID, map[string]any{"autopilot": resp})+ writeJSON(w, http.StatusOK, resp)+}++func (h *Handler) DeleteAutopilot(w http.ResponseWriter, r *http.Request) {+ id := chi.URLParam(r, "id")+ workspaceID := resolveWorkspaceID(r)++ if _, err := h.Queries.GetAutopilotInWorkspace(r.Context(), db.GetAutopilotInWorkspaceParams{+ ID: parseUUID(id),+ WorkspaceID: parseUUID(workspaceID),+ }); err != nil {+ writeError(w, http.StatusNotFound, "autopilot not found")+ return+ }++ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }++ if err := h.Queries.DeleteAutopilot(r.Context(), parseUUID(id)); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to delete autopilot")+ return+ }++ h.publish(protocol.EventAutopilotDeleted, workspaceID, "member", userID, map[string]any{"autopilot_id": id})+ w.WriteHeader(http.StatusNoContent)+}++// ── Trigger management ──────────────────────────────────────────────────────++func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request) {+ autopilotID := chi.URLParam(r, "id")+ workspaceID := resolveWorkspaceID(r)++ ap, err := h.Queries.GetAutopilotInWorkspace(r.Context(), db.GetAutopilotInWorkspaceParams{+ ID: parseUUID(autopilotID),+ WorkspaceID: parseUUID(workspaceID),+ })+ if err != nil {+ writeError(w, http.StatusNotFound, "autopilot not found")+ return+ }++ var req CreateAutopilotTriggerRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if req.Kind == "" {+ writeError(w, http.StatusBadRequest, "kind is required")+ return+ }+ if req.Kind != "schedule" && req.Kind != "webhook" && req.Kind != "api" {+ writeError(w, http.StatusBadRequest, "kind must be schedule, webhook, or api")+ return+ }+ if req.Kind == "schedule" && (req.CronExpression == nil || *req.CronExpression == "") {+ writeError(w, http.StatusBadRequest, "cron_expression is required for schedule triggers")+ return+ }++ var nextRunAt pgtype.Timestamptz+ if req.Kind == "schedule" && req.CronExpression != nil {+ tz := "UTC"+ if req.Timezone != nil && *req.Timezone != "" {+ tz = *req.Timezone+ }+ t, err := computeNextRun(*req.CronExpression, tz)+ if err != nil {+ writeError(w, http.StatusBadRequest, "invalid cron expression: "+err.Error())+ return+ }+ nextRunAt = pgtype.Timestamptz{Time: t, Valid: true}+ }++ trigger, err := h.Queries.CreateAutopilotTrigger(r.Context(), db.CreateAutopilotTriggerParams{+ AutopilotID: ap.ID,+ Kind: req.Kind,+ Enabled: true,+ CronExpression: ptrToText(req.CronExpression),+ Timezone: ptrToText(req.Timezone),+ NextRunAt: nextRunAt,+ Label: ptrToText(req.Label),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to create trigger")+ return+ }++ resp := triggerToResponse(trigger)+ userID, _ := requireUserID(w, r)+ h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", userID, map[string]any{+ "autopilot_id": autopilotID,+ "trigger": resp,+ })+ writeJSON(w, http.StatusCreated, resp)+}++func (h *Handler) UpdateAutopilotTrigger(w http.ResponseWriter, r *http.Request) {+ autopilotID := chi.URLParam(r, "id")+ triggerID := chi.URLParam(r, "triggerId")+ workspaceID := resolveWorkspaceID(r)++ // Verify autopilot belongs to workspace.+ if _, err := h.Queries.GetAutopilotInWorkspace(r.Context(), db.GetAutopilotInWorkspaceParams{+ ID: parseUUID(autopilotID),+ WorkspaceID: parseUUID(workspaceID),+ }); err != nil {+ writeError(w, http.StatusNotFound, "autopilot not found")+ return+ }++ prev, err := h.Queries.GetAutopilotTrigger(r.Context(), parseUUID(triggerID))+ if err != nil || uuidToString(prev.AutopilotID) != autopilotID {+ writeError(w, http.StatusNotFound, "trigger not found")+ return+ }++ var req UpdateAutopilotTriggerRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }++ params := db.UpdateAutopilotTriggerParams{+ ID: prev.ID,+ CronExpression: prev.CronExpression,+ Timezone: prev.Timezone,+ NextRunAt: prev.NextRunAt,+ Label: prev.Label,+ }+ if req.Enabled != nil {+ params.Enabled = pgtype.Bool{Bool: *req.Enabled, Valid: true}+ }+ if req.CronExpression != nil {+ params.CronExpression = pgtype.Text{String: *req.CronExpression, Valid: true}+ }+ if req.Timezone != nil {+ params.Timezone = pgtype.Text{String: *req.Timezone, Valid: true}+ }+ if req.Label != nil {+ params.Label = pgtype.Text{String: *req.Label, Valid: true}+ }++ // Recompute next_run_at if cron or timezone changed.+ cronExpr := prev.CronExpression.String+ if req.CronExpression != nil {+ cronExpr = *req.CronExpression+ }+ tz := "UTC"+ if prev.Timezone.Valid {+ tz = prev.Timezone.String+ }+ if req.Timezone != nil {+ tz = *req.Timezone+ }+ if prev.Kind == "schedule" && cronExpr != "" {+ t, err := computeNextRun(cronExpr, tz)+ if err != nil {+ writeError(w, http.StatusBadRequest, "invalid cron expression: "+err.Error())+ return+ }+ params.NextRunAt = pgtype.Timestamptz{Time: t, Valid: true}+ }++ trigger, err := h.Queries.UpdateAutopilotTrigger(r.Context(), params)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to update trigger")+ return+ }++ resp := triggerToResponse(trigger)+ userID, _ := requireUserID(w, r)+ h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", userID, map[string]any{+ "autopilot_id": autopilotID,+ "trigger": resp,+ })+ writeJSON(w, http.StatusOK, resp)+}++func (h *Handler) DeleteAutopilotTrigger(w http.ResponseWriter, r *http.Request) {+ autopilotID := chi.URLParam(r, "id")+ triggerID := chi.URLParam(r, "triggerId")+ workspaceID := resolveWorkspaceID(r)++ if _, err := h.Queries.GetAutopilotInWorkspace(r.Context(), db.GetAutopilotInWorkspaceParams{+ ID: parseUUID(autopilotID),+ WorkspaceID: parseUUID(workspaceID),+ }); err != nil {+ writeError(w, http.StatusNotFound, "autopilot not found")+ return+ }++ trigger, err := h.Queries.GetAutopilotTrigger(r.Context(), parseUUID(triggerID))+ if err != nil || uuidToString(trigger.AutopilotID) != autopilotID {+ writeError(w, http.StatusNotFound, "trigger not found")+ return+ }++ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }++ if err := h.Queries.DeleteAutopilotTrigger(r.Context(), parseUUID(triggerID)); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to delete trigger")+ return+ }++ h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", userID, map[string]any{+ "autopilot_id": autopilotID,+ "trigger_id": triggerID,+ })+ w.WriteHeader(http.StatusNoContent)+}++// ── Runs ────────────────────────────────────────────────────────────────────++func (h *Handler) ListAutopilotRuns(w http.ResponseWriter, r *http.Request) {+ autopilotID := chi.URLParam(r, "id")+ workspaceID := resolveWorkspaceID(r)++ if _, err := h.Queries.GetAutopilotInWorkspace(r.Context(), db.GetAutopilotInWorkspaceParams{+ ID: parseUUID(autopilotID),+ WorkspaceID: parseUUID(workspaceID),+ }); err != nil {+ writeError(w, http.StatusNotFound, "autopilot not found")+ return+ }++ limit := int32(20)+ offset := int32(0)+ if l := r.URL.Query().Get("limit"); l != "" {+ if v, err := strconv.Atoi(l); err == nil && v > 0 {+ limit = int32(v)+ }+ }+ if limit > 100 {+ limit = 100+ }+ if o := r.URL.Query().Get("offset"); o != "" {+ if v, err := strconv.Atoi(o); err == nil && v >= 0 {+ offset = int32(v)+ }+ }++ runs, err := h.Queries.ListAutopilotRuns(r.Context(), db.ListAutopilotRunsParams{+ AutopilotID: parseUUID(autopilotID),+ Limit: limit,+ Offset: offset,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list runs")+ return+ }++ resp := make([]AutopilotRunResponse, len(runs))+ for i, run := range runs {+ resp[i] = runToResponse(run)+ }+ writeJSON(w, http.StatusOK, map[string]any{"runs": resp, "total": len(resp)})+}++// ── Manual trigger ──────────────────────────────────────────────────────────++func (h *Handler) TriggerAutopilot(w http.ResponseWriter, r *http.Request) {+ id := chi.URLParam(r, "id")+ workspaceID := resolveWorkspaceID(r)++ autopilot, err := h.Queries.GetAutopilotInWorkspace(r.Context(), db.GetAutopilotInWorkspaceParams{+ ID: parseUUID(id),+ WorkspaceID: parseUUID(workspaceID),+ })+ if err != nil {+ writeError(w, http.StatusNotFound, "autopilot not found")+ return+ }+ if autopilot.Status != "active" {+ writeError(w, http.StatusBadRequest, "autopilot is not active")+ return+ }++ run, err := h.AutopilotService.DispatchAutopilot(r.Context(), autopilot, pgtype.UUID{}, "manual", nil)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to trigger autopilot: "+err.Error())+ return+ }++ writeJSON(w, http.StatusOK, runToResponse(*run))+}diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 5c57299a76..4d4533da66 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -32,17 +32,18 @@ type dbExecutor interface {}type Handler struct {- Queries *db.Queries- DB dbExecutor- TxStarter txStarter- Hub *realtime.Hub- Bus *events.Bus- TaskService *service.TaskService- EmailService *service.EmailService- PingStore *PingStore- UpdateStore *UpdateStore- Storage storage.Storage- CFSigner *auth.CloudFrontSigner+ Queries *db.Queries+ DB dbExecutor+ TxStarter txStarter+ Hub *realtime.Hub+ Bus *events.Bus+ TaskService *service.TaskService+ AutopilotService *service.AutopilotService+ EmailService *service.EmailService+ PingStore *PingStore+ UpdateStore *UpdateStore+ Storage storage.Storage+ CFSigner *auth.CloudFrontSigner}func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *events.Bus, emailService *service.EmailService, store storage.Storage, cfSigner *auth.CloudFrontSigner) *Handler {@@ -51,18 +52,20 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *eventexecutor = candidate}+ taskSvc := service.NewTaskService(queries, hub, bus)return &Handler{- Queries: queries,- DB: executor,- TxStarter: txStarter,- Hub: hub,- Bus: bus,- TaskService: service.NewTaskService(queries, hub, bus),- EmailService: emailService,- PingStore: NewPingStore(),- UpdateStore: NewUpdateStore(),- Storage: store,- CFSigner: cfSigner,+ Queries: queries,+ DB: executor,+ TxStarter: txStarter,+ Hub: hub,+ Bus: bus,+ TaskService: taskSvc,+ AutopilotService: service.NewAutopilotService(queries, txStarter, bus, taskSvc),+ EmailService: emailService,+ PingStore: NewPingStore(),+ UpdateStore: NewUpdateStore(),+ Storage: store,+ CFSigner: cfSigner,}}diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.gonew file mode 100644index 0000000000..d53f09ba55--- /dev/null+++ b/server/internal/service/autopilot.go@@ -0,0 +1,394 @@+package service++import (+ "context"+ "fmt"+ "log/slog"+ "strings"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// TxStarter abstracts transaction creation (satisfied by pgxpool.Pool).+type TxStarter interface {+ Begin(ctx context.Context) (pgx.Tx, error)+}++type AutopilotService struct {+ Queries *db.Queries+ TxStarter TxStarter+ Bus *events.Bus+ TaskSvc *TaskService+}++func NewAutopilotService(q *db.Queries, tx TxStarter, bus *events.Bus, taskSvc *TaskService) *AutopilotService {+ return &AutopilotService{Queries: q, TxStarter: tx, Bus: bus, TaskSvc: taskSvc}+}++// DispatchAutopilot is the core execution entry point.+// It checks concurrency policy, creates a run, and either creates an issue+// or enqueues a direct agent task depending on execution_mode.+func (s *AutopilotService) DispatchAutopilot(+ ctx context.Context,+ autopilot db.Autopilot,+ triggerID pgtype.UUID,+ source string,+ payload []byte,+) (*db.AutopilotRun, error) {+ // Check concurrency policy.+ allowed, err := s.checkConcurrency(ctx, autopilot)+ if err != nil {+ return nil, fmt.Errorf("concurrency check: %w", err)+ }+ if !allowed {+ // Create a skipped run record.+ run, err := s.Queries.CreateAutopilotRun(ctx, db.CreateAutopilotRunParams{+ AutopilotID: autopilot.ID,+ TriggerID: triggerID,+ Source: source,+ Status: "skipped",+ TriggerPayload: payload,+ })+ if err != nil {+ return nil, fmt.Errorf("create skipped run: %w", err)+ }+ if _, err := s.Queries.UpdateAutopilotRunSkipped(ctx, db.UpdateAutopilotRunSkippedParams{+ ID: run.ID,+ FailureReason: pgtype.Text{String: "skipped: active run exists", Valid: true},+ }); err != nil {+ slog.Warn("failed to finalize skipped run", "run_id", util.UUIDToString(run.ID), "error", err)+ }+ slog.Info("autopilot run skipped", "autopilot_id", util.UUIDToString(autopilot.ID), "source", source)+ return &run, nil+ }++ // Create a pending run.+ run, err := s.Queries.CreateAutopilotRun(ctx, db.CreateAutopilotRunParams{+ AutopilotID: autopilot.ID,+ TriggerID: triggerID,+ Source: source,+ Status: "pending",+ TriggerPayload: payload,+ })+ if err != nil {+ return nil, fmt.Errorf("create run: %w", err)+ }++ switch autopilot.ExecutionMode {+ case "create_issue":+ if err := s.dispatchCreateIssue(ctx, autopilot, &run); err != nil {+ s.failRun(ctx, run.ID, err.Error())+ return &run, fmt.Errorf("dispatch create_issue: %w", err)+ }+ case "run_only":+ if err := s.dispatchRunOnly(ctx, autopilot, &run); err != nil {+ s.failRun(ctx, run.ID, err.Error())+ return &run, fmt.Errorf("dispatch run_only: %w", err)+ }+ default:+ s.failRun(ctx, run.ID, "unknown execution_mode: "+autopilot.ExecutionMode)+ return &run, fmt.Errorf("unknown execution_mode: %s", autopilot.ExecutionMode)+ }++ // Update last_run_at on the autopilot.+ s.Queries.UpdateAutopilotLastRunAt(ctx, autopilot.ID)++ // Publish run start event.+ s.Bus.Publish(events.Event{+ Type: protocol.EventAutopilotRunStart,+ WorkspaceID: util.UUIDToString(autopilot.WorkspaceID),+ ActorType: "system",+ Payload: map[string]any{+ "run_id": util.UUIDToString(run.ID),+ "autopilot_id": util.UUIDToString(autopilot.ID),+ "source": source,+ "status": run.Status,+ },+ })++ return &run, nil+}++// dispatchCreateIssue creates an issue and enqueues a task for the agent.+func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopilot, run *db.AutopilotRun) error {+ tx, err := s.TxStarter.Begin(ctx)+ if err != nil {+ return fmt.Errorf("begin tx: %w", err)+ }+ defer tx.Rollback(ctx)++ qtx := s.Queries.WithTx(tx)++ // Get next issue number.+ issueNumber, err := qtx.IncrementIssueCounter(ctx, ap.WorkspaceID)+ if err != nil {+ return fmt.Errorf("increment issue counter: %w", err)+ }++ title := s.interpolateTemplate(ap)+ description := s.buildIssueDescription(ap)++ issue, err := qtx.CreateIssueWithOrigin(ctx, db.CreateIssueWithOriginParams{+ WorkspaceID: ap.WorkspaceID,+ Title: title,+ Description: description,+ Status: "todo",+ Priority: ap.Priority,+ AssigneeType: pgtype.Text{String: "agent", Valid: true},+ AssigneeID: ap.AssigneeID,+ CreatorType: ap.CreatedByType,+ CreatorID: ap.CreatedByID,+ ParentIssueID: pgtype.UUID{},+ Position: 0,+ DueDate: pgtype.Timestamptz{},+ Number: issueNumber,+ ProjectID: ap.ProjectID,+ OriginType: pgtype.Text{String: "autopilot", Valid: true},+ OriginID: ap.ID,+ })+ if err != nil {+ return fmt.Errorf("create issue: %w", err)+ }++ if err := tx.Commit(ctx); err != nil {+ return fmt.Errorf("commit tx: %w", err)+ }++ // Update run with the linked issue.+ updatedRun, err := s.Queries.UpdateAutopilotRunIssueCreated(ctx, db.UpdateAutopilotRunIssueCreatedParams{+ ID: run.ID,+ IssueID: issue.ID,+ })+ if err != nil {+ slog.Warn("failed to update run with issue_id", "run_id", util.UUIDToString(run.ID), "error", err)+ } else {+ *run = updatedRun+ }++ // Publish issue:created so the existing event chain fires+ // (subscriber listeners, activity listeners, notification listeners).+ prefix := s.getIssuePrefix(ap.WorkspaceID)+ s.Bus.Publish(events.Event{+ Type: protocol.EventIssueCreated,+ WorkspaceID: util.UUIDToString(ap.WorkspaceID),+ ActorType: ap.CreatedByType,+ ActorID: util.UUIDToString(ap.CreatedByID),+ Payload: map[string]any{+ "issue": issueToMap(issue, prefix),+ },+ })++ // Enqueue agent task via the existing flow.+ if _, err := s.TaskSvc.EnqueueTaskForIssue(ctx, issue); err != nil {+ slog.Warn("autopilot: failed to enqueue task for issue", "issue_id", util.UUIDToString(issue.ID), "error", err)+ }++ slog.Info("autopilot dispatched (create_issue)",+ "autopilot_id", util.UUIDToString(ap.ID),+ "issue_id", util.UUIDToString(issue.ID),+ "run_id", util.UUIDToString(run.ID),+ )+ return nil+}++// dispatchRunOnly enqueues a direct agent task without creating an issue.+func (s *AutopilotService) dispatchRunOnly(ctx context.Context, ap db.Autopilot, run *db.AutopilotRun) error {+ agent, err := s.Queries.GetAgent(ctx, ap.AssigneeID)+ if err != nil {+ return fmt.Errorf("load agent: %w", err)+ }+ if agent.ArchivedAt.Valid {+ return fmt.Errorf("agent is archived")+ }+ if !agent.RuntimeID.Valid {+ return fmt.Errorf("agent has no runtime")+ }++ task, err := s.Queries.CreateAutopilotTask(ctx, db.CreateAutopilotTaskParams{+ AgentID: ap.AssigneeID,+ RuntimeID: agent.RuntimeID,+ Priority: priorityToInt(ap.Priority),+ AutopilotRunID: run.ID,+ })+ if err != nil {+ return fmt.Errorf("create autopilot task: %w", err)+ }++ // Update run with task reference.+ updatedRun, err := s.Queries.UpdateAutopilotRunRunning(ctx, db.UpdateAutopilotRunRunningParams{+ ID: run.ID,+ TaskID: task.ID,+ })+ if err != nil {+ slog.Warn("failed to update run with task_id", "run_id", util.UUIDToString(run.ID), "error", err)+ } else {+ *run = updatedRun+ }++ slog.Info("autopilot dispatched (run_only)",+ "autopilot_id", util.UUIDToString(ap.ID),+ "task_id", util.UUIDToString(task.ID),+ "run_id", util.UUIDToString(run.ID),+ )+ return nil+}++// SyncRunFromIssue updates the autopilot run when its linked issue reaches a terminal status.+func (s *AutopilotService) SyncRunFromIssue(ctx context.Context, issue db.Issue) {+ if !issue.OriginType.Valid || issue.OriginType.String != "autopilot" {+ return+ }++ run, err := s.Queries.GetAutopilotRunByIssue(ctx, issue.ID)+ if err != nil {+ return // no active run linked to this issue+ }++ wsID := util.UUIDToString(issue.WorkspaceID)++ switch issue.Status {+ case "done", "in_review":+ if _, err := s.Queries.UpdateAutopilotRunCompleted(ctx, db.UpdateAutopilotRunCompletedParams{+ ID: run.ID,+ }); err != nil {+ slog.Warn("failed to complete autopilot run", "run_id", util.UUIDToString(run.ID), "error", err)+ return+ }+ s.publishRunDone(wsID, run, "completed")+ case "cancelled", "blocked":+ reason := "issue " + issue.Status+ if _, err := s.Queries.UpdateAutopilotRunFailed(ctx, db.UpdateAutopilotRunFailedParams{+ ID: run.ID,+ FailureReason: pgtype.Text{String: reason, Valid: true},+ }); err != nil {+ slog.Warn("failed to fail autopilot run", "run_id", util.UUIDToString(run.ID), "error", err)+ return+ }+ s.publishRunDone(wsID, run, "failed")+ }+}++// SyncRunFromTask updates the autopilot run when a run_only task completes or fails.+func (s *AutopilotService) SyncRunFromTask(ctx context.Context, task db.AgentTaskQueue) {+ if !task.AutopilotRunID.Valid {+ return+ }++ run, err := s.Queries.GetAutopilotRun(ctx, task.AutopilotRunID)+ if err != nil {+ return+ }++ autopilot, err := s.Queries.GetAutopilot(ctx, run.AutopilotID)+ if err != nil {+ return+ }+ wsID := util.UUIDToString(autopilot.WorkspaceID)++ switch task.Status {+ case "completed":+ if _, err := s.Queries.UpdateAutopilotRunCompleted(ctx, db.UpdateAutopilotRunCompletedParams{+ ID: run.ID,+ Result: task.Result,+ }); err != nil {+ slog.Warn("failed to complete autopilot run from task", "run_id", util.UUIDToString(run.ID), "error", err)+ return+ }+ s.publishRunDone(wsID, run, "completed")+ case "failed", "cancelled":+ reason := "task " + task.Status+ if task.Error.Valid {+ reason = task.Error.String+ }+ if _, err := s.Queries.UpdateAutopilotRunFailed(ctx, db.UpdateAutopilotRunFailedParams{+ ID: run.ID,+ FailureReason: pgtype.Text{String: reason, Valid: true},+ }); err != nil {+ slog.Warn("failed to fail autopilot run from task", "run_id", util.UUIDToString(run.ID), "error", err)+ return+ }+ s.publishRunDone(wsID, run, "failed")+ }+}++// checkConcurrency enforces the autopilot's concurrency policy.+// Returns true if a new run is allowed, false otherwise.+func (s *AutopilotService) checkConcurrency(ctx context.Context, ap db.Autopilot) (bool, error) {+ switch ap.ConcurrencyPolicy {+ case "queue":+ return true, nil // always allow+ case "skip":+ _, err := s.Queries.FindActiveAutopilotRun(ctx, ap.ID)+ if err == nil {+ return false, nil // active run exists+ }+ if err == pgx.ErrNoRows {+ return true, nil+ }+ return false, err+ case "replace":+ // Cancel existing active runs, then allow.+ if err := s.Queries.CancelActiveAutopilotRuns(ctx, ap.ID); err != nil {+ slog.Warn("failed to cancel active runs for replace policy", "autopilot_id", util.UUIDToString(ap.ID), "error", err)+ }+ return true, nil+ default:+ return true, nil+ }+}++func (s *AutopilotService) failRun(ctx context.Context, runID pgtype.UUID, reason string) {+ if _, err := s.Queries.UpdateAutopilotRunFailed(ctx, db.UpdateAutopilotRunFailedParams{+ ID: runID,+ FailureReason: pgtype.Text{String: reason, Valid: true},+ }); err != nil {+ slog.Warn("failed to mark autopilot run as failed", "run_id", util.UUIDToString(runID), "error", err)+ }+}++func (s *AutopilotService) publishRunDone(workspaceID string, run db.AutopilotRun, status string) {+ s.Bus.Publish(events.Event{+ Type: protocol.EventAutopilotRunDone,+ WorkspaceID: workspaceID,+ ActorType: "system",+ Payload: map[string]any{+ "run_id": util.UUIDToString(run.ID),+ "autopilot_id": util.UUIDToString(run.AutopilotID),+ "status": status,+ },+ })+}++// buildIssueDescription appends an autopilot system instruction to the+// user-provided description, asking the agent to rename the issue after+// it understands the actual work.+func (s *AutopilotService) buildIssueDescription(ap db.Autopilot) pgtype.Text {+ now := time.Now().UTC().Format(time.RFC3339)+ note := fmt.Sprintf("\n\n---\n*Autopilot run triggered at %s. After starting work, rename this issue to accurately reflect what you are doing.*", now)+ base := ap.Description.String+ return pgtype.Text{String: base + note, Valid: true}+}++// interpolateTemplate replaces {{date}} in the issue title template.+func (s *AutopilotService) interpolateTemplate(ap db.Autopilot) string {+ tmpl := ap.Title+ if ap.IssueTitleTemplate.Valid && ap.IssueTitleTemplate.String != "" {+ tmpl = ap.IssueTitleTemplate.String+ }+ now := time.Now().UTC().Format("2006-01-02")+ return strings.ReplaceAll(tmpl, "{{date}}", now)+}++func (s *AutopilotService) getIssuePrefix(workspaceID pgtype.UUID) string {+ ws, err := s.Queries.GetWorkspace(context.Background(), workspaceID)+ if err != nil {+ return ""+ }+ return ws.IssuePrefix+}diff --git a/server/internal/service/cron.go b/server/internal/service/cron.gonew file mode 100644index 0000000000..0970cad31d--- /dev/null+++ b/server/internal/service/cron.go@@ -0,0 +1,25 @@+package service++import (+ "fmt"+ "time"++ "github.com/robfig/cron/v3"+)++// cronParser accepts standard 5-field cron expressions.+var cronParser = cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow)++// ComputeNextRun parses a cron expression and returns the next fire time+// in the given timezone (falls back to UTC on error).+func ComputeNextRun(cronExpr, timezone string) (time.Time, error) {+ sched, err := cronParser.Parse(cronExpr)+ if err != nil {+ return time.Time{}, fmt.Errorf("parse cron: %w", err)+ }+ loc, err := time.LoadLocation(timezone)+ if err != nil {+ loc = time.UTC+ }+ return sched.Next(time.Now().In(loc)), nil+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 89812394ad..39d5866450 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -517,6 +517,7 @@ func (s *TaskService) broadcastTaskEvent(ctx context.Context, eventType string,// resolveTaskWorkspaceID determines the workspace ID for a task.// For issue tasks, it comes from the issue. For chat tasks, from the chat session.+// For autopilot tasks, from the autopilot via its run.func (s *TaskService) resolveTaskWorkspaceID(ctx context.Context, task db.AgentTaskQueue) string {if task.IssueID.Valid {if issue, err := s.Queries.GetIssue(ctx, task.IssueID); err == nil {@@ -528,6 +529,13 @@ func (s *TaskService) resolveTaskWorkspaceID(ctx context.Context, task db.AgentTreturn util.UUIDToString(cs.WorkspaceID)}}+ if task.AutopilotRunID.Valid {+ if run, err := s.Queries.GetAutopilotRun(ctx, task.AutopilotRunID); err == nil {+ if ap, err := s.Queries.GetAutopilot(ctx, run.AutopilotID); err == nil {+ return util.UUIDToString(ap.WorkspaceID)+ }+ }+ }return ""}diff --git a/server/migrations/042_autopilot.down.sql b/server/migrations/042_autopilot.down.sqlnew file mode 100644index 0000000000..042498fda3--- /dev/null+++ b/server/migrations/042_autopilot.down.sql@@ -0,0 +1,9 @@+DROP INDEX IF EXISTS idx_issue_origin;+ALTER TABLE issue DROP COLUMN IF EXISTS origin_id;+ALTER TABLE issue DROP COLUMN IF EXISTS origin_type;++ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS autopilot_run_id;++DROP TABLE IF EXISTS autopilot_run;+DROP TABLE IF EXISTS autopilot_trigger;+DROP TABLE IF EXISTS autopilot;diff --git a/server/migrations/042_autopilot.up.sql b/server/migrations/042_autopilot.up.sqlnew file mode 100644index 0000000000..2c74d64f59--- /dev/null+++ b/server/migrations/042_autopilot.up.sql@@ -0,0 +1,77 @@+-- Autopilot: scheduled/triggered automations that assign recurring work to AI Agents.++CREATE TABLE IF NOT EXISTS autopilot (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ workspace_id UUID NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,+ project_id UUID REFERENCES project(id) ON DELETE SET NULL,+ title TEXT NOT NULL,+ description TEXT,+ assignee_id UUID NOT NULL REFERENCES agent(id) ON DELETE CASCADE,+ priority TEXT NOT NULL DEFAULT 'medium'+ CHECK (priority IN ('urgent', 'high', 'medium', 'low', 'none')),+ status TEXT NOT NULL DEFAULT 'active'+ CHECK (status IN ('active', 'paused', 'archived')),+ execution_mode TEXT NOT NULL DEFAULT 'create_issue'+ CHECK (execution_mode IN ('create_issue', 'run_only')),+ issue_title_template TEXT,+ concurrency_policy TEXT NOT NULL DEFAULT 'skip'+ CHECK (concurrency_policy IN ('skip', 'queue', 'replace')),+ created_by_type TEXT NOT NULL CHECK (created_by_type IN ('member', 'agent')),+ created_by_id UUID NOT NULL,+ last_run_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_autopilot_workspace ON autopilot(workspace_id);+CREATE INDEX IF NOT EXISTS idx_autopilot_assignee ON autopilot(assignee_id);++-- Trigger: how an autopilot gets kicked off (schedule, webhook, or API).+CREATE TABLE IF NOT EXISTS autopilot_trigger (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ autopilot_id UUID NOT NULL REFERENCES autopilot(id) ON DELETE CASCADE,+ kind TEXT NOT NULL CHECK (kind IN ('schedule', 'webhook', 'api')),+ enabled BOOLEAN NOT NULL DEFAULT true,+ cron_expression TEXT,+ timezone TEXT DEFAULT 'UTC',+ next_run_at TIMESTAMPTZ,+ webhook_token TEXT,+ label TEXT,+ last_fired_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_autopilot_trigger_autopilot ON autopilot_trigger(autopilot_id);+CREATE INDEX IF NOT EXISTS idx_autopilot_trigger_next_run ON autopilot_trigger(next_run_at)+ WHERE enabled = true AND kind = 'schedule';++-- Run: one execution of an autopilot.+CREATE TABLE IF NOT EXISTS autopilot_run (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ autopilot_id UUID NOT NULL REFERENCES autopilot(id) ON DELETE CASCADE,+ trigger_id UUID REFERENCES autopilot_trigger(id) ON DELETE SET NULL,+ source TEXT NOT NULL CHECK (source IN ('schedule', 'manual', 'webhook', 'api')),+ status TEXT NOT NULL DEFAULT 'pending'+ CHECK (status IN ('pending', 'issue_created', 'running', 'skipped', 'completed', 'failed')),+ issue_id UUID REFERENCES issue(id) ON DELETE SET NULL,+ task_id UUID REFERENCES agent_task_queue(id) ON DELETE SET NULL,+ triggered_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ completed_at TIMESTAMPTZ,+ failure_reason TEXT,+ trigger_payload JSONB,+ result JSONB,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_autopilot_run_autopilot ON autopilot_run(autopilot_id, created_at DESC);+CREATE INDEX IF NOT EXISTS idx_autopilot_run_status ON autopilot_run(autopilot_id, status)+ WHERE status IN ('pending', 'issue_created', 'running');++-- Link agent tasks to autopilot runs (same pattern as chat_session_id from migration 033).+ALTER TABLE agent_task_queue ADD COLUMN IF NOT EXISTS autopilot_run_id UUID REFERENCES autopilot_run(id) ON DELETE SET NULL;++-- Track which issues were created by an autopilot so they can be filtered in lists.+ALTER TABLE issue ADD COLUMN IF NOT EXISTS origin_type TEXT CHECK (origin_type IN ('autopilot'));+ALTER TABLE issue ADD COLUMN IF NOT EXISTS origin_id UUID;+CREATE INDEX IF NOT EXISTS idx_issue_origin ON issue(origin_type, origin_id) WHERE origin_type IS NOT NULL;diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 65f4135df4..4cf70ad135 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -52,7 +52,7 @@ const cancelAgentTask = `-- name: CancelAgentTask :oneUPDATE agent_task_queueSET status = 'cancelled', completed_at = now()WHERE id = $1 AND status IN ('queued', 'dispatched', 'running')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id`func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {@@ -76,6 +76,7 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas&i.WorkDir,&i.TriggerCommentID,&i.ChatSessionID,+ &i.AutopilotRunID,)return i, err}@@ -121,7 +122,7 @@ WHERE id = (LIMIT 1FOR UPDATE SKIP LOCKED)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id`// Claims the next queued task for an agent, enforcing per-(issue, agent) serialization:@@ -150,6 +151,7 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, agentID pgtype.UUID) (Agen&i.WorkDir,&i.TriggerCommentID,&i.ChatSessionID,+ &i.AutopilotRunID,)return i, err}@@ -158,7 +160,7 @@ const completeAgentTask = `-- name: CompleteAgentTask :oneUPDATE agent_task_queueSET status = 'completed', completed_at = now(), result = $2, session_id = $3, work_dir = $4WHERE id = $1 AND status = 'running'-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id`type CompleteAgentTaskParams struct {@@ -194,6 +196,7 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa&i.WorkDir,&i.TriggerCommentID,&i.ChatSessionID,+ &i.AutopilotRunID,)return i, err}@@ -276,7 +279,7 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agentconst createAgentTask = `-- name: CreateAgentTask :oneINSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id)VALUES ($1, $2, $3, 'queued', $4, $5)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id`type CreateAgentTaskParams struct {@@ -314,6 +317,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams&i.WorkDir,&i.TriggerCommentID,&i.ChatSessionID,+ &i.AutopilotRunID,)return i, err}@@ -322,7 +326,7 @@ const failAgentTask = `-- name: FailAgentTask :oneUPDATE agent_task_queueSET status = 'failed', completed_at = now(), error = $2WHERE id = $1 AND status IN ('dispatched', 'running')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id`type FailAgentTaskParams struct {@@ -351,6 +355,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A&i.WorkDir,&i.TriggerCommentID,&i.ChatSessionID,+ &i.AutopilotRunID,)return i, err}@@ -465,7 +470,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa}const getAgentTask = `-- name: GetAgentTask :one-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id FROM agent_task_queueWHERE id = $1`@@ -490,6 +495,7 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu&i.WorkDir,&i.TriggerCommentID,&i.ChatSessionID,+ &i.AutopilotRunID,)return i, err}@@ -569,7 +575,7 @@ func (q *Queries) HasPendingTaskForIssueAndAgent(ctx context.Context, arg HasPen}const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id FROM agent_task_queueWHERE issue_id = $1 AND status IN ('dispatched', 'running')ORDER BY created_at DESC`@@ -601,6 +607,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI&i.WorkDir,&i.TriggerCommentID,&i.ChatSessionID,+ &i.AutopilotRunID,); err != nil {return nil, err}@@ -613,7 +620,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI}const listAgentTasks = `-- name: ListAgentTasks :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id FROM agent_task_queueWHERE agent_id = $1ORDER BY created_at DESC`@@ -645,6 +652,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag&i.WorkDir,&i.TriggerCommentID,&i.ChatSessionID,+ &i.AutopilotRunID,); err != nil {return nil, err}@@ -747,7 +755,7 @@ func (q *Queries) ListAllAgents(ctx context.Context, workspaceID pgtype.UUID) ([}const listPendingTasksByRuntime = `-- name: ListPendingTasksByRuntime :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id FROM agent_task_queueWHERE runtime_id = $1 AND status IN ('queued', 'dispatched')ORDER BY priority DESC, created_at ASC`@@ -779,6 +787,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp&i.WorkDir,&i.TriggerCommentID,&i.ChatSessionID,+ &i.AutopilotRunID,); err != nil {return nil, err}@@ -791,7 +800,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp}const listTasksByIssue = `-- name: ListTasksByIssue :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id FROM agent_task_queueWHERE issue_id = $1ORDER BY created_at DESC`@@ -823,6 +832,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]&i.WorkDir,&i.TriggerCommentID,&i.ChatSessionID,+ &i.AutopilotRunID,); err != nil {return nil, err}@@ -870,7 +880,7 @@ const startAgentTask = `-- name: StartAgentTask :oneUPDATE agent_task_queueSET status = 'running', started_at = now()WHERE id = $1 AND status = 'dispatched'-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id`func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {@@ -894,6 +904,7 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask&i.WorkDir,&i.TriggerCommentID,&i.ChatSessionID,+ &i.AutopilotRunID,)return i, err}diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.gonew file mode 100644index 0000000000..ad946e623b--- /dev/null+++ b/server/pkg/db/generated/autopilot.sql.go@@ -0,0 +1,975 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.30.0+// source: autopilot.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const advanceTriggerNextRun = `-- name: AdvanceTriggerNextRun :exec+UPDATE autopilot_trigger+SET next_run_at = $2,+ last_fired_at = now(),+ updated_at = now()+WHERE id = $1+`++type AdvanceTriggerNextRunParams struct {+ ID pgtype.UUID `json:"id"`+ NextRunAt pgtype.Timestamptz `json:"next_run_at"`+}++func (q *Queries) AdvanceTriggerNextRun(ctx context.Context, arg AdvanceTriggerNextRunParams) error {+ _, err := q.db.Exec(ctx, advanceTriggerNextRun, arg.ID, arg.NextRunAt)+ return err+}++const cancelActiveAutopilotRuns = `-- name: CancelActiveAutopilotRuns :exec+UPDATE autopilot_run+SET status = 'failed', completed_at = now(), failure_reason = 'replaced by new run'+WHERE autopilot_id = $1+ AND status IN ('pending', 'issue_created', 'running')+`++// Used by the 'replace' concurrency policy to cancel existing runs.+func (q *Queries) CancelActiveAutopilotRuns(ctx context.Context, autopilotID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, cancelActiveAutopilotRuns, autopilotID)+ return err+}++const claimDueScheduleTriggers = `-- name: ClaimDueScheduleTriggers :many++UPDATE autopilot_trigger t+SET next_run_at = NULL+FROM autopilot a+WHERE t.autopilot_id = a.id+ AND t.kind = 'schedule'+ AND t.enabled = true+ AND t.next_run_at IS NOT NULL+ AND t.next_run_at <= now()+ AND a.status = 'active'+RETURNING t.id, t.autopilot_id, t.kind, t.enabled, t.cron_expression, t.timezone, t.next_run_at, t.webhook_token, t.label, t.last_fired_at, t.created_at, t.updated_at, a.workspace_id AS autopilot_workspace_id+`++type ClaimDueScheduleTriggersRow struct {+ ID pgtype.UUID `json:"id"`+ AutopilotID pgtype.UUID `json:"autopilot_id"`+ Kind string `json:"kind"`+ Enabled bool `json:"enabled"`+ CronExpression pgtype.Text `json:"cron_expression"`+ Timezone pgtype.Text `json:"timezone"`+ NextRunAt pgtype.Timestamptz `json:"next_run_at"`+ WebhookToken pgtype.Text `json:"webhook_token"`+ Label pgtype.Text `json:"label"`+ LastFiredAt pgtype.Timestamptz `json:"last_fired_at"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ AutopilotWorkspaceID pgtype.UUID `json:"autopilot_workspace_id"`+}++// =====================+// Scheduler Queries+// =====================+// Atomically claim all due schedule triggers to prevent concurrent execution.+// Joins the autopilot table to ensure only active autopilots are fired.+func (q *Queries) ClaimDueScheduleTriggers(ctx context.Context) ([]ClaimDueScheduleTriggersRow, error) {+ rows, err := q.db.Query(ctx, claimDueScheduleTriggers)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ClaimDueScheduleTriggersRow{}+ for rows.Next() {+ var i ClaimDueScheduleTriggersRow+ if err := rows.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.Kind,+ &i.Enabled,+ &i.CronExpression,+ &i.Timezone,+ &i.NextRunAt,+ &i.WebhookToken,+ &i.Label,+ &i.LastFiredAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.AutopilotWorkspaceID,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const createAutopilot = `-- name: CreateAutopilot :one+INSERT INTO autopilot (+ workspace_id, project_id, title, description, assignee_id,+ priority, status, execution_mode, issue_title_template,+ concurrency_policy, created_by_type, created_by_id+) VALUES (+ $1, $10, $2, $11, $3,+ $4, $5, $6, $12,+ $7, $8, $9+) RETURNING id, workspace_id, project_id, title, description, assignee_id, priority, status, execution_mode, issue_title_template, concurrency_policy, created_by_type, created_by_id, last_run_at, created_at, updated_at+`++type CreateAutopilotParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Title string `json:"title"`+ AssigneeID pgtype.UUID `json:"assignee_id"`+ Priority string `json:"priority"`+ Status string `json:"status"`+ ExecutionMode string `json:"execution_mode"`+ ConcurrencyPolicy string `json:"concurrency_policy"`+ CreatedByType string `json:"created_by_type"`+ CreatedByID pgtype.UUID `json:"created_by_id"`+ ProjectID pgtype.UUID `json:"project_id"`+ Description pgtype.Text `json:"description"`+ IssueTitleTemplate pgtype.Text `json:"issue_title_template"`+}++func (q *Queries) CreateAutopilot(ctx context.Context, arg CreateAutopilotParams) (Autopilot, error) {+ row := q.db.QueryRow(ctx, createAutopilot,+ arg.WorkspaceID,+ arg.Title,+ arg.AssigneeID,+ arg.Priority,+ arg.Status,+ arg.ExecutionMode,+ arg.ConcurrencyPolicy,+ arg.CreatedByType,+ arg.CreatedByID,+ arg.ProjectID,+ arg.Description,+ arg.IssueTitleTemplate,+ )+ var i Autopilot+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ProjectID,+ &i.Title,+ &i.Description,+ &i.AssigneeID,+ &i.Priority,+ &i.Status,+ &i.ExecutionMode,+ &i.IssueTitleTemplate,+ &i.ConcurrencyPolicy,+ &i.CreatedByType,+ &i.CreatedByID,+ &i.LastRunAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const createAutopilotRun = `-- name: CreateAutopilotRun :one++INSERT INTO autopilot_run (+ autopilot_id, trigger_id, source, status, trigger_payload+) VALUES (+ $1, $4, $2, $3, $5+) RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at+`++type CreateAutopilotRunParams struct {+ AutopilotID pgtype.UUID `json:"autopilot_id"`+ Source string `json:"source"`+ Status string `json:"status"`+ TriggerID pgtype.UUID `json:"trigger_id"`+ TriggerPayload []byte `json:"trigger_payload"`+}++// =====================+// Autopilot Run Management+// =====================+func (q *Queries) CreateAutopilotRun(ctx context.Context, arg CreateAutopilotRunParams) (AutopilotRun, error) {+ row := q.db.QueryRow(ctx, createAutopilotRun,+ arg.AutopilotID,+ arg.Source,+ arg.Status,+ arg.TriggerID,+ arg.TriggerPayload,+ )+ var i AutopilotRun+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.TriggerID,+ &i.Source,+ &i.Status,+ &i.IssueID,+ &i.TaskID,+ &i.TriggeredAt,+ &i.CompletedAt,+ &i.FailureReason,+ &i.TriggerPayload,+ &i.Result,+ &i.CreatedAt,+ )+ return i, err+}++const createAutopilotTask = `-- name: CreateAutopilotTask :one++INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, autopilot_run_id)+VALUES ($1, $2, NULL, 'queued', $3, $4)+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id+`++type CreateAutopilotTaskParams struct {+ AgentID pgtype.UUID `json:"agent_id"`+ RuntimeID pgtype.UUID `json:"runtime_id"`+ Priority int32 `json:"priority"`+ AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`+}++// =====================+// Task Queue (run_only mode)+// =====================+func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTaskParams) (AgentTaskQueue, error) {+ row := q.db.QueryRow(ctx, createAutopilotTask,+ arg.AgentID,+ arg.RuntimeID,+ arg.Priority,+ arg.AutopilotRunID,+ )+ var i AgentTaskQueue+ err := row.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ )+ return i, err+}++const createAutopilotTrigger = `-- name: CreateAutopilotTrigger :one+INSERT INTO autopilot_trigger (+ autopilot_id, kind, enabled, cron_expression, timezone,+ next_run_at, webhook_token, label+) VALUES (+ $1, $2, $3, $4, $5,+ $6, $7, $8+) RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at+`++type CreateAutopilotTriggerParams struct {+ AutopilotID pgtype.UUID `json:"autopilot_id"`+ Kind string `json:"kind"`+ Enabled bool `json:"enabled"`+ CronExpression pgtype.Text `json:"cron_expression"`+ Timezone pgtype.Text `json:"timezone"`+ NextRunAt pgtype.Timestamptz `json:"next_run_at"`+ WebhookToken pgtype.Text `json:"webhook_token"`+ Label pgtype.Text `json:"label"`+}++func (q *Queries) CreateAutopilotTrigger(ctx context.Context, arg CreateAutopilotTriggerParams) (AutopilotTrigger, error) {+ row := q.db.QueryRow(ctx, createAutopilotTrigger,+ arg.AutopilotID,+ arg.Kind,+ arg.Enabled,+ arg.CronExpression,+ arg.Timezone,+ arg.NextRunAt,+ arg.WebhookToken,+ arg.Label,+ )+ var i AutopilotTrigger+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.Kind,+ &i.Enabled,+ &i.CronExpression,+ &i.Timezone,+ &i.NextRunAt,+ &i.WebhookToken,+ &i.Label,+ &i.LastFiredAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const deleteAutopilot = `-- name: DeleteAutopilot :exec+DELETE FROM autopilot WHERE id = $1+`++func (q *Queries) DeleteAutopilot(ctx context.Context, id pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteAutopilot, id)+ return err+}++const deleteAutopilotTrigger = `-- name: DeleteAutopilotTrigger :exec+DELETE FROM autopilot_trigger WHERE id = $1+`++func (q *Queries) DeleteAutopilotTrigger(ctx context.Context, id pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteAutopilotTrigger, id)+ return err+}++const findActiveAutopilotRun = `-- name: FindActiveAutopilotRun :one++SELECT id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at FROM autopilot_run+WHERE autopilot_id = $1+ AND status IN ('pending', 'issue_created', 'running')+ORDER BY created_at DESC+LIMIT 1+`++// =====================+// Concurrency Check+// =====================+// Returns an active (non-terminal) run for the given autopilot, if any.+func (q *Queries) FindActiveAutopilotRun(ctx context.Context, autopilotID pgtype.UUID) (AutopilotRun, error) {+ row := q.db.QueryRow(ctx, findActiveAutopilotRun, autopilotID)+ var i AutopilotRun+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.TriggerID,+ &i.Source,+ &i.Status,+ &i.IssueID,+ &i.TaskID,+ &i.TriggeredAt,+ &i.CompletedAt,+ &i.FailureReason,+ &i.TriggerPayload,+ &i.Result,+ &i.CreatedAt,+ )+ return i, err+}++const getAutopilot = `-- name: GetAutopilot :one+SELECT id, workspace_id, project_id, title, description, assignee_id, priority, status, execution_mode, issue_title_template, concurrency_policy, created_by_type, created_by_id, last_run_at, created_at, updated_at FROM autopilot+WHERE id = $1+`++func (q *Queries) GetAutopilot(ctx context.Context, id pgtype.UUID) (Autopilot, error) {+ row := q.db.QueryRow(ctx, getAutopilot, id)+ var i Autopilot+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ProjectID,+ &i.Title,+ &i.Description,+ &i.AssigneeID,+ &i.Priority,+ &i.Status,+ &i.ExecutionMode,+ &i.IssueTitleTemplate,+ &i.ConcurrencyPolicy,+ &i.CreatedByType,+ &i.CreatedByID,+ &i.LastRunAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const getAutopilotInWorkspace = `-- name: GetAutopilotInWorkspace :one+SELECT id, workspace_id, project_id, title, description, assignee_id, priority, status, execution_mode, issue_title_template, concurrency_policy, created_by_type, created_by_id, last_run_at, created_at, updated_at FROM autopilot+WHERE id = $1 AND workspace_id = $2+`++type GetAutopilotInWorkspaceParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) GetAutopilotInWorkspace(ctx context.Context, arg GetAutopilotInWorkspaceParams) (Autopilot, error) {+ row := q.db.QueryRow(ctx, getAutopilotInWorkspace, arg.ID, arg.WorkspaceID)+ var i Autopilot+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ProjectID,+ &i.Title,+ &i.Description,+ &i.AssigneeID,+ &i.Priority,+ &i.Status,+ &i.ExecutionMode,+ &i.IssueTitleTemplate,+ &i.ConcurrencyPolicy,+ &i.CreatedByType,+ &i.CreatedByID,+ &i.LastRunAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const getAutopilotRun = `-- name: GetAutopilotRun :one+SELECT id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at FROM autopilot_run+WHERE id = $1+`++func (q *Queries) GetAutopilotRun(ctx context.Context, id pgtype.UUID) (AutopilotRun, error) {+ row := q.db.QueryRow(ctx, getAutopilotRun, id)+ var i AutopilotRun+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.TriggerID,+ &i.Source,+ &i.Status,+ &i.IssueID,+ &i.TaskID,+ &i.TriggeredAt,+ &i.CompletedAt,+ &i.FailureReason,+ &i.TriggerPayload,+ &i.Result,+ &i.CreatedAt,+ )+ return i, err+}++const getAutopilotRunByIssue = `-- name: GetAutopilotRunByIssue :one++SELECT id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at FROM autopilot_run+WHERE issue_id = $1 AND status IN ('issue_created', 'running')+LIMIT 1+`++// =====================+// Run lookup by linked entities+// =====================+func (q *Queries) GetAutopilotRunByIssue(ctx context.Context, issueID pgtype.UUID) (AutopilotRun, error) {+ row := q.db.QueryRow(ctx, getAutopilotRunByIssue, issueID)+ var i AutopilotRun+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.TriggerID,+ &i.Source,+ &i.Status,+ &i.IssueID,+ &i.TaskID,+ &i.TriggeredAt,+ &i.CompletedAt,+ &i.FailureReason,+ &i.TriggerPayload,+ &i.Result,+ &i.CreatedAt,+ )+ return i, err+}++const getAutopilotRunByTask = `-- name: GetAutopilotRunByTask :one+SELECT id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at FROM autopilot_run+WHERE task_id = $1+LIMIT 1+`++func (q *Queries) GetAutopilotRunByTask(ctx context.Context, taskID pgtype.UUID) (AutopilotRun, error) {+ row := q.db.QueryRow(ctx, getAutopilotRunByTask, taskID)+ var i AutopilotRun+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.TriggerID,+ &i.Source,+ &i.Status,+ &i.IssueID,+ &i.TaskID,+ &i.TriggeredAt,+ &i.CompletedAt,+ &i.FailureReason,+ &i.TriggerPayload,+ &i.Result,+ &i.CreatedAt,+ )+ return i, err+}++const getAutopilotTrigger = `-- name: GetAutopilotTrigger :one+SELECT id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at FROM autopilot_trigger+WHERE id = $1+`++func (q *Queries) GetAutopilotTrigger(ctx context.Context, id pgtype.UUID) (AutopilotTrigger, error) {+ row := q.db.QueryRow(ctx, getAutopilotTrigger, id)+ var i AutopilotTrigger+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.Kind,+ &i.Enabled,+ &i.CronExpression,+ &i.Timezone,+ &i.NextRunAt,+ &i.WebhookToken,+ &i.Label,+ &i.LastFiredAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const listAutopilotRuns = `-- name: ListAutopilotRuns :many+SELECT id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at FROM autopilot_run+WHERE autopilot_id = $1+ORDER BY created_at DESC+LIMIT $2 OFFSET $3+`++type ListAutopilotRunsParams struct {+ AutopilotID pgtype.UUID `json:"autopilot_id"`+ Limit int32 `json:"limit"`+ Offset int32 `json:"offset"`+}++func (q *Queries) ListAutopilotRuns(ctx context.Context, arg ListAutopilotRunsParams) ([]AutopilotRun, error) {+ rows, err := q.db.Query(ctx, listAutopilotRuns, arg.AutopilotID, arg.Limit, arg.Offset)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []AutopilotRun{}+ for rows.Next() {+ var i AutopilotRun+ if err := rows.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.TriggerID,+ &i.Source,+ &i.Status,+ &i.IssueID,+ &i.TaskID,+ &i.TriggeredAt,+ &i.CompletedAt,+ &i.FailureReason,+ &i.TriggerPayload,+ &i.Result,+ &i.CreatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listAutopilotTriggers = `-- name: ListAutopilotTriggers :many++SELECT id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at FROM autopilot_trigger+WHERE autopilot_id = $1+ORDER BY created_at ASC+`++// =====================+// Autopilot Trigger CRUD+// =====================+func (q *Queries) ListAutopilotTriggers(ctx context.Context, autopilotID pgtype.UUID) ([]AutopilotTrigger, error) {+ rows, err := q.db.Query(ctx, listAutopilotTriggers, autopilotID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []AutopilotTrigger{}+ for rows.Next() {+ var i AutopilotTrigger+ if err := rows.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.Kind,+ &i.Enabled,+ &i.CronExpression,+ &i.Timezone,+ &i.NextRunAt,+ &i.WebhookToken,+ &i.Label,+ &i.LastFiredAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listAutopilots = `-- name: ListAutopilots :many++SELECT id, workspace_id, project_id, title, description, assignee_id, priority, status, execution_mode, issue_title_template, concurrency_policy, created_by_type, created_by_id, last_run_at, created_at, updated_at FROM autopilot+WHERE workspace_id = $1+ AND ($2::text IS NULL OR status = $2)+ORDER BY created_at DESC+`++type ListAutopilotsParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Status pgtype.Text `json:"status"`+}++// =====================+// Autopilot CRUD+// =====================+func (q *Queries) ListAutopilots(ctx context.Context, arg ListAutopilotsParams) ([]Autopilot, error) {+ rows, err := q.db.Query(ctx, listAutopilots, arg.WorkspaceID, arg.Status)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []Autopilot{}+ for rows.Next() {+ var i Autopilot+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ProjectID,+ &i.Title,+ &i.Description,+ &i.AssigneeID,+ &i.Priority,+ &i.Status,+ &i.ExecutionMode,+ &i.IssueTitleTemplate,+ &i.ConcurrencyPolicy,+ &i.CreatedByType,+ &i.CreatedByID,+ &i.LastRunAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const updateAutopilot = `-- name: UpdateAutopilot :one+UPDATE autopilot SET+ title = COALESCE($2, title),+ description = COALESCE($3, description),+ assignee_id = COALESCE($4::uuid, assignee_id),+ project_id = $5,+ priority = COALESCE($6, priority),+ status = COALESCE($7, status),+ execution_mode = COALESCE($8, execution_mode),+ issue_title_template = $9,+ concurrency_policy = COALESCE($10, concurrency_policy),+ updated_at = now()+WHERE id = $1+RETURNING id, workspace_id, project_id, title, description, assignee_id, priority, status, execution_mode, issue_title_template, concurrency_policy, created_by_type, created_by_id, last_run_at, created_at, updated_at+`++type UpdateAutopilotParams struct {+ ID pgtype.UUID `json:"id"`+ Title pgtype.Text `json:"title"`+ Description pgtype.Text `json:"description"`+ AssigneeID pgtype.UUID `json:"assignee_id"`+ ProjectID pgtype.UUID `json:"project_id"`+ Priority pgtype.Text `json:"priority"`+ Status pgtype.Text `json:"status"`+ ExecutionMode pgtype.Text `json:"execution_mode"`+ IssueTitleTemplate pgtype.Text `json:"issue_title_template"`+ ConcurrencyPolicy pgtype.Text `json:"concurrency_policy"`+}++func (q *Queries) UpdateAutopilot(ctx context.Context, arg UpdateAutopilotParams) (Autopilot, error) {+ row := q.db.QueryRow(ctx, updateAutopilot,+ arg.ID,+ arg.Title,+ arg.Description,+ arg.AssigneeID,+ arg.ProjectID,+ arg.Priority,+ arg.Status,+ arg.ExecutionMode,+ arg.IssueTitleTemplate,+ arg.ConcurrencyPolicy,+ )+ var i Autopilot+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ProjectID,+ &i.Title,+ &i.Description,+ &i.AssigneeID,+ &i.Priority,+ &i.Status,+ &i.ExecutionMode,+ &i.IssueTitleTemplate,+ &i.ConcurrencyPolicy,+ &i.CreatedByType,+ &i.CreatedByID,+ &i.LastRunAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const updateAutopilotLastRunAt = `-- name: UpdateAutopilotLastRunAt :exec+UPDATE autopilot SET last_run_at = now(), updated_at = now()+WHERE id = $1+`++func (q *Queries) UpdateAutopilotLastRunAt(ctx context.Context, id pgtype.UUID) error {+ _, err := q.db.Exec(ctx, updateAutopilotLastRunAt, id)+ return err+}++const updateAutopilotRunCompleted = `-- name: UpdateAutopilotRunCompleted :one+UPDATE autopilot_run+SET status = 'completed', completed_at = now(), result = $2+WHERE id = $1+RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at+`++type UpdateAutopilotRunCompletedParams struct {+ ID pgtype.UUID `json:"id"`+ Result []byte `json:"result"`+}++func (q *Queries) UpdateAutopilotRunCompleted(ctx context.Context, arg UpdateAutopilotRunCompletedParams) (AutopilotRun, error) {+ row := q.db.QueryRow(ctx, updateAutopilotRunCompleted, arg.ID, arg.Result)+ var i AutopilotRun+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.TriggerID,+ &i.Source,+ &i.Status,+ &i.IssueID,+ &i.TaskID,+ &i.TriggeredAt,+ &i.CompletedAt,+ &i.FailureReason,+ &i.TriggerPayload,+ &i.Result,+ &i.CreatedAt,+ )+ return i, err+}++const updateAutopilotRunFailed = `-- name: UpdateAutopilotRunFailed :one+UPDATE autopilot_run+SET status = 'failed', completed_at = now(), failure_reason = $2+WHERE id = $1+RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at+`++type UpdateAutopilotRunFailedParams struct {+ ID pgtype.UUID `json:"id"`+ FailureReason pgtype.Text `json:"failure_reason"`+}++func (q *Queries) UpdateAutopilotRunFailed(ctx context.Context, arg UpdateAutopilotRunFailedParams) (AutopilotRun, error) {+ row := q.db.QueryRow(ctx, updateAutopilotRunFailed, arg.ID, arg.FailureReason)+ var i AutopilotRun+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.TriggerID,+ &i.Source,+ &i.Status,+ &i.IssueID,+ &i.TaskID,+ &i.TriggeredAt,+ &i.CompletedAt,+ &i.FailureReason,+ &i.TriggerPayload,+ &i.Result,+ &i.CreatedAt,+ )+ return i, err+}++const updateAutopilotRunIssueCreated = `-- name: UpdateAutopilotRunIssueCreated :one+UPDATE autopilot_run+SET status = 'issue_created', issue_id = $2+WHERE id = $1+RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at+`++type UpdateAutopilotRunIssueCreatedParams struct {+ ID pgtype.UUID `json:"id"`+ IssueID pgtype.UUID `json:"issue_id"`+}++func (q *Queries) UpdateAutopilotRunIssueCreated(ctx context.Context, arg UpdateAutopilotRunIssueCreatedParams) (AutopilotRun, error) {+ row := q.db.QueryRow(ctx, updateAutopilotRunIssueCreated, arg.ID, arg.IssueID)+ var i AutopilotRun+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.TriggerID,+ &i.Source,+ &i.Status,+ &i.IssueID,+ &i.TaskID,+ &i.TriggeredAt,+ &i.CompletedAt,+ &i.FailureReason,+ &i.TriggerPayload,+ &i.Result,+ &i.CreatedAt,+ )+ return i, err+}++const updateAutopilotRunRunning = `-- name: UpdateAutopilotRunRunning :one+UPDATE autopilot_run+SET status = 'running', task_id = $2+WHERE id = $1+RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at+`++type UpdateAutopilotRunRunningParams struct {+ ID pgtype.UUID `json:"id"`+ TaskID pgtype.UUID `json:"task_id"`+}++func (q *Queries) UpdateAutopilotRunRunning(ctx context.Context, arg UpdateAutopilotRunRunningParams) (AutopilotRun, error) {+ row := q.db.QueryRow(ctx, updateAutopilotRunRunning, arg.ID, arg.TaskID)+ var i AutopilotRun+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.TriggerID,+ &i.Source,+ &i.Status,+ &i.IssueID,+ &i.TaskID,+ &i.TriggeredAt,+ &i.CompletedAt,+ &i.FailureReason,+ &i.TriggerPayload,+ &i.Result,+ &i.CreatedAt,+ )+ return i, err+}++const updateAutopilotRunSkipped = `-- name: UpdateAutopilotRunSkipped :one+UPDATE autopilot_run+SET status = 'skipped', completed_at = now(), failure_reason = $2+WHERE id = $1+RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at+`++type UpdateAutopilotRunSkippedParams struct {+ ID pgtype.UUID `json:"id"`+ FailureReason pgtype.Text `json:"failure_reason"`+}++func (q *Queries) UpdateAutopilotRunSkipped(ctx context.Context, arg UpdateAutopilotRunSkippedParams) (AutopilotRun, error) {+ row := q.db.QueryRow(ctx, updateAutopilotRunSkipped, arg.ID, arg.FailureReason)+ var i AutopilotRun+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.TriggerID,+ &i.Source,+ &i.Status,+ &i.IssueID,+ &i.TaskID,+ &i.TriggeredAt,+ &i.CompletedAt,+ &i.FailureReason,+ &i.TriggerPayload,+ &i.Result,+ &i.CreatedAt,+ )+ return i, err+}++const updateAutopilotTrigger = `-- name: UpdateAutopilotTrigger :one+UPDATE autopilot_trigger SET+ enabled = COALESCE($2::boolean, enabled),+ cron_expression = COALESCE($3, cron_expression),+ timezone = COALESCE($4, timezone),+ next_run_at = $5,+ label = COALESCE($6, label),+ updated_at = now()+WHERE id = $1+RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at+`++type UpdateAutopilotTriggerParams struct {+ ID pgtype.UUID `json:"id"`+ Enabled pgtype.Bool `json:"enabled"`+ CronExpression pgtype.Text `json:"cron_expression"`+ Timezone pgtype.Text `json:"timezone"`+ NextRunAt pgtype.Timestamptz `json:"next_run_at"`+ Label pgtype.Text `json:"label"`+}++func (q *Queries) UpdateAutopilotTrigger(ctx context.Context, arg UpdateAutopilotTriggerParams) (AutopilotTrigger, error) {+ row := q.db.QueryRow(ctx, updateAutopilotTrigger,+ arg.ID,+ arg.Enabled,+ arg.CronExpression,+ arg.Timezone,+ arg.NextRunAt,+ arg.Label,+ )+ var i AutopilotTrigger+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.Kind,+ &i.Enabled,+ &i.CronExpression,+ &i.Timezone,+ &i.NextRunAt,+ &i.WebhookToken,+ &i.Label,+ &i.LastFiredAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex ed245357fe..9b340437fc 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -93,7 +93,7 @@ func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionPaconst createChatTask = `-- name: CreateChatTask :oneINSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, chat_session_id)VALUES ($1, $2, NULL, 'queued', $3, $4)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id`type CreateChatTaskParams struct {@@ -129,6 +129,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)&i.WorkDir,&i.TriggerCommentID,&i.ChatSessionID,+ &i.AutopilotRunID,)return i, err}diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 5654a9a7fc..7c51c94732 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -136,7 +136,7 @@ INSERT INTO issue (parent_issue_id, position, due_date, number, project_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14-) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id+) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id`type CreateIssueParams struct {@@ -194,6 +194,85 @@ func (q *Queries) CreateIssue(ctx context.Context, arg CreateIssueParams) (Issue&i.UpdatedAt,&i.Number,&i.ProjectID,+ &i.OriginType,+ &i.OriginID,+ )+ return i, err+}++const createIssueWithOrigin = `-- name: CreateIssueWithOrigin :one+INSERT INTO issue (+ workspace_id, title, description, status, priority,+ assignee_type, assignee_id, creator_type, creator_id,+ parent_issue_id, position, due_date, number, project_id,+ origin_type, origin_id+) VALUES (+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14,+ $15, $16+) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id+`++type CreateIssueWithOriginParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Title string `json:"title"`+ Description pgtype.Text `json:"description"`+ Status string `json:"status"`+ Priority string `json:"priority"`+ AssigneeType pgtype.Text `json:"assignee_type"`+ AssigneeID pgtype.UUID `json:"assignee_id"`+ CreatorType string `json:"creator_type"`+ CreatorID pgtype.UUID `json:"creator_id"`+ ParentIssueID pgtype.UUID `json:"parent_issue_id"`+ Position float64 `json:"position"`+ DueDate pgtype.Timestamptz `json:"due_date"`+ Number int32 `json:"number"`+ ProjectID pgtype.UUID `json:"project_id"`+ OriginType pgtype.Text `json:"origin_type"`+ OriginID pgtype.UUID `json:"origin_id"`+}++func (q *Queries) CreateIssueWithOrigin(ctx context.Context, arg CreateIssueWithOriginParams) (Issue, error) {+ row := q.db.QueryRow(ctx, createIssueWithOrigin,+ arg.WorkspaceID,+ arg.Title,+ arg.Description,+ arg.Status,+ arg.Priority,+ arg.AssigneeType,+ arg.AssigneeID,+ arg.CreatorType,+ arg.CreatorID,+ arg.ParentIssueID,+ arg.Position,+ arg.DueDate,+ arg.Number,+ arg.ProjectID,+ arg.OriginType,+ arg.OriginID,+ )+ var i Issue+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Title,+ &i.Description,+ &i.Status,+ &i.Priority,+ &i.AssigneeType,+ &i.AssigneeID,+ &i.CreatorType,+ &i.CreatorID,+ &i.ParentIssueID,+ &i.AcceptanceCriteria,+ &i.ContextRefs,+ &i.Position,+ &i.DueDate,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Number,+ &i.ProjectID,+ &i.OriginType,+ &i.OriginID,)return i, err}@@ -208,7 +287,7 @@ func (q *Queries) DeleteIssue(ctx context.Context, id pgtype.UUID) error {}const getIssue = `-- name: GetIssue :one-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id FROM issueWHERE id = $1`@@ -235,12 +314,14 @@ func (q *Queries) GetIssue(ctx context.Context, id pgtype.UUID) (Issue, error) {&i.UpdatedAt,&i.Number,&i.ProjectID,+ &i.OriginType,+ &i.OriginID,)return i, err}const getIssueByNumber = `-- name: GetIssueByNumber :one-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id FROM issueWHERE workspace_id = $1 AND number = $2`@@ -272,12 +353,14 @@ func (q *Queries) GetIssueByNumber(ctx context.Context, arg GetIssueByNumberPara&i.UpdatedAt,&i.Number,&i.ProjectID,+ &i.OriginType,+ &i.OriginID,)return i, err}const getIssueInWorkspace = `-- name: GetIssueInWorkspace :one-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id FROM issueWHERE id = $1 AND workspace_id = $2`@@ -309,12 +392,14 @@ func (q *Queries) GetIssueInWorkspace(ctx context.Context, arg GetIssueInWorkspa&i.UpdatedAt,&i.Number,&i.ProjectID,+ &i.OriginType,+ &i.OriginID,)return i, err}const listChildIssues = `-- name: ListChildIssues :many-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id FROM issueWHERE parent_issue_id = $1ORDER BY position ASC, created_at DESC`@@ -348,6 +433,8 @@ func (q *Queries) ListChildIssues(ctx context.Context, parentIssueID pgtype.UUID&i.UpdatedAt,&i.Number,&i.ProjectID,+ &i.OriginType,+ &i.OriginID,); err != nil {return nil, err}@@ -554,7 +641,7 @@ UPDATE issue SETproject_id = $11,updated_at = now()WHERE id = $1-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id`type UpdateIssueParams struct {@@ -606,6 +693,8 @@ func (q *Queries) UpdateIssue(ctx context.Context, arg UpdateIssueParams) (Issue&i.UpdatedAt,&i.Number,&i.ProjectID,+ &i.OriginType,+ &i.OriginID,)return i, err}@@ -615,7 +704,7 @@ UPDATE issue SETstatus = $2,updated_at = now()WHERE id = $1-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id`type UpdateIssueStatusParams struct {@@ -646,6 +735,8 @@ func (q *Queries) UpdateIssueStatus(ctx context.Context, arg UpdateIssueStatusPa&i.UpdatedAt,&i.Number,&i.ProjectID,+ &i.OriginType,+ &i.OriginID,)return i, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 76e6cda039..cc297f9ae3 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -80,6 +80,7 @@ type AgentTaskQueue struct {WorkDir pgtype.Text `json:"work_dir"`TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`ChatSessionID pgtype.UUID `json:"chat_session_id"`+ AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`}type Attachment struct {@@ -96,6 +97,56 @@ type Attachment struct {CreatedAt pgtype.Timestamptz `json:"created_at"`}+type Autopilot struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ProjectID pgtype.UUID `json:"project_id"`+ Title string `json:"title"`+ Description pgtype.Text `json:"description"`+ AssigneeID pgtype.UUID `json:"assignee_id"`+ Priority string `json:"priority"`+ Status string `json:"status"`+ ExecutionMode string `json:"execution_mode"`+ IssueTitleTemplate pgtype.Text `json:"issue_title_template"`+ ConcurrencyPolicy string `json:"concurrency_policy"`+ CreatedByType string `json:"created_by_type"`+ CreatedByID pgtype.UUID `json:"created_by_id"`+ LastRunAt pgtype.Timestamptz `json:"last_run_at"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}++type AutopilotRun struct {+ ID pgtype.UUID `json:"id"`+ AutopilotID pgtype.UUID `json:"autopilot_id"`+ TriggerID pgtype.UUID `json:"trigger_id"`+ Source string `json:"source"`+ Status string `json:"status"`+ IssueID pgtype.UUID `json:"issue_id"`+ TaskID pgtype.UUID `json:"task_id"`+ TriggeredAt pgtype.Timestamptz `json:"triggered_at"`+ CompletedAt pgtype.Timestamptz `json:"completed_at"`+ FailureReason pgtype.Text `json:"failure_reason"`+ TriggerPayload []byte `json:"trigger_payload"`+ Result []byte `json:"result"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}++type AutopilotTrigger struct {+ ID pgtype.UUID `json:"id"`+ AutopilotID pgtype.UUID `json:"autopilot_id"`+ Kind string `json:"kind"`+ Enabled bool `json:"enabled"`+ CronExpression pgtype.Text `json:"cron_expression"`+ Timezone pgtype.Text `json:"timezone"`+ NextRunAt pgtype.Timestamptz `json:"next_run_at"`+ WebhookToken pgtype.Text `json:"webhook_token"`+ Label pgtype.Text `json:"label"`+ LastFiredAt pgtype.Timestamptz `json:"last_fired_at"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}+type ChatMessage struct {ID pgtype.UUID `json:"id"`ChatSessionID pgtype.UUID `json:"chat_session_id"`@@ -200,6 +251,8 @@ type Issue struct {UpdatedAt pgtype.Timestamptz `json:"updated_at"`Number int32 `json:"number"`ProjectID pgtype.UUID `json:"project_id"`+ OriginType pgtype.Text `json:"origin_type"`+ OriginID pgtype.UUID `json:"origin_id"`}type IssueDependency struct {diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sqlnew file mode 100644index 0000000000..338111cf35--- /dev/null+++ b/server/pkg/db/queries/autopilot.sql@@ -0,0 +1,204 @@+-- =====================+-- Autopilot CRUD+-- =====================++-- name: ListAutopilots :many+SELECT * FROM autopilot+WHERE workspace_id = $1+ AND (sqlc.narg('status')::text IS NULL OR status = sqlc.narg('status'))+ORDER BY created_at DESC;++-- name: GetAutopilot :one+SELECT * FROM autopilot+WHERE id = $1;++-- name: GetAutopilotInWorkspace :one+SELECT * FROM autopilot+WHERE id = $1 AND workspace_id = $2;++-- name: CreateAutopilot :one+INSERT INTO autopilot (+ workspace_id, project_id, title, description, assignee_id,+ priority, status, execution_mode, issue_title_template,+ concurrency_policy, created_by_type, created_by_id+) VALUES (+ $1, sqlc.narg('project_id'), $2, sqlc.narg('description'), $3,+ $4, $5, $6, sqlc.narg('issue_title_template'),+ $7, $8, $9+) RETURNING *;++-- name: UpdateAutopilot :one+UPDATE autopilot SET+ title = COALESCE(sqlc.narg('title'), title),+ description = COALESCE(sqlc.narg('description'), description),+ assignee_id = COALESCE(sqlc.narg('assignee_id')::uuid, assignee_id),+ project_id = sqlc.narg('project_id'),+ priority = COALESCE(sqlc.narg('priority'), priority),+ status = COALESCE(sqlc.narg('status'), status),+ execution_mode = COALESCE(sqlc.narg('execution_mode'), execution_mode),+ issue_title_template = sqlc.narg('issue_title_template'),+ concurrency_policy = COALESCE(sqlc.narg('concurrency_policy'), concurrency_policy),+ updated_at = now()+WHERE id = $1+RETURNING *;++-- name: DeleteAutopilot :exec+DELETE FROM autopilot WHERE id = $1;++-- name: UpdateAutopilotLastRunAt :exec+UPDATE autopilot SET last_run_at = now(), updated_at = now()+WHERE id = $1;++-- =====================+-- Autopilot Trigger CRUD+-- =====================++-- name: ListAutopilotTriggers :many+SELECT * FROM autopilot_trigger+WHERE autopilot_id = $1+ORDER BY created_at ASC;++-- name: GetAutopilotTrigger :one+SELECT * FROM autopilot_trigger+WHERE id = $1;++-- name: CreateAutopilotTrigger :one+INSERT INTO autopilot_trigger (+ autopilot_id, kind, enabled, cron_expression, timezone,+ next_run_at, webhook_token, label+) VALUES (+ $1, $2, $3, sqlc.narg('cron_expression'), sqlc.narg('timezone'),+ sqlc.narg('next_run_at'), sqlc.narg('webhook_token'), sqlc.narg('label')+) RETURNING *;++-- name: UpdateAutopilotTrigger :one+UPDATE autopilot_trigger SET+ enabled = COALESCE(sqlc.narg('enabled')::boolean, enabled),+ cron_expression = COALESCE(sqlc.narg('cron_expression'), cron_expression),+ timezone = COALESCE(sqlc.narg('timezone'), timezone),+ next_run_at = sqlc.narg('next_run_at'),+ label = COALESCE(sqlc.narg('label'), label),+ updated_at = now()+WHERE id = $1+RETURNING *;++-- name: DeleteAutopilotTrigger :exec+DELETE FROM autopilot_trigger WHERE id = $1;++-- name: AdvanceTriggerNextRun :exec+UPDATE autopilot_trigger+SET next_run_at = sqlc.narg('next_run_at'),+ last_fired_at = now(),+ updated_at = now()+WHERE id = $1;++-- =====================+-- Autopilot Run Management+-- =====================++-- name: CreateAutopilotRun :one+INSERT INTO autopilot_run (+ autopilot_id, trigger_id, source, status, trigger_payload+) VALUES (+ $1, sqlc.narg('trigger_id'), $2, $3, sqlc.narg('trigger_payload')+) RETURNING *;++-- name: GetAutopilotRun :one+SELECT * FROM autopilot_run+WHERE id = $1;++-- name: ListAutopilotRuns :many+SELECT * FROM autopilot_run+WHERE autopilot_id = $1+ORDER BY created_at DESC+LIMIT $2 OFFSET $3;++-- name: UpdateAutopilotRunIssueCreated :one+UPDATE autopilot_run+SET status = 'issue_created', issue_id = $2+WHERE id = $1+RETURNING *;++-- name: UpdateAutopilotRunRunning :one+UPDATE autopilot_run+SET status = 'running', task_id = $2+WHERE id = $1+RETURNING *;++-- name: UpdateAutopilotRunSkipped :one+UPDATE autopilot_run+SET status = 'skipped', completed_at = now(), failure_reason = sqlc.narg('failure_reason')+WHERE id = $1+RETURNING *;++-- name: UpdateAutopilotRunCompleted :one+UPDATE autopilot_run+SET status = 'completed', completed_at = now(), result = sqlc.narg('result')+WHERE id = $1+RETURNING *;++-- name: UpdateAutopilotRunFailed :one+UPDATE autopilot_run+SET status = 'failed', completed_at = now(), failure_reason = $2+WHERE id = $1+RETURNING *;++-- =====================+-- Scheduler Queries+-- =====================++-- name: ClaimDueScheduleTriggers :many+-- Atomically claim all due schedule triggers to prevent concurrent execution.+-- Joins the autopilot table to ensure only active autopilots are fired.+UPDATE autopilot_trigger t+SET next_run_at = NULL+FROM autopilot a+WHERE t.autopilot_id = a.id+ AND t.kind = 'schedule'+ AND t.enabled = true+ AND t.next_run_at IS NOT NULL+ AND t.next_run_at <= now()+ AND a.status = 'active'+RETURNING t.*, a.workspace_id AS autopilot_workspace_id;++-- =====================+-- Concurrency Check+-- =====================++-- name: FindActiveAutopilotRun :one+-- Returns an active (non-terminal) run for the given autopilot, if any.+SELECT * FROM autopilot_run+WHERE autopilot_id = $1+ AND status IN ('pending', 'issue_created', 'running')+ORDER BY created_at DESC+LIMIT 1;++-- name: CancelActiveAutopilotRuns :exec+-- Used by the 'replace' concurrency policy to cancel existing runs.+UPDATE autopilot_run+SET status = 'failed', completed_at = now(), failure_reason = 'replaced by new run'+WHERE autopilot_id = $1+ AND status IN ('pending', 'issue_created', 'running');++-- =====================+-- Task Queue (run_only mode)+-- =====================++-- name: CreateAutopilotTask :one+INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, autopilot_run_id)+VALUES ($1, $2, NULL, 'queued', $3, $4)+RETURNING *;++-- =====================+-- Run lookup by linked entities+-- =====================++-- name: GetAutopilotRunByIssue :one+SELECT * FROM autopilot_run+WHERE issue_id = $1 AND status IN ('issue_created', 'running')+LIMIT 1;++-- name: GetAutopilotRunByTask :one+SELECT * FROM autopilot_run+WHERE task_id = $1+LIMIT 1;diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex bb224a05c6..1df1a65bab 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -57,6 +57,17 @@ UPDATE issue SETWHERE id = $1RETURNING *;+-- name: CreateIssueWithOrigin :one+INSERT INTO issue (+ workspace_id, title, description, status, priority,+ assignee_type, assignee_id, creator_type, creator_id,+ parent_issue_id, position, due_date, number, project_id,+ origin_type, origin_id+) VALUES (+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14,+ sqlc.narg('origin_type'), sqlc.narg('origin_id')+) RETURNING *;+-- name: DeleteIssue :execDELETE FROM issue WHERE id = $1;diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex 3bd88ead0b..7bab27da30 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -78,6 +78,13 @@ const (EventInvitationDeclined = "invitation:declined"EventInvitationRevoked = "invitation:revoked"+ // Autopilot events+ EventAutopilotCreated = "autopilot:created"+ EventAutopilotUpdated = "autopilot:updated"+ EventAutopilotDeleted = "autopilot:deleted"+ EventAutopilotRunStart = "autopilot:run_start"+ EventAutopilotRunDone = "autopilot:run_done"+// Daemon eventsEventDaemonHeartbeat = "daemon:heartbeat"EventDaemonRegister = "daemon:register"