Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(autopilot): link created issues to projects (#2908)

Angular1f978bf1ec31
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index 927aa8c752..0c2dcb0d30 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -48,10 +48,11 @@ describe("ApiClient", () => {
await client.getAutopilot("ap-1");
await client.createAutopilot({
title: "Daily triage",
+ project_id: "project-1",
assignee_id: "agent-1",
execution_mode: "create_issue",
});
- await client.updateAutopilot("ap-1", { status: "paused" });
+ await client.updateAutopilot("ap-1", { status: "paused", project_id: null });
await client.deleteAutopilot("ap-1");
await client.triggerAutopilot("ap-1");
await client.listAutopilotRuns("ap-1", { limit: 10, offset: 20 });
@@ -78,6 +79,7 @@ describe("ApiClient", () => {
method: "POST",
body: JSON.stringify({
title: "Daily triage",
+ project_id: "project-1",
assignee_id: "agent-1",
execution_mode: "create_issue",
}),
@@ -85,7 +87,7 @@ describe("ApiClient", () => {
{
url: "https://api.example.test/api/autopilots/ap-1",
method: "PATCH",
- body: JSON.stringify({ status: "paused" }),
+ body: JSON.stringify({ status: "paused", project_id: null }),
},
{ url: "https://api.example.test/api/autopilots/ap-1", method: "DELETE" },
{ url: "https://api.example.test/api/autopilots/ap-1/trigger", method: "POST" },
diff --git a/packages/core/types/autopilot.ts b/packages/core/types/autopilot.ts
index 79b85934e0..c18e7041d6 100644
--- a/packages/core/types/autopilot.ts
+++ b/packages/core/types/autopilot.ts
@@ -28,6 +28,7 @@ export interface Autopilot {
workspace_id: string;
title: string;
description: string | null;
+ project_id?: string | null;
assignee_type: AutopilotAssigneeType;
assignee_id: string;
status: AutopilotStatus;
@@ -82,6 +83,7 @@ export interface AutopilotRun {
export interface CreateAutopilotRequest {
title: string;
description?: string;
+ project_id?: string | null;
// Optional on the wire — when omitted the server defaults to "agent" so
// older clients keep working.
assignee_type?: AutopilotAssigneeType;
@@ -93,6 +95,7 @@ export interface CreateAutopilotRequest {
export interface UpdateAutopilotRequest {
title?: string;
description?: string | null;
+ project_id?: string | null;
// Send `assignee_type` together with `assignee_id` whenever you change the
// assignee — the server requires both for a type swap.
assignee_type?: AutopilotAssigneeType;
diff --git a/packages/views/autopilots/components/autopilot-detail-page.tsx b/packages/views/autopilots/components/autopilot-detail-page.tsx
index 9232ce75d7..cd9c00c536 100644
--- a/packages/views/autopilots/components/autopilot-detail-page.tsx
+++ b/packages/views/autopilots/components/autopilot-detail-page.tsx
@@ -8,6 +8,7 @@ import {
} from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { autopilotDetailOptions, autopilotRunsOptions, autopilotRunOptions } from "@multica/core/autopilots/queries";
+import { projectDetailOptions } from "@multica/core/projects/queries";
import {
useUpdateAutopilot,
useDeleteAutopilot,
@@ -57,6 +58,7 @@ import { TranscriptButton } from "../../common/task-transcript";
import { AutopilotDialog } from "./autopilot-dialog";
import { WebhookPayloadPreview } from "./webhook-payload-preview";
import { WebhookDeliveriesSection } from "./webhook-deliveries-section";
+import { ProjectIcon } from "../../projects/components/project-icon";
import { useT } from "../../i18n";
function formatDate(date: string): string {
@@ -583,6 +585,11 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
const updateAutopilot = useUpdateAutopilot();
const deleteAutopilot = useDeleteAutopilot();
const triggerAutopilot = useTriggerAutopilot();
+ const projectId = data?.autopilot.project_id ?? null;
+ const { data: project, isLoading: projectLoading } = useQuery({
+ ...projectDetailOptions(wsId, projectId ?? ""),
+ enabled: Boolean(projectId),
+ });
const [triggerDialogOpen, setTriggerDialogOpen] = useState(false);
const [editDialogOpen, setEditDialogOpen] = useState(false);
@@ -742,6 +749,28 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
{t(($) => $.execution_mode[autopilot.execution_mode as AutopilotExecutionMode])}
</div>
</div>
+ {autopilot.execution_mode === "create_issue" && (
+ <div>
+ <label className="text-xs text-muted-foreground">{t(($) => $.detail.field_project)}</label>
+ <div className="mt-1 min-w-0">
+ {!autopilot.project_id ? (
+ <span className="text-muted-foreground">{t(($) => $.detail.no_project)}</span>
+ ) : projectLoading ? (
+ <Skeleton className="h-5 w-32" />
+ ) : project ? (
+ <AppLink
+ href={wsPaths.projectDetail(project.id)}
+ className="inline-flex max-w-full items-center gap-1.5 text-foreground hover:underline"
+ >
+ <ProjectIcon project={project} size="md" />
+ <span className="truncate">{project.title}</span>
+ </AppLink>
+ ) : (
+ <span className="text-muted-foreground">{t(($) => $.detail.project_unavailable)}</span>
+ )}
+ </div>
+ </div>
+ )}
{autopilot.description && (
<div className="col-span-2">
<label className="text-xs text-muted-foreground">{t(($) => $.detail.field_prompt)}</label>
@@ -836,6 +865,7 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
initial={{
title: autopilot.title,
description: autopilot.description ?? "",
+ project_id: autopilot.project_id ?? null,
assignee_type: autopilot.assignee_type,
assignee_id: autopilot.assignee_id,
execution_mode: autopilot.execution_mode as AutopilotExecutionMode,
diff --git a/packages/views/autopilots/components/autopilot-dialog.tsx b/packages/views/autopilots/components/autopilot-dialog.tsx
index ccb2b5263f..3e57753059 100644
--- a/packages/views/autopilots/components/autopilot-dialog.tsx
+++ b/packages/views/autopilots/components/autopilot-dialog.tsx
@@ -10,6 +10,7 @@ import {
Clock,
Copy,
FilePlus2,
+ FolderKanban,
Maximize2,
Minimize2,
Play,
@@ -38,6 +39,7 @@ import { TimezonePicker } from "./pickers/timezone-picker";
import { useCurrentWorkspace } from "@multica/core/paths";
import { useWorkspaceId } from "@multica/core/hooks";
import { agentListOptions, squadListOptions } from "@multica/core/workspace/queries";
+import { projectListOptions } from "@multica/core/projects/queries";
import {
useCreateAutopilot,
useCreateAutopilotTrigger,
@@ -53,6 +55,8 @@ import type {
} from "@multica/core/types";
import { TitleEditor, ContentEditor } from "../../editor";
import { ActorAvatar } from "../../common/actor-avatar";
+import { ProjectPicker } from "../../projects/components/project-picker";
+import { ProjectIcon } from "../../projects/components/project-icon";
import { AgentPicker, type AssigneeSelection } from "./pickers/agent-picker";
import {
getDefaultTriggerConfig,
@@ -72,6 +76,7 @@ import { formatSchedulePartialFailureToast } from "./autopilot-dialog-toast";
export interface AutopilotInitial {
title: string;
description: string;
+ project_id: string | null;
assignee_type: AutopilotAssigneeType;
assignee_id: string;
execution_mode: AutopilotExecutionMode;
@@ -245,6 +250,7 @@ export function AutopilotDialog(props: AutopilotDialogProps) {
const wsId = useWorkspaceId();
const { data: agents = [] } = useQuery(agentListOptions(wsId));
const { data: squads = [] } = useQuery(squadListOptions(wsId));
+ const { data: projects = [] } = useQuery(projectListOptions(wsId));
const [isExpanded, setIsExpanded] = useState(false);
const isCreate = props.mode === "create";
@@ -254,6 +260,7 @@ export function AutopilotDialog(props: AutopilotDialogProps) {
const [title, setTitle] = useState(initial.title ?? "");
const [description, setDescription] = useState(initial.description ?? "");
+ const [projectId, setProjectId] = useState<string | null>(initial.project_id ?? null);
const [assigneeType, setAssigneeType] = useState<AutopilotAssigneeType>(
initial.assignee_type ?? "agent",
);
@@ -311,6 +318,10 @@ export function AutopilotDialog(props: AutopilotDialogProps) {
const agent = agents.find((a) => a.id === assigneeId);
return agent ? { name: agent.name, description: agent.description } : null;
}, [agents, squads, assigneeId, assigneeType]);
+ const selectedProject = useMemo(
+ () => projects.find((project) => project.id === projectId) ?? null,
+ [projects, projectId],
+ );
const handleAssigneeChange = (next: AssigneeSelection) => {
setAssigneeType(next.type);
@@ -340,6 +351,7 @@ export function AutopilotDialog(props: AutopilotDialogProps) {
const autopilot = await createAutopilot.mutateAsync({
title: title.trim(),
description: description.trim() || undefined,
+ project_id: executionMode === "create_issue" ? projectId : null,
assignee_type: assigneeType,
assignee_id: assigneeId,
execution_mode: executionMode,
@@ -387,6 +399,7 @@ export function AutopilotDialog(props: AutopilotDialogProps) {
id: props.autopilotId,
title: title.trim(),
description: description.trim() || null,
+ project_id: executionMode === "create_issue" ? projectId : null,
assignee_type: assigneeType,
assignee_id: assigneeId,
execution_mode: executionMode,
@@ -575,6 +588,14 @@ export function AutopilotDialog(props: AutopilotDialogProps) {
<OutputModeSection mode={executionMode} onChange={setExecutionMode} />
+ {executionMode === "create_issue" && (
+ <ProjectSection
+ projectId={projectId}
+ selectedProject={selectedProject}
+ onChange={setProjectId}
+ />
+ )}
+
{isCreate && (
<TriggerKindSection kind={triggerKind} onChange={setTriggerKind} />
)}
@@ -753,6 +774,49 @@ function OutputModeSection({
);
}
+function ProjectSection({
+ projectId,
+ selectedProject,
+ onChange,
+}: {
+ projectId: string | null;
+ selectedProject: { title: string; icon: string | null } | null;
+ onChange: (projectId: string | null) => void;
+}) {
+ const { t } = useT("autopilots");
+ return (
+ <div>
+ <SectionLabel>{t(($) => $.dialog.section_project)}</SectionLabel>
+ <ProjectPicker
+ projectId={projectId}
+ onUpdate={(updates) => onChange(updates.project_id ?? null)}
+ align="start"
+ triggerRender={
+ <button
+ type="button"
+ className={cn(
+ "w-full flex items-center gap-2.5 rounded-md border bg-background px-3 py-2 text-left",
+ "hover:bg-accent/40 transition-colors cursor-pointer",
+ )}
+ >
+ {selectedProject ? (
+ <ProjectIcon project={selectedProject} size="md" />
+ ) : (
+ <span className="inline-flex size-5 items-center justify-center rounded-md bg-muted text-muted-foreground">
+ <FolderKanban className="size-3.5" />
+ </span>
+ )}
+ <span className="flex-1 min-w-0 truncate text-sm font-medium">
+ {selectedProject?.title ?? t(($) => $.dialog.no_project)}
+ </span>
+ <ChevronDown className="size-3.5 text-muted-foreground shrink-0" />
+ </button>
+ }
+ />
+ </div>
+ );
+}
+
function ScheduleSection({
config,
onChange,
diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.json
index 8ee2196027..24e3ab63e9 100644
--- a/packages/views/locales/en/autopilots.json
+++ b/packages/views/locales/en/autopilots.json
@@ -72,6 +72,9 @@
"section_danger": "Danger Zone",
"field_agent": "Agent",
"field_output_mode": "Output Mode",
+ "field_project": "Project",
+ "no_project": "No project",
+ "project_unavailable": "Project unavailable",
"field_prompt": "Prompt",
"add_trigger": "Add trigger",
"no_triggers": "No triggers configured. Add a schedule to run automatically.",
@@ -241,6 +244,8 @@
"section_assignee": "Assignee",
"select_agent": "Select agent",
"select_assignee": "Select agent or squad",
+ "section_project": "Project",
+ "no_project": "No project",
"section_output_mode": "Output mode",
"section_schedule": "Schedule",
"section_trigger_kind": "Trigger",
diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.json
index cd59f14709..dbde107518 100644
--- a/packages/views/locales/zh-Hans/autopilots.json
+++ b/packages/views/locales/zh-Hans/autopilots.json
@@ -72,6 +72,9 @@
"section_danger": "危险操作",
"field_agent": "智能体",
"field_output_mode": "输出模式",
+ "field_project": "关联项目",
+ "no_project": "不关联项目",
+ "project_unavailable": "项目不可用",
"field_prompt": "Prompt",
"add_trigger": "添加触发器",
"no_triggers": "未配置触发器。添加一个时间表让它自动运行。",
@@ -241,6 +244,8 @@
"section_assignee": "执行方",
"select_agent": "选择智能体",
"select_assignee": "选择智能体或小队",
+ "section_project": "关联项目",
+ "no_project": "不关联项目",
"section_output_mode": "输出模式",
"section_schedule": "时间表",
"section_trigger_kind": "触发方式",
diff --git a/server/cmd/multica/cmd_autopilot_test.go b/server/cmd/multica/cmd_autopilot_test.go
index 7d851557b5..bd38a5ea0b 100644
--- a/server/cmd/multica/cmd_autopilot_test.go
+++ b/server/cmd/multica/cmd_autopilot_test.go
@@ -8,9 +8,38 @@ import (
"strings"
"testing"
+ "github.com/spf13/cobra"
+
"github.com/multica-ai/multica/server/internal/cli"
)
+func newAutopilotCreateTestCmd() *cobra.Command {
+ cmd := &cobra.Command{Use: "create"}
+ cmd.Flags().String("title", "", "")
+ cmd.Flags().String("description", "", "")
+ cmd.Flags().String("agent", "", "")
+ cmd.Flags().String("mode", "", "")
+ cmd.Flags().String("priority", "none", "")
+ cmd.Flags().String("project", "", "")
+ cmd.Flags().String("issue-title-template", "", "")
+ cmd.Flags().String("output", "json", "")
+ return cmd
+}
+
+func newAutopilotUpdateTestCmd() *cobra.Command {
+ cmd := &cobra.Command{Use: "update"}
+ cmd.Flags().String("title", "", "")
+ cmd.Flags().String("description", "", "")
+ cmd.Flags().String("agent", "", "")
+ cmd.Flags().String("project", "", "")
+ cmd.Flags().String("priority", "", "")
+ cmd.Flags().String("status", "", "")
+ cmd.Flags().String("mode", "", "")
+ cmd.Flags().String("issue-title-template", "", "")
+ cmd.Flags().String("output", "json", "")
+ return cmd
+}
+
func TestResolveAgent(t *testing.T) {
agentsResp := []map[string]any{
{"id": "11111111-1111-1111-1111-111111111111", "name": "Lambda"},
@@ -99,6 +128,109 @@ func TestResolveAgent(t *testing.T) {
})
}
+func TestRunAutopilotCreateSendsProjectID(t *testing.T) {
+ const (
+ agentID = "11111111-1111-1111-1111-111111111111"
+ projectID = "22222222-2222-2222-2222-222222222222"
+ )
+
+ var body map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/autopilots" {
+ http.NotFound(w, r)
+ return
+ }
+ if r.Method != http.MethodPost {
+ t.Errorf("method = %s, want POST", r.Method)
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode body: %v", err)
+ }
+ json.NewEncoder(w).Encode(map[string]any{
+ "id": "autopilot-1",
+ "title": "Daily planner",
+ "project_id": body["project_id"],
+ })
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newAutopilotCreateTestCmd()
+ _ = cmd.Flags().Set("title", "Daily planner")
+ _ = cmd.Flags().Set("agent", agentID)
+ _ = cmd.Flags().Set("mode", "create_issue")
+ _ = cmd.Flags().Set("project", projectID)
+
+ if err := runAutopilotCreate(cmd, nil); err != nil {
+ t.Fatalf("runAutopilotCreate: %v", err)
+ }
+ if got := body["project_id"]; got != projectID {
+ t.Fatalf("project_id = %#v, want %q", got, projectID)
+ }
+}
+
+func TestRunAutopilotUpdateSendsProjectIDChanges(t *testing.T) {
+ const (
+ autopilotID = "33333333-3333-3333-3333-333333333333"
+ projectID = "44444444-4444-4444-4444-444444444444"
+ )
+
+ var bodies []map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/autopilots/"+autopilotID {
+ http.NotFound(w, r)
+ return
+ }
+ if r.Method != http.MethodPatch {
+ t.Errorf("method = %s, want PATCH", r.Method)
+ }
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode body: %v", err)
+ }
+ bodies = append(bodies, body)
+ json.NewEncoder(w).Encode(map[string]any{
+ "id": autopilotID,
+ "title": "Daily planner",
+ "project_id": body["project_id"],
+ })
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ t.Run("set project", func(t *testing.T) {
+ cmd := newAutopilotUpdateTestCmd()
+ _ = cmd.Flags().Set("project", projectID)
+ if err := runAutopilotUpdate(cmd, []string{autopilotID}); err != nil {
+ t.Fatalf("runAutopilotUpdate: %v", err)
+ }
+ if got := bodies[len(bodies)-1]["project_id"]; got != projectID {
+ t.Fatalf("project_id = %#v, want %q", got, projectID)
+ }
+ })
+
+ t.Run("clear project", func(t *testing.T) {
+ cmd := newAutopilotUpdateTestCmd()
+ _ = cmd.Flags().Set("project", "")
+ if err := runAutopilotUpdate(cmd, []string{autopilotID}); err != nil {
+ t.Fatalf("runAutopilotUpdate: %v", err)
+ }
+ got, ok := bodies[len(bodies)-1]["project_id"]
+ if !ok {
+ t.Fatalf("project_id key missing from update body")
+ }
+ if got != nil {
+ t.Fatalf("project_id = %#v, want nil", got)
+ }
+ })
+}
+
func TestUUIDRegexp(t *testing.T) {
tests := []struct {
in string
diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.go
index 5d317412d6..bd16e053fc 100644
--- a/server/internal/handler/autopilot.go
+++ b/server/internal/handler/autopilot.go
@@ -24,10 +24,11 @@ func computeNextRun(cronExpr, timezone string) (time.Time, error) {
// ── Response types ──────────────────────────────────────────────────────────
type AutopilotResponse struct {
- ID string `json:"id"`
- WorkspaceID string `json:"workspace_id"`
- Title string `json:"title"`
- Description *string `json:"description"`
+ ID string `json:"id"`
+ WorkspaceID string `json:"workspace_id"`
+ Title string `json:"title"`
+ Description *string `json:"description"`
+ ProjectID *string `json:"project_id"`
// AssigneeType is "agent" or "squad". Path A from MUL-2429: when set
// to "squad", AssigneeID points at squad(id) rather than agent(id) and
// dispatch resolves to squad.leader_id at run time.
@@ -110,6 +111,7 @@ func autopilotToResponse(a db.Autopilot) AutopilotResponse {
WorkspaceID: uuidToString(a.WorkspaceID),
Title: a.Title,
Description: textToPtr(a.Description),
+ ProjectID: uuidToPtr(a.ProjectID),
AssigneeType: assigneeType,
AssigneeID: uuidToString(a.AssigneeID),
Status: a.Status,
@@ -217,8 +219,9 @@ func runToResponseSlim(r db.AutopilotRun) AutopilotRunResponse {
// ── Request types ───────────────────────────────────────────────────────────
type CreateAutopilotRequest struct {
- Title string `json:"title"`
- Description *string `json:"description"`
+ Title string `json:"title"`
+ Description *string `json:"description"`
+ ProjectID *string `json:"project_id"`
// AssigneeType is optional and defaults to "agent" — preserves backward
// compatibility with desktop clients shipped before MUL-2429.
AssigneeType *string `json:"assignee_type"`
@@ -230,6 +233,7 @@ type CreateAutopilotRequest struct {
type UpdateAutopilotRequest struct {
Title *string `json:"title"`
Description *string `json:"description"`
+ ProjectID *string `json:"project_id"`
AssigneeType *string `json:"assignee_type"`
AssigneeID *string `json:"assignee_id"`
Status *string `json:"status"`
@@ -396,6 +400,10 @@ func (h *Handler) CreateAutopilot(w http.ResponseWriter, r *http.Request) {
if !h.validateAutopilotAssignee(w, r, assigneeType, assigneeUUID, wsUUID) {
return
}
+ projectID, ok := h.parseAutopilotProjectID(w, r, req.ProjectID, wsUUID)
+ if !ok {
+ return
+ }
autopilot, err := h.Queries.CreateAutopilot(r.Context(), db.CreateAutopilotParams{
WorkspaceID: wsUUID,
@@ -408,6 +416,7 @@ func (h *Handler) CreateAutopilot(w http.ResponseWriter, r *http.Request) {
CreatedByID: parseUUID(userID),
Description: ptrToText(req.Description),
IssueTitleTemplate: ptrToText(req.IssueTitleTemplate),
+ ProjectID: projectID,
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to create autopilot")
@@ -451,6 +460,7 @@ func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {
Description: prev.Description,
AssigneeID: prev.AssigneeID,
IssueTitleTemplate: prev.IssueTitleTemplate,
+ ProjectID: prev.ProjectID,
}
if req.Title != nil {
params.Title = pgtype.Text{String: *req.Title, Valid: true}
@@ -473,6 +483,13 @@ func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {
}
params.IssueTitleTemplate = ptrToText(req.IssueTitleTemplate)
}
+ if _, ok := rawFields["project_id"]; ok {
+ projectID, ok := h.parseAutopilotProjectID(w, r, req.ProjectID, prev.WorkspaceID)
+ if !ok {
+ return
+ }
+ params.ProjectID = projectID
+ }
// assignee_type and assignee_id are validated as a pair: switching
// between agent and squad without supplying a new id would leave the
// row pointing at the wrong table. The client is expected to send both
@@ -530,6 +547,29 @@ func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
}
+func (h *Handler) parseAutopilotProjectID(
+ w http.ResponseWriter,
+ r *http.Request,
+ raw *string,
+ workspaceID pgtype.UUID,
+) (pgtype.UUID, bool) {
+ if raw == nil || *raw == "" {
+ return pgtype.UUID{}, true
+ }
+ projectID, ok := parseUUIDOrBadRequest(w, *raw, "project_id")
+ if !ok {
+ return pgtype.UUID{}, false
+ }
+ if _, err := h.Queries.GetProjectInWorkspace(r.Context(), db.GetProjectInWorkspaceParams{
+ ID: projectID,
+ WorkspaceID: workspaceID,
+ }); err != nil {
+ writeError(w, http.StatusBadRequest, "project_id must reference a project in this workspace")
+ return pgtype.UUID{}, false
+ }
+ return projectID, true
+}
+
func (h *Handler) DeleteAutopilot(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
workspaceID := h.resolveWorkspaceID(r)
diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.go
index 541ad23ccd..ca8cf1f003 100644
--- a/server/internal/handler/handler_test.go
+++ b/server/internal/handler/handler_test.go
@@ -1113,6 +1113,162 @@ func TestAutopilotCreatedIssueCreatorIsAssigneeAgent(t *testing.T) {
}
}
+func TestAutopilotCreateIssueAssociatesConfiguredProject(t *testing.T) {
+ ctx := context.Background()
+ title := fmt.Sprintf("Autopilot project issue %d", time.Now().UnixNano())
+ var autopilotID, issueID, projectID string
+ defer func() {
+ if issueID != "" {
+ testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID)
+ }
+ if autopilotID != "" {
+ testPool.Exec(ctx, `DELETE FROM autopilot WHERE id = $1`, autopilotID)
+ }
+ if projectID != "" {
+ testPool.Exec(ctx, `DELETE FROM project WHERE id = $1`, projectID)
+ }
+ }()
+
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO project (workspace_id, title)
+ VALUES ($1, $2)
+ RETURNING id::text
+ `, testWorkspaceID, "Autopilot project target").Scan(&projectID); err != nil {
+ t.Fatalf("create project fixture: %v", err)
+ }
+
+ var agentID string
+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {
+ t.Fatalf("load test agent: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "Project-linked autopilot",
+ "assignee_id": agentID,
+ "execution_mode": "create_issue",
+ "issue_title_template": title,
+ "project_id": projectID,
+ })
+ testHandler.CreateAutopilot(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateAutopilot: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var autopilot AutopilotResponse
+ if err := json.NewDecoder(w.Body).Decode(&autopilot); err != nil {
+ t.Fatalf("decode autopilot: %v", err)
+ }
+ autopilotID = autopilot.ID
+ if autopilot.ProjectID == nil || *autopilot.ProjectID != projectID {
+ t.Fatalf("autopilot project_id = %v, want %q", autopilot.ProjectID, projectID)
+ }
+
+ queries := db.New(testPool)
+ ap, err := queries.GetAutopilot(ctx, parseUUID(autopilotID))
+ if err != nil {
+ t.Fatalf("GetAutopilot: %v", err)
+ }
+ run, err := testHandler.AutopilotService.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "manual", nil)
+ if err != nil {
+ t.Fatalf("DispatchAutopilot: %v", err)
+ }
+ if run == nil || !run.IssueID.Valid {
+ t.Fatalf("dispatch run = %+v, want linked issue", run)
+ }
+ issueID = uuidToString(run.IssueID)
+
+ var issueProjectID *string
+ if err := testPool.QueryRow(ctx, `
+ SELECT project_id::text
+ FROM issue
+ WHERE id = $1
+ `, issueID).Scan(&issueProjectID); err != nil {
+ t.Fatalf("load created issue project: %v", err)
+ }
+ if issueProjectID == nil || *issueProjectID != projectID {
+ t.Fatalf("created issue project_id = %v, want %q", issueProjectID, projectID)
+ }
+}
+
+func TestUpdateAutopilotCanSetAndClearProject(t *testing.T) {
+ ctx := context.Background()
+ var autopilotID, projectID string
+ defer func() {
+ if autopilotID != "" {
+ testPool.Exec(ctx, `DELETE FROM autopilot WHERE id = $1`, autopilotID)
+ }
+ if projectID != "" {
+ testPool.Exec(ctx, `DELETE FROM project WHERE id = $1`, projectID)
+ }
+ }()
+
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO project (workspace_id, title)
+ VALUES ($1, $2)
+ RETURNING id::text
+ `, testWorkspaceID, "Autopilot update project target").Scan(&projectID); err != nil {
+ t.Fatalf("create project fixture: %v", err)
+ }
+
+ var agentID string
+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {
+ t.Fatalf("load test agent: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "Project update autopilot",
+ "assignee_id": agentID,
+ "execution_mode": "create_issue",
+ })
+ testHandler.CreateAutopilot(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateAutopilot: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var created AutopilotResponse
+ if err := json.NewDecoder(w.Body).Decode(&created); err != nil {
+ t.Fatalf("decode created autopilot: %v", err)
+ }
+ autopilotID = created.ID
+ if created.ProjectID != nil {
+ t.Fatalf("new autopilot project_id = %v, want nil", created.ProjectID)
+ }
+
+ w = httptest.NewRecorder()
+ req = newRequest("PATCH", "/api/autopilots/"+autopilotID+"?workspace_id="+testWorkspaceID, map[string]any{
+ "project_id": projectID,
+ })
+ req = withURLParam(req, "id", autopilotID)
+ testHandler.UpdateAutopilot(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateAutopilot set project: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var updated AutopilotResponse
+ if err := json.NewDecoder(w.Body).Decode(&updated); err != nil {
+ t.Fatalf("decode updated autopilot: %v", err)
+ }
+ if updated.ProjectID == nil || *updated.ProjectID != projectID {
+ t.Fatalf("updated project_id = %v, want %q", updated.ProjectID, projectID)
+ }
+
+ w = httptest.NewRecorder()
+ req = newRequest("PATCH", "/api/autopilots/"+autopilotID+"?workspace_id="+testWorkspaceID, map[string]any{
+ "project_id": nil,
+ })
+ req = withURLParam(req, "id", autopilotID)
+ testHandler.UpdateAutopilot(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateAutopilot clear project: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var cleared AutopilotResponse
+ if err := json.NewDecoder(w.Body).Decode(&cleared); err != nil {
+ t.Fatalf("decode cleared autopilot: %v", err)
+ }
+ if cleared.ProjectID != nil {
+ t.Fatalf("cleared project_id = %v, want nil", cleared.ProjectID)
+ }
+}
+
// TestCreateIssueRejectsNonexistentMemberAssignee covers the bug where any
// well-formed UUID was accepted as assignee_id without checking workspace
// membership.
diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.go
index 88ace10eb0..d276c8bd43 100644
--- a/server/internal/service/autopilot.go
+++ b/server/internal/service/autopilot.go
@@ -175,7 +175,7 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopi
StartDate: pgtype.Timestamptz{},
DueDate: pgtype.Timestamptz{},
Number: issueNumber,
- ProjectID: pgtype.UUID{},
+ ProjectID: ap.ProjectID,
OriginType: pgtype.Text{String: "autopilot", Valid: true},
OriginID: ap.ID,
})
diff --git a/server/migrations/097_autopilot_project_id.down.sql b/server/migrations/097_autopilot_project_id.down.sql
new file mode 100644
index 0000000000..171f8affac
--- /dev/null
+++ b/server/migrations/097_autopilot_project_id.down.sql
@@ -0,0 +1,4 @@
+DROP INDEX IF EXISTS idx_autopilot_project;
+
+ALTER TABLE autopilot
+ DROP COLUMN IF EXISTS project_id;
diff --git a/server/migrations/097_autopilot_project_id.up.sql b/server/migrations/097_autopilot_project_id.up.sql
new file mode 100644
index 0000000000..252f5960a3
--- /dev/null
+++ b/server/migrations/097_autopilot_project_id.up.sql
@@ -0,0 +1,4 @@
+ALTER TABLE autopilot
+ ADD COLUMN IF NOT EXISTS project_id UUID REFERENCES project(id) ON DELETE SET NULL;
+
+CREATE INDEX IF NOT EXISTS idx_autopilot_project ON autopilot(project_id);
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index 4d56dfe95a..1a149151f8 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -105,13 +105,13 @@ func (q *Queries) ClaimDueScheduleTriggers(ctx context.Context) ([]ClaimDueSched
const createAutopilot = `-- name: CreateAutopilot :one
INSERT INTO autopilot (
workspace_id, title, description, assignee_type, assignee_id,
- status, execution_mode, issue_title_template,
+ status, execution_mode, issue_title_template, project_id,
created_by_type, created_by_id
) VALUES (
$1, $2, $9, $3, $4,
- $5, $6, $10,
+ $5, $6, $10, $11,
$7, $8
-) RETURNING id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type
+) RETURNING id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id
`
type CreateAutopilotParams struct {
@@ -125,6 +125,7 @@ type CreateAutopilotParams struct {
CreatedByID pgtype.UUID `json:"created_by_id"`
Description pgtype.Text `json:"description"`
IssueTitleTemplate pgtype.Text `json:"issue_title_template"`
+ ProjectID pgtype.UUID `json:"project_id"`
}
func (q *Queries) CreateAutopilot(ctx context.Context, arg CreateAutopilotParams) (Autopilot, error) {
@@ -139,6 +140,7 @@ func (q *Queries) CreateAutopilot(ctx context.Context, arg CreateAutopilotParams
arg.CreatedByID,
arg.Description,
arg.IssueTitleTemplate,
+ arg.ProjectID,
)
var i Autopilot
err := row.Scan(
@@ -156,6 +158,7 @@ func (q *Queries) CreateAutopilot(ctx context.Context, arg CreateAutopilotParams
&i.CreatedAt,
&i.UpdatedAt,
&i.AssigneeType,
+ &i.ProjectID,
)
return i, err
}
@@ -360,7 +363,7 @@ func (q *Queries) FailAutopilotRunsByIssue(ctx context.Context, issueID pgtype.U
}
const getAutopilot = `-- name: GetAutopilot :one
-SELECT id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type FROM autopilot
+SELECT id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id FROM autopilot
WHERE id = $1
`
@@ -382,12 +385,13 @@ func (q *Queries) GetAutopilot(ctx context.Context, id pgtype.UUID) (Autopilot,
&i.CreatedAt,
&i.UpdatedAt,
&i.AssigneeType,
+ &i.ProjectID,
)
return i, err
}
const getAutopilotInWorkspace = `-- name: GetAutopilotInWorkspace :one
-SELECT id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type FROM autopilot
+SELECT id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id FROM autopilot
WHERE id = $1 AND workspace_id = $2
`
@@ -414,6 +418,7 @@ func (q *Queries) GetAutopilotInWorkspace(ctx context.Context, arg GetAutopilotI
&i.CreatedAt,
&i.UpdatedAt,
&i.AssigneeType,
+ &i.ProjectID,
)
return i, err
}
@@ -653,7 +658,7 @@ func (q *Queries) ListAutopilotTriggers(ctx context.Context, autopilotID pgtype.
const listAutopilots = `-- name: ListAutopilots :many
-SELECT id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type FROM autopilot
+SELECT id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id FROM autopilot
WHERE workspace_id = $1
AND ($2::text IS NULL OR status = $2)
ORDER BY created_at DESC
@@ -691,6 +696,7 @@ func (q *Queries) ListAutopilots(ctx context.Context, arg ListAutopilotsParams)
&i.CreatedAt,
&i.UpdatedAt,
&i.AssigneeType,
+ &i.ProjectID,
); err != nil {
return nil, err
}
@@ -980,7 +986,7 @@ const systemPauseAutopilot = `-- name: SystemPauseAutopilot :one
UPDATE autopilot
SET status = 'paused', updated_at = now()
WHERE id = $1 AND status = 'active'
-RETURNING id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type
+RETURNING id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id
`
// Atomically pauses an autopilot only if it is currently active. Returns no
@@ -1005,6 +1011,7 @@ func (q *Queries) SystemPauseAutopilot(ctx context.Context, id pgtype.UUID) (Aut
&i.CreatedAt,
&i.UpdatedAt,
&i.AssigneeType,
+ &i.ProjectID,
)
return i, err
}
@@ -1034,9 +1041,10 @@ UPDATE autopilot SET
status = COALESCE($6, status),
execution_mode = COALESCE($7, execution_mode),
issue_title_template = $8,
+ project_id = $9,
updated_at = now()
WHERE id = $1
-RETURNING id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type
+RETURNING id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id
`
type UpdateAutopilotParams struct {
@@ -1048,6 +1056,7 @@ type UpdateAutopilotParams struct {
Status pgtype.Text `json:"status"`
ExecutionMode pgtype.Text `json:"execution_mode"`
IssueTitleTemplate pgtype.Text `json:"issue_title_template"`
+ ProjectID pgtype.UUID `json:"project_id"`
}
func (q *Queries) UpdateAutopilot(ctx context.Context, arg UpdateAutopilotParams) (Autopilot, error) {
@@ -1060,6 +1069,7 @@ func (q *Queries) UpdateAutopilot(ctx context.Context, arg UpdateAutopilotParams
arg.Status,
arg.ExecutionMode,
arg.IssueTitleTemplate,
+ arg.ProjectID,
)
var i Autopilot
err := row.Scan(
@@ -1077,6 +1087,7 @@ func (q *Queries) UpdateAutopilot(ctx context.Context, arg UpdateAutopilotParams
&i.CreatedAt,
&i.UpdatedAt,
&i.AssigneeType,
+ &i.ProjectID,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 1d5ea9346e..80446f52fc 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -129,6 +129,7 @@ type Autopilot struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
AssigneeType string `json:"assignee_type"`
+ ProjectID pgtype.UUID `json:"project_id"`
}
type AutopilotRun struct {
diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sql
index 46ff60990d..1c307208b2 100644
--- a/server/pkg/db/queries/autopilot.sql
+++ b/server/pkg/db/queries/autopilot.sql
@@ -19,11 +19,11 @@ WHERE id = $1 AND workspace_id = $2;
-- name: CreateAutopilot :one
INSERT INTO autopilot (
workspace_id, title, description, assignee_type, assignee_id,
- status, execution_mode, issue_title_template,
+ status, execution_mode, issue_title_template, project_id,
created_by_type, created_by_id
) VALUES (
$1, $2, sqlc.narg('description'), $3, $4,
- $5, $6, sqlc.narg('issue_title_template'),
+ $5, $6, sqlc.narg('issue_title_template'), sqlc.narg('project_id'),
$7, $8
) RETURNING *;
@@ -36,6 +36,7 @@ UPDATE autopilot SET
status = COALESCE(sqlc.narg('status'), status),
execution_mode = COALESCE(sqlc.narg('execution_mode'), execution_mode),
issue_title_template = sqlc.narg('issue_title_template'),
+ project_id = sqlc.narg('project_id'),
updated_at = now()
WHERE id = $1
RETURNING *;