Skip to content

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

Go

MUL-7420: Project workflows — columns and handoffs on the workflow (#8814)

Jiayuan Zhangda1671ca204e
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 144e3fc677..caafd2e8e8 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -132,6 +132,13 @@ import type {
IssueStatusEntry,
CreateIssueStatusRequest,
UpdateIssueStatusRequest,
+ IssueWorkflow,
+ IssueWorkflowWriteRequest,
+ IssueWorkflowDryRunResponse,
+ ListIssueWorkflowsResponse,
+ SetProjectWorkflowRequest,
+ SetWorkflowHandoffRequest,
+ WorkflowHandoffPreview,
IssueLabelsResponse,
LabelResourceType,
ResourceLabelsResponse,
@@ -407,6 +414,15 @@ import {
ListLabelsResponseSchema,
ListIssueStatusesResponseSchema,
IssueStatusEntrySchema,
+ ListIssueWorkflowsResponseSchema,
+ IssueWorkflowSchema,
+ IssueWorkflowDryRunResponseSchema,
+ EMPTY_LIST_ISSUE_WORKFLOWS_RESPONSE,
+ EMPTY_ISSUE_WORKFLOW,
+ EMPTY_ISSUE_WORKFLOW_DRY_RUN,
+ WorkflowHandoffPreviewSchema,
+ EMPTY_WORKFLOW_HANDOFF_PREVIEW,
+ IssueWorkflowBriefPreviewSchema,
IssuePropertySchema,
ListPropertiesResponseSchema,
IssuePropertiesResponseSchema,
@@ -4116,6 +4132,135 @@ export class ApiClient {
await this.fetch(`/api/labels/${id}`, { method: "DELETE" });
}
+ // Workspace workflows (MUL-7420). Reads are open to any workspace member;
+ // creating, editing and deleting a workflow is owner/admin only. Adoption
+ // (creating a workflow, pointing a project at one) is gated server-side by
+ // the project_workflows_v1 flag and returns 403 when it is off.
+ async listIssueWorkflows(): Promise<ListIssueWorkflowsResponse> {
+ const raw = await this.fetch<unknown>(`/api/issue-workflows`);
+ return parseWithFallback(raw, ListIssueWorkflowsResponseSchema, EMPTY_LIST_ISSUE_WORKFLOWS_RESPONSE, {
+ endpoint: "GET /api/issue-workflows",
+ });
+ }
+
+ async createIssueWorkflow(data: IssueWorkflowWriteRequest): Promise<IssueWorkflow> {
+ const raw = await this.fetch<unknown>(`/api/issue-workflows`, {
+ method: "POST",
+ body: JSON.stringify(data),
+ });
+ return parseWithFallback(raw, IssueWorkflowSchema, EMPTY_ISSUE_WORKFLOW, {
+ endpoint: "POST /api/issue-workflows",
+ });
+ }
+
+ /**
+ * Saves a workflow edit. When the edit removes statuses that issues of the
+ * workflow's projects still use, the server answers 409
+ * `workflow_status_mapping_required` with a plan; resend with
+ * `status_mapping`. `dryRunIssueWorkflowUpdate` fetches that plan up front.
+ */
+ async updateIssueWorkflow(id: string, data: IssueWorkflowWriteRequest): Promise<IssueWorkflow> {
+ const raw = await this.fetch<unknown>(`/api/issue-workflows/${id}`, {
+ method: "PATCH",
+ body: JSON.stringify({ ...data, dry_run: false }),
+ });
+ return parseWithFallback(raw, IssueWorkflowSchema, EMPTY_ISSUE_WORKFLOW, {
+ endpoint: "PATCH /api/issue-workflows/{id}",
+ });
+ }
+
+ async dryRunIssueWorkflowUpdate(id: string, data: IssueWorkflowWriteRequest): Promise<IssueWorkflowDryRunResponse> {
+ const raw = await this.fetch<unknown>(`/api/issue-workflows/${id}`, {
+ method: "PATCH",
+ body: JSON.stringify({ ...data, dry_run: true }),
+ });
+ return parseWithFallback(raw, IssueWorkflowDryRunResponseSchema, EMPTY_ISSUE_WORKFLOW_DRY_RUN, {
+ endpoint: "PATCH /api/issue-workflows/{id} (dry run)",
+ });
+ }
+
+ async deleteIssueWorkflow(id: string): Promise<void> {
+ await this.fetch(`/api/issue-workflows/${id}`, { method: "DELETE" });
+ }
+
+ /**
+ * Renders the brief a column's handler would receive, from an unsaved
+ * handoff. `project_id` names the project the preview is for, if any.
+ */
+ async previewWorkflowBrief(
+ workflowId: string,
+ data: SetWorkflowHandoffRequest & { status_key: string; project_id?: string },
+ ): Promise<string> {
+ const raw = await this.fetch<unknown>(`/api/issue-workflows/${workflowId}/brief`, {
+ method: "POST",
+ body: JSON.stringify(data),
+ });
+ const parsed = parseWithFallback(raw, IssueWorkflowBriefPreviewSchema, { brief: "" }, {
+ endpoint: "POST /api/issue-workflows/{id}/brief",
+ });
+ return parsed.brief;
+ }
+
+ /**
+ * Saves a workflow's handoff for one column, for every project using it;
+ * handler "none" clears it. With `copyForProjectId` the workflow stays as
+ * it is: the handoff lands on a copy that project switches to, and the copy
+ * is returned. Admin only.
+ */
+ async setWorkflowHandoff(
+ workflowId: string,
+ statusKey: string,
+ data: SetWorkflowHandoffRequest,
+ copyForProjectId?: string,
+ ): Promise<IssueWorkflow> {
+ const body = copyForProjectId ? { ...data, copy_for_project_id: copyForProjectId } : data;
+ const raw = await this.fetch<unknown>(
+ `/api/issue-workflows/${workflowId}/handoffs/${encodeURIComponent(statusKey)}`,
+ { method: "PUT", body: JSON.stringify(body) },
+ );
+ return parseWithFallback(raw, IssueWorkflowSchema, EMPTY_ISSUE_WORKFLOW, {
+ endpoint: "PUT /api/issue-workflows/{id}/handoffs/{status}",
+ });
+ }
+
+ /**
+ * What moving an issue to `status` would do under its project's workflow:
+ * who it goes to, the current agent's active runs, and the brief. Writes
+ * nothing; a status outside the workflow answers 400. With `projectId` it
+ * previews moving the issue into that project instead, entering the column
+ * it lands on (`status` may then be empty).
+ */
+ async previewWorkflowHandoff(issueId: string, status: string, projectId?: string): Promise<WorkflowHandoffPreview> {
+ const query = new URLSearchParams();
+ if (status) query.set("status", status);
+ if (projectId) query.set("project_id", projectId);
+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/workflow-handoff?${query.toString()}`);
+ return parseWithFallback(raw, WorkflowHandoffPreviewSchema, EMPTY_WORKFLOW_HANDOFF_PREVIEW, {
+ endpoint: "GET /api/issues/{id}/workflow-handoff",
+ });
+ }
+
+ /**
+ * Switches a project's workflow; issues on unlisted statuses need a mapping.
+ * Callers refetch the project and its issues, so the response is not read.
+ */
+ async setProjectWorkflow(projectId: string, data: SetProjectWorkflowRequest): Promise<void> {
+ await this.fetch<unknown>(`/api/projects/${projectId}/workflow`, {
+ method: "POST",
+ body: JSON.stringify({ ...data, dry_run: false }),
+ });
+ }
+
+ async dryRunProjectWorkflow(projectId: string, workflowId: string | null): Promise<IssueWorkflowDryRunResponse> {
+ const raw = await this.fetch<unknown>(`/api/projects/${projectId}/workflow`, {
+ method: "POST",
+ body: JSON.stringify({ workflow_id: workflowId, dry_run: true }),
+ });
+ return parseWithFallback(raw, IssueWorkflowDryRunResponseSchema, EMPTY_ISSUE_WORKFLOW_DRY_RUN, {
+ endpoint: "POST /api/projects/{id}/workflow (dry run)",
+ });
+ }
+
// Issue status catalog (MUL-6243). Reads are open to any workspace member;
// the mutations below are owner/admin only and return 403 otherwise.
async listIssueStatuses(includeArchived = false): Promise<ListIssueStatusesResponse> {
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 79743b76b4..539113259f 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -1,6 +1,11 @@
import { z } from "zod";
import { normalizeIssueStatusCategory } from "../issues/config/status";
import type {
+ WorkflowHandoffPreview,
+ IssueWorkflow,
+ IssueWorkflowDryRunResponse,
+ IssueWorkflowHandlerType,
+ ListIssueWorkflowsResponse,
AgentBuilderRuntimeSwitch,
AgentBuilderSession,
AgentBuilderSessionSummary,
@@ -536,6 +541,127 @@ export const EMPTY_LIST_ISSUE_STATUSES_RESPONSE: ListIssueStatusesResponse = {
total: 0,
};
+// Workspace workflows (MUL-7420). Handler types parse as plain strings and an
+// unknown one degrades to "none": a newer server may add a handler this build
+// cannot render, and the step's status must still show.
+const IssueWorkflowHandlerSchema = z.object({
+ type: z.string().transform((value): IssueWorkflowHandlerType =>
+ ISSUE_WORKFLOW_HANDLER_TYPES.has(value) ? (value as IssueWorkflowHandlerType) : "none",
+ ),
+ id: z.string().optional(),
+}).loose();
+
+const ISSUE_WORKFLOW_HANDLER_TYPES = new Set<string>([
+ "none", "agent", "squad", "member", "project_lead", "creator",
+]);
+
+const IssueWorkflowStepSchema = z.object({
+ status_key: z.string(),
+ handler: IssueWorkflowHandlerSchema.default({ type: "none" }),
+ instructions: z.string().default(""),
+ next_status_key: z.string().optional(),
+ back_status_key: z.string().optional(),
+}).loose();
+
+export const IssueWorkflowSchema = z.object({
+ id: z.string(),
+ workspace_id: z.string(),
+ name: z.string(),
+ description: z.string().default(""),
+ is_default: z.boolean().default(false),
+ steps: z.array(IssueWorkflowStepSchema).default([]),
+ project_ids: z.array(z.string()).default([]),
+ created_at: z.string(),
+ updated_at: z.string(),
+}).loose();
+
+export const ListIssueWorkflowsResponseSchema = z.object({
+ workflows: z.array(IssueWorkflowSchema).default([]),
+ total: z.number().default(0),
+}).loose();
+
+export const EMPTY_LIST_ISSUE_WORKFLOWS_RESPONSE: ListIssueWorkflowsResponse = {
+ workflows: [],
+ total: 0,
+};
+
+export const EMPTY_ISSUE_WORKFLOW: IssueWorkflow = {
+ id: "",
+ workspace_id: "",
+ name: "",
+ description: "",
+ is_default: false,
+ steps: [],
+ project_ids: [],
+ created_at: "",
+ updated_at: "",
+};
+
+export const IssueWorkflowMappingPlanSchema = z.object({
+ required: z.array(z.object({
+ status_key: z.string(),
+ issue_count: z.number().default(0),
+ suggested_status_key: z.string().default(""),
+ }).loose()).default([]),
+ unchanged: z.array(z.object({
+ status_key: z.string(),
+ issue_count: z.number().default(0),
+ }).loose()).default([]),
+ total_issues: z.number().default(0),
+ affected_issues: z.number().default(0),
+}).loose();
+
+export const IssueWorkflowDryRunResponseSchema = z.object({
+ dry_run: z.literal(true).default(true),
+ plan: IssueWorkflowMappingPlanSchema.default({ required: [], unchanged: [], total_issues: 0, affected_issues: 0 }),
+}).loose();
+
+export const EMPTY_ISSUE_WORKFLOW_DRY_RUN: IssueWorkflowDryRunResponse = {
+ dry_run: true,
+ plan: { required: [], unchanged: [], total_issues: 0, affected_issues: 0 },
+};
+
+export const IssueWorkflowBriefPreviewSchema = z.object({
+ brief: z.string().default(""),
+}).loose();
+
+const HANDOFF_HANDLER_TYPES = new Set(["agent", "squad", "member"]);
+
+export const WorkflowHandoffPreviewSchema = z.object({
+ handoff: z.boolean().default(false),
+ workflow_name: z.string().default(""),
+ from_status: z.string().default(""),
+ to_status: z.string().default(""),
+ handler_type: z.string().optional().transform((value): WorkflowHandoffPreview["handler_type"] =>
+ value && HANDOFF_HANDLER_TYPES.has(value) ? (value as "agent" | "squad" | "member") : null,
+ ),
+ handler_id: z.string().nullable().optional().transform((value) => value || null),
+ previous_assignee_type: z.string().nullable().default(null),
+ previous_assignee_id: z.string().nullable().default(null),
+ previous_runs: z.array(z.object({
+ task_id: z.string(),
+ agent_id: z.string(),
+ status: z.string().default(""),
+ started_at: z.string().nullable().default(null),
+ }).loose()).default([]),
+ brief: z.string().default(""),
+}).loose();
+
+// A preview the client cannot read says "no handoff": the write path still
+// applies the workflow, it only loses the confirmation.
+export const EMPTY_WORKFLOW_HANDOFF_PREVIEW: WorkflowHandoffPreview = {
+ handoff: false,
+ workflow_name: "",
+ from_status: "",
+ to_status: "",
+ handler_type: null,
+ handler_id: null,
+ previous_assignee_type: null,
+ previous_assignee_id: null,
+ previous_runs: [],
+ brief: "",
+};
+
export const ResourceLabelsResponseSchema = z.object({
labels: z.array(LabelSchema).default([]),
issue_revision: z.number().int().positive().optional(),
@@ -1417,6 +1543,7 @@ const ProjectSchema = z.object({
issue_count: z.number().default(0),
done_count: z.number().default(0),
resource_count: z.number().default(0),
+ workflow_id: z.string().nullable().default(null),
}).loose();
const SearchProjectResultSchema = ProjectSchema.extend({
diff --git a/packages/core/feature-flags/index.ts b/packages/core/feature-flags/index.ts
index 4683dcb667..c54f183f72 100644
--- a/packages/core/feature-flags/index.ts
+++ b/packages/core/feature-flags/index.ts
@@ -21,6 +21,7 @@ export {
BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,
COMPOSIO_MCP_APPS_FLAG,
PLUGINS_V1_FLAG,
+ PROJECT_WORKFLOWS_V1_FLAG,
} from "./keys";
export {
FeatureFlagsProvider,
diff --git a/packages/core/feature-flags/keys.ts b/packages/core/feature-flags/keys.ts
index db0dd7123d..957a3bfe23 100644
--- a/packages/core/feature-flags/keys.ts
+++ b/packages/core/feature-flags/keys.ts
@@ -2,3 +2,4 @@ export const COMPOSIO_MCP_APPS_FLAG = "composio_mcp_apps";
export const PLUGINS_V1_FLAG = "plugins_v1";
export const BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG =
"billing_workspace_subscriptions";
+export const PROJECT_WORKFLOWS_V1_FLAG = "project_workflows_v1";
diff --git a/packages/core/issue-workflows/hooks.ts b/packages/core/issue-workflows/hooks.ts
new file mode 100644
index 0000000000..144a5ec229
--- /dev/null
+++ b/packages/core/issue-workflows/hooks.ts
@@ -0,0 +1,41 @@
+import { useQuery } from "@tanstack/react-query";
+import { useMemo } from "react";
+import { projectListOptions } from "../projects/queries";
+import type { IssueWorkflow, Project } from "../types";
+import { issueWorkflowListOptions, resolveProjectWorkflow } from "./queries";
+
+const EMPTY: IssueWorkflow[] = [];
+
+/** The workspace's workflows, in name order. Empty until loaded. */
+export function useIssueWorkflows(wsId: string): { workflows: IssueWorkflow[]; isLoaded: boolean } {
+ const { data } = useQuery({ ...issueWorkflowListOptions(wsId), enabled: Boolean(wsId) });
+ return useMemo(() => ({ workflows: data ?? EMPTY, isLoaded: data !== undefined }), [data]);
+}
+
+/**
+ * A project and the workflow it uses. `workflow` is null for the Default
+ * workflow — including while either list is still loading, which renders the
+ * Default behavior rather than an empty board.
+ */
+export function useProjectWithWorkflow(
+ wsId: string,
+ projectId: string | null | undefined,
+): { project: Project | null; workflow: IssueWorkflow | null } {
+ const { workflows } = useIssueWorkflows(wsId);
+ const { data: projects } = useQuery({
+ ...projectListOptions(wsId),
+ enabled: Boolean(wsId) && Boolean(projectId),
+ });
+ return useMemo(() => {
+ const project = projectId ? projects?.find((p) => p.id === projectId) ?? null : null;
+ return { project, workflow: resolveProjectWorkflow(workflows, project) };
+ }, [projectId, projects, workflows]);
+}
+
+/** The workflow a project uses, or null for the Default workflow. */
+export function useProjectWorkflow(
+ wsId: string,
+ projectId: string | null | undefined,
+): IssueWorkflow | null {
+ return useProjectWithWorkflow(wsId, projectId).workflow;
+}
diff --git a/packages/core/issue-workflows/index.ts b/packages/core/issue-workflows/index.ts
new file mode 100644
index 0000000000..e47d60d56c
--- /dev/null
+++ b/packages/core/issue-workflows/index.ts
@@ -0,0 +1,29 @@
+export {
+ issueWorkflowKeys,
+ issueWorkflowListOptions,
+ resolveProjectWorkflow,
+ sharedWorkflowStatusKeys,
+ defaultWorkflow,
+ isFixedWorkflowStatus,
+ isOptionalWorkflowStatus,
+ statusAcceptsHandoff,
+ workflowMiddleKeys,
+ workflowNextStatus,
+ WORKFLOW_HEAD_STATUSES,
+ WORKFLOW_TAIL_STATUSES,
+ WORKFLOW_OPTIONAL_STATUSES,
+ workflowStep,
+ stepHandsOff,
+ workflowAllowsStatus,
+ projectMoveMayHandOff,
+ workflowHandoffPreviewOptions,
+ handoffStepCount,
+} from "./queries";
+export { useIssueWorkflows, useProjectWorkflow, useProjectWithWorkflow } from "./hooks";
+export {
+ useCreateIssueWorkflow,
+ useUpdateIssueWorkflow,
+ useDeleteIssueWorkflow,
+ useSetProjectWorkflow,
+ useSetWorkflowHandoff,
+} from "./mutations";
diff --git a/packages/core/issue-workflows/mutations.ts b/packages/core/issue-workflows/mutations.ts
new file mode 100644
index 0000000000..59d5037961
--- /dev/null
+++ b/packages/core/issue-workflows/mutations.ts
@@ -0,0 +1,107 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { api } from "../api";
+import { useWorkspaceId } from "../hooks";
+import { issueKeys } from "../issues/queries";
+import { projectKeys } from "../projects/queries";
+import type {
+ IssueWorkflowWriteRequest,
+ ListIssueWorkflowsResponse,
+ SetProjectWorkflowRequest,
+ SetWorkflowHandoffRequest,
+} from "../types";
+import { issueWorkflowKeys } from "./queries";
+
+/**
+ * Workflow mutations (MUL-7420).
+ *
+ * Like the status catalog, the list refreshes through the
+ * `issue_workflow:changed` realtime event; the writer only invalidates on
+ * failure, when its own copy is the likely stale one. A project switch or a
+ * step removal can move issues between statuses, and those moves arrive as
+ * ordinary issue events.
+ */
+
+export function useCreateIssueWorkflow() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (data: IssueWorkflowWriteRequest) => api.createIssueWorkflow(data),
+ onError: () => {
+ qc.invalidateQueries({ queryKey: issueWorkflowKeys.all(wsId) });
+ },
+ });
+}
+
+export function useUpdateIssueWorkflow() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: ({ id, ...data }: { id: string } & IssueWorkflowWriteRequest) =>
+ api.updateIssueWorkflow(id, data),
+ onError: () => {
+ qc.invalidateQueries({ queryKey: issueWorkflowKeys.all(wsId) });
+ },
+ });
+}
+
+export function useDeleteIssueWorkflow() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (id: string) => api.deleteIssueWorkflow(id),
+ onError: () => {
+ qc.invalidateQueries({ queryKey: issueWorkflowKeys.all(wsId) });
+ },
+ });
+}
+
+export function useSetProjectWorkflow() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: ({ projectId, ...data }: { projectId: string } & SetProjectWorkflowRequest) =>
+ api.setProjectWorkflow(projectId, data),
+ onSettled: (_data, _error, { projectId }) => {
+ qc.invalidateQueries({ queryKey: projectKeys.list(wsId) });
+ qc.invalidateQueries({ queryKey: projectKeys.detail(wsId, projectId) });
+ // project_ids on each workflow row changed.
+ qc.invalidateQueries({ queryKey: issueWorkflowKeys.all(wsId) });
+ // Remapped issues moved columns.
+ qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });
+ },
+ });
+}
+
+/**
+ * Saves a workflow's handoff for one column, for every project using it — or,
+ * with `copyForProjectId`, on a copy only that project uses.
+ */
+export function useSetWorkflowHandoff() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: ({
+ workflowId,
+ statusKey,
+ copyForProjectId,
+ ...data
+ }: { workflowId: string; statusKey: string; copyForProjectId?: string } & SetWorkflowHandoffRequest) =>
+ api.setWorkflowHandoff(workflowId, statusKey, data, copyForProjectId),
+ onSuccess: (saved, { workflowId, copyForProjectId }) => {
+ if (!saved.id) return;
+ if (copyForProjectId) {
+ // A new workflow row, and the project now points at it.
+ qc.invalidateQueries({ queryKey: issueWorkflowKeys.all(wsId) });
+ qc.invalidateQueries({ queryKey: projectKeys.list(wsId) });
+ qc.invalidateQueries({ queryKey: projectKeys.detail(wsId, copyForProjectId) });
+ return;
+ }
+ qc.setQueryData<ListIssueWorkflowsResponse>(issueWorkflowKeys.list(wsId), (old) =>
+ old && { ...old, workflows: old.workflows.map((w) => (w.id === workflowId ? saved : w)) },
+ );
+ },
+ onError: () => {
+ qc.invalidateQueries({ queryKey: issueWorkflowKeys.all(wsId) });
+ },
+ });
+}
diff --git a/packages/core/issue-workflows/queries.test.ts b/packages/core/issue-workflows/queries.test.ts
new file mode 100644
index 0000000000..c94f78eb6e
--- /dev/null
+++ b/packages/core/issue-workflows/queries.test.ts
@@ -0,0 +1,111 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { IssueWorkflow, IssueWorkflowStep } from "../types";
+import {
+ projectMoveMayHandOff,
+ resolveProjectWorkflow,
+ stepHandsOff,
+ statusAcceptsHandoff,
+ workflowAllowsStatus,
+ workflowMiddleKeys,
+ workflowNextStatus,
+ workflowStep,
+} from "./queries";
+
+const manual = (status_key: string): IssueWorkflowStep => ({ status_key, handler: { type: "none" }, instructions: "" });
+
+const columns = (...middle: string[]) =>
+ ["backlog", "todo", ...middle, "blocked", "done", "cancelled"].map(manual);
+
+const defaultWorkflow: IssueWorkflow = {
+ id: "wf-default",
+ workspace_id: "ws-1",
+ name: "Default",
+ description: "",
+ is_default: true,
+ steps: columns("in_progress", "in_review"),
+ project_ids: [],
+ created_at: "",
+ updated_at: "",
+};
+
+const content: IssueWorkflow = {
+ ...defaultWorkflow,
+ id: "wf-content",
+ name: "Content",
+ is_default: false,
+ steps: columns("drafting", "editing"),
+};
+
+const lead: IssueWorkflowStep = { status_key: "in_review", handler: { type: "project_lead" }, instructions: "Review it." };
+
+describe("project workflow resolution (MUL-7420)", () => {
+ it("uses the project's workflow, else Default", () => {
+ expect(resolveProjectWorkflow([defaultWorkflow, content], { workflow_id: "wf-content" })?.id).toBe("wf-content");
+ expect(resolveProjectWorkflow([defaultWorkflow, content], { workflow_id: null })?.id).toBe("wf-default");
+ // A dangling reference renders as Default, like the server treats it.
+ expect(resolveProjectWorkflow([defaultWorkflow, content], { workflow_id: "gone" })?.id).toBe("wf-default");
+ });
+
+ it("is unknown while workflows load or without a project", () => {
+ expect(resolveProjectWorkflow(undefined, { workflow_id: null })).toBeNull();
+ expect(resolveProjectWorkflow([defaultWorkflow], undefined)).toBeNull();
+ expect(resolveProjectWorkflow([], { workflow_id: null })).toBeNull();
+ });
+
+ it("carries the workflow's own handoffs", () => {
+ const reviewed = { ...content, steps: content.steps.map((s) => (s.status_key === "editing" ? { ...lead, status_key: "editing" } : s)) };
+ const resolved = resolveProjectWorkflow([defaultWorkflow, reviewed], { workflow_id: "wf-content" });
+ expect(stepHandsOff(workflowStep(resolved, "editing"))).toBe(true);
+ expect(workflowStep(resolved, "editing")?.instructions).toBe("Review it.");
+ expect(stepHandsOff(workflowStep(resolved, "drafting"))).toBe(false);
+ });
+});
+
+describe("workflow helpers (MUL-7420)", () => {
+ it("allows any status under Default and only listed ones under a named workflow", () => {
+ expect(workflowAllowsStatus(null, "drafting")).toBe(true);
+ expect(workflowAllowsStatus(defaultWorkflow, "drafting")).toBe(true);
+ expect(workflowAllowsStatus(content, "drafting")).toBe(true);
+ expect(workflowAllowsStatus(content, "in_progress")).toBe(false);
+ });
+
+ it("names the middle columns and who may hand off", () => {
+ expect(workflowMiddleKeys(content)).toEqual(["drafting", "editing"]);
+ expect(statusAcceptsHandoff("todo")).toBe(true);
+ expect(statusAcceptsHandoff("blocked")).toBe(true);
+ expect(statusAcceptsHandoff("backlog")).toBe(false);
+ expect(statusAcceptsHandoff("done")).toBe(false);
+ });
+
+ it("points a step at the next column unless it names its own", () => {
+ expect(workflowNextStatus(content, "drafting")).toBe("editing");
+ // blocked is a detour, not the next step.
+ expect(workflowNextStatus(content, "editing")).toBe("done");
+ const own = { ...content, steps: content.steps.map((s) => (s.status_key === "drafting" ? { ...s, next_status_key: "done" } : s)) };
+ expect(workflowNextStatus(own, "drafting")).toBe("done");
+ expect(workflowNextStatus(content, "cancelled")).toBe("");
+ expect(workflowNextStatus(content, "missing")).toBe("");
+ });
+});
+
+describe("projectMoveMayHandOff", () => {
+ const handsOffDrafting: IssueWorkflow = {
+ ...content,
+ steps: content.steps.map((s) => (s.status_key === "drafting" ? { ...s, handler: { type: "agent", id: "a-1" } } : s)),
+ };
+
+ it("checks the column the issue keeps", () => {
+ expect(projectMoveMayHandOff(handsOffDrafting, "drafting")).toBe(true);
+ expect(projectMoveMayHandOff(handsOffDrafting, "todo")).toBe(false);
+ });
+
+ it("asks the server when the issue lands on another column", () => {
+ expect(projectMoveMayHandOff(handsOffDrafting, "in_progress")).toBe(true);
+ expect(projectMoveMayHandOff(content, "in_progress")).toBe(false);
+ });
+
+ it("never asks without a workflow", () => {
+ expect(projectMoveMayHandOff(null, "todo")).toBe(false);
+ });
+});
diff --git a/packages/core/issue-workflows/queries.ts b/packages/core/issue-workflows/queries.ts
new file mode 100644
index 0000000000..418f742f25
--- /dev/null
+++ b/packages/core/issue-workflows/queries.ts
@@ -0,0 +1,170 @@
+import { queryOptions } from "@tanstack/react-query";
+import { api } from "../api";
+import type { IssueWorkflow, IssueWorkflowStep, Project } from "../types";
+
+/**
+ * Workspace workflows (MUL-7420).
+ *
+ * A project's board is its workflow's columns — the named one it picked, or
+ * the workspace Default — with that workflow's handoffs on them. Helpers
+ * return null only while workflows are unknown (still loading, or a server
+ * without workflows), and callers then keep their pre-workflow behavior.
+ */
+
+export const issueWorkflowKeys = {
+ all: (wsId: string) => ["issue-workflows", wsId] as const,
+ list: (wsId: string) => [...issueWorkflowKeys.all(wsId), "list"] as const,
+ handoffPreview: (wsId: string, issueId: string, status: string, projectId = "") =>
+ [...issueWorkflowKeys.all(wsId), "handoff-preview", issueId, status, projectId] as const,
+};
+
+/**
+ * What moving an issue to `status` — or into project `projectId` — would do.
+ * Short-lived: the answer depends on the issue's assignee and runs, which
+ * change under it.
+ */
+export function workflowHandoffPreviewOptions(wsId: string, issueId: string, status: string, projectId?: string) {
+ return queryOptions({
+ queryKey: issueWorkflowKeys.handoffPreview(wsId, issueId, status, projectId),
+ queryFn: () => api.previewWorkflowHandoff(issueId, status, projectId),
+ staleTime: 0,
+ gcTime: 30_000,
+ });
+}
+
+export function issueWorkflowListOptions(wsId: string) {
+ return queryOptions({
+ queryKey: issueWorkflowKeys.list(wsId),
+ queryFn: () => api.listIssueWorkflows(),
+ select: (data) => data.workflows,
+ // Workflows change only when an admin edits one; the
+ // `issue_workflow:changed` event refreshes every client when that happens.
+ staleTime: 5 * 60_000,
+ });
+}
+
+/** The workspace Default workflow, once loaded. */
+export function defaultWorkflow(workflows: readonly IssueWorkflow[] | undefined): IssueWorkflow | null {
+ return workflows?.find((w) => w.is_default) ?? null;
+}
+
+/** Statuses with fixed places at the ends of a workflow, in the order they sit. */
+export const WORKFLOW_HEAD_STATUSES = ["backlog", "todo"] as const;
+export const WORKFLOW_TAIL_STATUSES = ["blocked", "done", "cancelled"] as const;
+/** Fixed statuses a workflow may leave out; the others every workflow lists. */
+export const WORKFLOW_OPTIONAL_STATUSES = ["backlog", "blocked"] as const;
+const FIXED_STATUSES = new Set<string>([...WORKFLOW_HEAD_STATUSES, ...WORKFLOW_TAIL_STATUSES]);
+const OPTIONAL_STATUSES = new Set<string>(WORKFLOW_OPTIONAL_STATUSES);
+const NO_HANDOFF_STATUSES = new Set(["backlog", "done", "cancelled"]);
+
+/** Whether a status has a fixed place when a workflow lists it. */
+export function isFixedWorkflowStatus(statusKey: string): boolean {
+ return FIXED_STATUSES.has(statusKey);
+}
+
+/** Whether a fixed status may be left out of a workflow. */
+export function isOptionalWorkflowStatus(statusKey: string): boolean {
+ return OPTIONAL_STATUSES.has(statusKey);
+}
+
+/** Whether a column can have a handler: parking and closing columns cannot. */
+export function statusAcceptsHandoff(statusKey: string): boolean {
+ return !NO_HANDOFF_STATUSES.has(statusKey);
+}
+
+/** The columns between the fixed head and tail, in order. */
+export function workflowMiddleKeys(workflow: Pick<IssueWorkflow, "steps">): string[] {
+ return workflow.steps.map((s) => s.status_key).filter((k) => !FIXED_STATUSES.has(k));
+}
+
+/**
+ * The column a step's handler is told to move to when done: the step's own
+ * choice, else the next column (skipping blocked); empty at the end.
+ */
+export function workflowNextStatus(workflow: Pick<IssueWorkflow, "steps">, statusKey: string): string {
+ const index = workflow.steps.findIndex((s) => s.status_key === statusKey);
+ if (index < 0) return "";
+ const own = workflow.steps[index]?.next_status_key;
+ if (own) return own;
+ for (const s of workflow.steps.slice(index + 1)) {
+ if (s.status_key !== "blocked") return s.status_key;
+ }
+ return "";
+}
+
+/**
+ * The workflow a project uses — its named one, else Default; null while
+ * workflows are unknown.
+ */
+export function resolveProjectWorkflow(
+ workflows: readonly IssueWorkflow[] | undefined,
+ project: Pick<Project, "workflow_id"> | null | undefined,
+): IssueWorkflow | null {
+ if (!project || !workflows) return null;
+ const named = project.workflow_id ? workflows.find((w) => w.id === project.workflow_id) : undefined;
+ return named ?? defaultWorkflow(workflows);
+}
+
+/**
+ * The statuses every one of `issues` may take, or null when none is limited.
+ * Only a named workflow limits an issue's statuses; Default and issues outside
+ * a project accept the whole catalog, as the server does. A batch status
+ * change offers this set, so it never shows a status the server would skip.
+ */
+export function sharedWorkflowStatusKeys(
+ workflows: readonly IssueWorkflow[] | undefined,
+ projects: readonly Pick<Project, "id" | "workflow_id">[] | undefined,
+ issues: readonly { project_id: string | null }[],
+): Set<string> | null {
+ let shared = null as Set<string> | null;
+ for (const issue of issues) {
+ const project = issue.project_id ? projects?.find((p) => p.id === issue.project_id) : undefined;
+ const workflow = resolveProjectWorkflow(workflows, project);
+ if (!workflow || workflow.is_default) continue;
+ const keys = new Set(workflow.steps.map((s) => s.status_key));
+ shared = shared ? new Set([...shared].filter((key) => keys.has(key))) : keys;
+ }
+ return shared;
+}
+
+export function workflowStep(
+ workflow: IssueWorkflow | null | undefined,
+ statusKey: string,
+): IssueWorkflowStep | undefined {
+ return workflow?.steps.find((s) => s.status_key === statusKey);
+}
+
+/** Whether entering the step reassigns the issue. */
+export function stepHandsOff(step: IssueWorkflowStep | undefined): boolean {
+ return !!step && step.handler.type !== "none";
+}
+
+/**
+ * Whether a status is allowed for issues of a project using `workflow`.
+ * Default allows every status, as the server does, so an issue on a status
+ * Default no longer lists can still be moved off and back.
+ */
+export function workflowAllowsStatus(
+ workflow: IssueWorkflow | null | undefined,
+ statusKey: string,
+): boolean {
+ if (!workflow || workflow.is_default) return true;
+ return workflow.steps.some((s) => s.status_key === statusKey);
+}
+
+/**
+ * Whether moving an issue on `statusKey` into a project using `workflow` may
+ * hand it off, when the move enters the column it lands on: the column it
+ * keeps hands off, or it lands on another column and some column does. The
+ * server preview has the final word.
+ */
+export function projectMoveMayHandOff(workflow: IssueWorkflow | null | undefined, statusKey: string): boolean {
+ if (!workflow) return false;
+ if (workflowAllowsStatus(workflow, statusKey)) return stepHandsOff(workflowStep(workflow, statusKey));
+ return workflow.steps.some(stepHandsOff);
+}
+
+/** Steps whose entry reassigns the issue. */
+export function handoffStepCount(workflow: IssueWorkflow): number {
+ return workflow.steps.filter((s) => s.handler.type !== "none").length;
+}
diff --git a/packages/core/issue-workflows/schemas.test.ts b/packages/core/issue-workflows/schemas.test.ts
new file mode 100644
index 0000000000..15196c7233
--- /dev/null
+++ b/packages/core/issue-workflows/schemas.test.ts
@@ -0,0 +1,112 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { parseWithFallback } from "../api/schema";
+import {
+ EMPTY_ISSUE_WORKFLOW_DRY_RUN,
+ EMPTY_LIST_ISSUE_WORKFLOWS_RESPONSE,
+ IssueWorkflowDryRunResponseSchema,
+ IssueWorkflowSchema,
+ ListIssueWorkflowsResponseSchema,
+ WorkflowHandoffPreviewSchema,
+ EMPTY_WORKFLOW_HANDOFF_PREVIEW,
+} from "../api/schemas";
+
+const baseWorkflow = {
+ id: "wf-1",
+ workspace_id: "ws-1",
+ name: "Delivery",
+ description: "",
+ is_default: false,
+ steps: [
+ { status_key: "todo", handler: { type: "none" }, instructions: "" },
+ {
+ status_key: "code_review",
+ handler: { type: "agent", id: "agent-1" },
+ instructions: "Review the PR.",
+ next_status_key: "done",
+ back_status_key: "todo",
+ },
+ ],
+ project_ids: ["project-1"],
+ created_at: "2026-09-24T00:00:00Z",
+ updated_at: "2026-09-24T00:00:00Z",
+};
+
+describe("workflow schemas (MUL-7420)", () => {
+ it("parses a workflow list", () => {
+ const parsed = ListIssueWorkflowsResponseSchema.parse({ workflows: [baseWorkflow], total: 1 });
+ expect(parsed.workflows[0]?.steps[1]?.handler).toEqual({ type: "agent", id: "agent-1" });
+ expect(parsed.workflows[0]?.project_ids).toEqual(["project-1"]);
+ });
+
+ it("falls back to an empty list on a malformed response", () => {
+ const parsed = parseWithFallback(
+ { workflows: "nope" },
+ ListIssueWorkflowsResponseSchema,
+ EMPTY_LIST_ISSUE_WORKFLOWS_RESPONSE,
+ { endpoint: "GET /api/issue-workflows" },
+ );
+ expect(parsed).toEqual(EMPTY_LIST_ISSUE_WORKFLOWS_RESPONSE);
+ });
+
+ it("degrades an unknown handler type to a manual step", () => {
+ const parsed = IssueWorkflowSchema.parse({
+ ...baseWorkflow,
+ steps: [{ status_key: "todo", handler: { type: "robot", id: "x" } }],
+ });
+ expect(parsed.steps[0]?.handler.type).toBe("none");
+ expect(parsed.steps[0]?.instructions).toBe("");
+ });
+
+ it("defaults the optional fields an older server may omit", () => {
+ const { description: _d, project_ids: _p, ...minimal } = baseWorkflow;
+ const parsed = IssueWorkflowSchema.parse({ ...minimal, steps: [{ status_key: "todo" }] });
+ expect(parsed.description).toBe("");
+ expect(parsed.project_ids).toEqual([]);
+ expect(parsed.steps[0]?.handler.type).toBe("none");
+ });
+
+ it("reads a workflow row's status-only steps as manual columns", () => {
+ const parsed = IssueWorkflowSchema.parse({ ...baseWorkflow, is_default: true, steps: [{ status_key: "todo" }] });
+ expect(parsed.is_default).toBe(true);
+ expect(parsed.steps[0]).toEqual({ status_key: "todo", handler: { type: "none" }, instructions: "" });
+ });
+
+ it("falls back to an empty plan on a malformed dry run", () => {
+ const parsed = parseWithFallback(
+ { plan: { required: 5 } },
+ IssueWorkflowDryRunResponseSchema,
+ EMPTY_ISSUE_WORKFLOW_DRY_RUN,
+ { endpoint: "POST /api/projects/{id}/workflow (dry run)" },
+ );
+ expect(parsed).toEqual(EMPTY_ISSUE_WORKFLOW_DRY_RUN);
+ });
+
+ it("parses a handoff preview and degrades an unknown handler type", () => {
+ const parsed = WorkflowHandoffPreviewSchema.parse({
+ handoff: true,
+ workflow_name: "Delivery",
+ from_status: "implement",
+ to_status: "code_review",
+ handler_type: "agent",
+ handler_id: "agent-2",
+ previous_assignee_type: "agent",
+ previous_assignee_id: "agent-1",
+ previous_runs: [{ task_id: "t1", agent_id: "agent-1", status: "running", started_at: "2026-09-24T00:00:00Z" }],
+ brief: "This project's workflow — Delivery",
+ });
+ expect(parsed.handler_type).toBe("agent");
+ expect(parsed.previous_runs).toHaveLength(1);
+ expect(WorkflowHandoffPreviewSchema.parse({ handoff: true, handler_type: "robot" }).handler_type).toBeNull();
+ });
+
+ it("treats a malformed handoff preview as no handoff", () => {
+ const parsed = parseWithFallback(
+ { handoff: "yes", previous_runs: 3 },
+ WorkflowHandoffPreviewSchema,
+ EMPTY_WORKFLOW_HANDOFF_PREVIEW,
+ { endpoint: "GET /api/issues/{id}/workflow-handoff" },
+ );
+ expect(parsed).toEqual(EMPTY_WORKFLOW_HANDOFF_PREVIEW);
+ });
+});
diff --git a/packages/core/issues/config/status.ts b/packages/core/issues/config/status.ts
index da441bfff5..83cd9b7ddf 100644
--- a/packages/core/issues/config/status.ts
+++ b/packages/core/issues/config/status.ts
@@ -63,7 +63,7 @@ export const STATUS_CONFIG: Record<
}
> = {
unstarted: { label: "Unstarted", iconColor: "text-muted-foreground", hoverBg: "hover:bg-accent", dividerColor: "bg-muted-foreground/40", columnBg: "bg-muted/40" },
- started: { label: "Started", iconColor: "text-warning", hoverBg: "hover:bg-warning/10", dividerColor: "bg-warning", columnBg: "bg-warning/5" },
- done: { label: "Done", iconColor: "text-info", hoverBg: "hover:bg-info/10", dividerColor: "bg-info", columnBg: "bg-info/5" },
+ started: { label: "Started", iconColor: "text-warning", hoverBg: "hover:bg-warning/10", dividerColor: "bg-warning", columnBg: "bg-muted/40" },
+ done: { label: "Done", iconColor: "text-info", hoverBg: "hover:bg-info/10", dividerColor: "bg-info", columnBg: "bg-muted/40" },
closed: { label: "Closed", iconColor: "text-muted-foreground", hoverBg: "hover:bg-accent", dividerColor: "bg-muted-foreground/40", columnBg: "bg-muted/40" },
};
diff --git a/packages/core/issues/mutations.test.tsx b/packages/core/issues/mutations.test.tsx
index aea920f5d2..babad7f0b2 100644
--- a/packages/core/issues/mutations.test.tsx
+++ b/packages/core/issues/mutations.test.tsx
@@ -734,6 +734,27 @@ describe("useBatchUpdateIssues — optimistic patch covers filtered boards too",
});
});
+ it("rolls back and refetches when the server skips some issues", async () => {
+ batchUpdateIssues.mockResolvedValue({ updated: 0 });
+ const invalidateSpy = vi.spyOn(qc, "invalidateQueries");
+
+ const { result } = renderHook(() => useBatchUpdateIssues(), {
+ wrapper: createWrapper(qc),
+ });
+
+ await act(async () => {
+ await result.current.mutateAsync({ ids: ["issue-1"], updates: { status: "in_progress" } });
+ });
+
+ for (const key of [wsKey, myKey]) {
+ expect(bucketIds(key, "unstarted")).toEqual(["issue-1"]);
+ expect(bucketIds(key, "started")).toEqual([]);
+ }
+ const invalidatedKeys = invalidateSpy.mock.calls.map((c) => c[0]?.queryKey);
+ expect(invalidatedKeys).toContainEqual(issueKeys.list(WS_ID));
+ expect(invalidatedKeys).toContainEqual(issueKeys.detail(WS_ID, "issue-1"));
+ });
+
it("rolls both caches back when the request fails", async () => {
batchUpdateIssues.mockRejectedValue(new Error("boom"));
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index 8f28beb073..072e91644e 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -200,6 +200,8 @@ export function useUpdateIssue() {
// a rapid follow-up edit. mutationFn still sends the full payload.
const {
suppress_run: _suppressRun,
+ stop_previous_assignee_runs: _stopPreviousAssigneeRuns,
+ enter_workflow_step: _enterWorkflowStep,
duplicate_of_issue_id: _duplicateOfIssueId,
description: _description,
description_base: _descriptionBase,
@@ -312,6 +314,8 @@ export function useUpdateIssue() {
// is the plain surgical patch it always was.
const {
suppress_run: _suppressRun,
+ stop_previous_assignee_runs: _stopPreviousAssigneeRuns,
+ enter_workflow_step: _enterWorkflowStep,
duplicate_of_issue_id: _duplicateOfIssueId,
description_base: _descriptionBase,
move_intent: _moveIntent,
@@ -497,9 +501,30 @@ export function useDeleteIssue() {
});
}
+interface BatchUpdateSnapshots {
+ prevLists?: Iterable<readonly [QueryKey, unknown]>;
+ prevFlatLists?: Iterable<readonly [QueryKey, unknown]>;
+ prevTableRows?: Iterable<readonly [QueryKey, unknown]>;
+ prevDetailById?: Iterable<readonly [string, unknown]>;
+ prevInboxList?: unknown;
+ prevArchivedInboxCaches?: Iterable<readonly [QueryKey, unknown]>;
+ prevChildren?: Iterable<readonly [string, unknown]>;
+}
+
export function useBatchUpdateIssues() {
const qc = useQueryClient();
const wsId = useWorkspaceId();
+ const rollback = (ctx: BatchUpdateSnapshots | undefined) => {
+ for (const [key, snapshot] of ctx?.prevLists ?? []) qc.setQueryData(key, snapshot);
+ for (const [key, snapshot] of ctx?.prevFlatLists ?? []) qc.setQueryData(key, snapshot);
+ for (const [key, snapshot] of ctx?.prevTableRows ?? []) qc.setQueryData(key, snapshot);
+ for (const [id, snapshot] of ctx?.prevDetailById ?? []) qc.setQueryData(issueKeys.detail(wsId, id), snapshot);
+ if (ctx?.prevInboxList !== undefined) qc.setQueryData(inboxKeys.list(wsId), ctx.prevInboxList);
+ for (const [key, snapshot] of ctx?.prevArchivedInboxCaches ?? []) qc.setQueryData(key, snapshot);
+ for (const [parentId, snapshot] of ctx?.prevChildren ?? []) {
+ qc.setQueryData(issueKeys.children(wsId, parentId), snapshot);
+ }
+ };
return useMutation({
mutationKey: issueWriteMutationKey(wsId),
mutationFn: ({
@@ -516,6 +541,8 @@ export function useBatchUpdateIssues() {
// until a refetch returns the committed result.
const {
suppress_run: _suppressRun,
+ stop_previous_assignee_runs: _stopPreviousAssigneeRuns,
+ enter_workflow_step: _enterWorkflowStep,
description: _description,
description_base: _descriptionBase,
...patch
@@ -612,38 +639,18 @@ export function useBatchUpdateIssues() {
affectedParentIds,
};
},
- onError: (_err, _vars, ctx) => {
- if (ctx?.prevLists) {
- for (const [key, snapshot] of ctx.prevLists) {
- qc.setQueryData(key, snapshot);
- }
- }
- if (ctx?.prevFlatLists) {
- for (const [key, snapshot] of ctx.prevFlatLists) {
- qc.setQueryData(key, snapshot);
- }
- }
- if (ctx?.prevTableRows) {
- for (const [key, snapshot] of ctx.prevTableRows) {
- qc.setQueryData(key, snapshot);
- }
- }
- if (ctx?.prevDetailById) {
- for (const [id, snapshot] of ctx.prevDetailById) {
- qc.setQueryData(issueKeys.detail(wsId, id), snapshot);
- }
- }
- if (ctx?.prevInboxList !== undefined) {
- qc.setQueryData(inboxKeys.list(wsId), ctx.prevInboxList);
- }
- for (const [key, snapshot] of ctx?.prevArchivedInboxCaches ?? []) {
- qc.setQueryData(key, snapshot);
- }
- if (ctx?.prevChildren) {
- for (const [parentId, snapshot] of ctx.prevChildren) {
- qc.setQueryData(issueKeys.children(wsId, parentId), snapshot);
- }
- }
+ onError: (_err, _vars, ctx) => rollback(ctx),
+ // The server skips items its per-issue guards refuse (a status the
+ // issue's workflow does not list, an assignee it cannot take) and reports
+ // only how many it wrote. Which ones were skipped is unknown, so the
+ // optimistic writes are undone and the affected caches refetched.
+ onSuccess: (data, { ids }, ctx) => {
+ if (data.updated >= ids.length) return;
+ rollback(ctx);
+ qc.invalidateQueries({ queryKey: issueKeys.list(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.flatAll(wsId) });
+ for (const id of ids) qc.invalidateQueries({ queryKey: issueKeys.detail(wsId, id) });
},
onSettled: (_data, err, _vars, ctx) => {
settleInboxAfterIssueWrite(qc, wsId, ctx?.inboxWrite, err !== null);
diff --git a/packages/core/modals/store.ts b/packages/core/modals/store.ts
index 3c9664438b..5711839f0d 100644
--- a/packages/core/modals/store.ts
+++ b/packages/core/modals/store.ts
@@ -13,6 +13,7 @@ type ModalType =
| "issue-add-child"
| "issue-delete-confirm"
| "issue-run-confirm"
+ | "issue-workflow-handoff"
| null;
export type IssueLimitRecoveryReason = "issue_limit" | "autopilot_quota";
diff --git a/packages/core/package.json b/packages/core/package.json
index b6301e6430..63a4dac901 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -34,6 +34,10 @@
"./issue-statuses/queries": "./issue-statuses/queries.ts",
"./issue-statuses/hooks": "./issue-statuses/hooks.ts",
"./issue-statuses/mutations": "./issue-statuses/mutations.ts",
+ "./issue-workflows": "./issue-workflows/index.ts",
+ "./issue-workflows/queries": "./issue-workflows/queries.ts",
+ "./issue-workflows/hooks": "./issue-workflows/hooks.ts",
+ "./issue-workflows/mutations": "./issue-workflows/mutations.ts",
"./issues": "./issues/index.ts",
"./issues/batch": "./issues/batch.ts",
"./issues/canonical-id": "./issues/canonical-id.ts",
diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
index aeaea6c8a6..334b9122f6 100644
--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
@@ -13,6 +13,7 @@ import { runtimeKeys } from "../runtimes/queries";
import { workspaceWorkingAgentsKeys } from "../agents/queries";
import { workspaceKeys } from "../workspace/queries";
import { issueStatusKeys } from "../issue-statuses/queries";
+import { issueWorkflowKeys } from "../issue-workflows/queries";
import {
markWorkspaceDeletePending,
unmarkWorkspaceDeletePending,
@@ -126,15 +127,15 @@ describe("useRealtimeSync — ws instance change", () => {
rerender({ ws: ws2 });
// Should have called invalidateQueries for all workspace-scoped keys
- // (16 workspace-scoped [incl. property definitions] + 6 per-issue
- // prefixes + the workspace working-agents projection + 5 per-chat
- // prefixes + 1 workspaceKeys.list() + 1 cross-workspace inbox unread
- // summary = 31 calls).
+ // (17 workspace-scoped [incl. property definitions and workflows] + 6
+ // per-issue prefixes + the workspace working-agents projection + 5
+ // per-chat prefixes + 1 workspaceKeys.list() + 1 cross-workspace inbox
+ // unread summary = 32 calls).
//
// Awaited rather than counted synchronously: the inbox unread summary
// refresh cancels any in-flight request before invalidating (see
// onInboxSummaryInvalidate), so that one lands after the synchronous ones.
- await waitFor(() => expect(invalidateSpy).toHaveBeenCalledTimes(31));
+ await waitFor(() => expect(invalidateSpy).toHaveBeenCalledTimes(32));
});
it("does not re-invalidate when rerendered with the same ws instance", () => {
@@ -173,6 +174,24 @@ describe("useRealtimeSync — ws instance change", () => {
expect(calls).toContainEqual(issueStatusKeys.all("ws-1"));
});
+ it.each(["project:created", "project:updated", "project:deleted"])("refreshes workflow usage after %s", (type) => {
+ vi.useFakeTimers();
+ try {
+ const ws = createMockWs();
+ renderHook(() => useRealtimeSync(ws, stores), { wrapper: createWrapper(qc) });
+ const onAny = vi.mocked(ws.onAny).mock.calls[0]![0];
+ invalidateSpy.mockClear();
+
+ onAny({ type, payload: {} } as never);
+ vi.advanceTimersByTime(100);
+
+ expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: issueWorkflowKeys.all("ws-1") });
+ expect(invalidateSpy).not.toHaveBeenCalledWith({ queryKey: issueWorkflowKeys.all("ws-2") });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("invalidates agent projections when a daemon changes liveness", () => {
vi.useFakeTimers();
try {
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 6bbe715f4b..1762486cf6 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -18,6 +18,7 @@ import { runtimeKeys } from "../runtimes/queries";
import { labelKeys } from "../labels/queries";
import { propertyKeys } from "../properties/queries";
import { issueStatusKeys } from "../issue-statuses/queries";
+import { issueWorkflowKeys } from "../issue-workflows/queries";
import {
agentTaskSnapshotKeys,
workspaceWorkingAgentsKeys,
@@ -668,6 +669,7 @@ function invalidateWorkspaceScopedQueries(qc: QueryClient): void {
// 5-minute staleTime — long enough to offer a status the server already
// archived, or to keep painting its old name.
qc.invalidateQueries({ queryKey: issueStatusKeys.all(wsId) });
+ qc.invalidateQueries({ queryKey: issueWorkflowKeys.all(wsId) });
}
// Cross-workspace, so outside the wsId guard: a reconnect may have missed
// inbox events from any workspace, so re-pull the switcher-dot summary.
@@ -827,6 +829,9 @@ export function useRealtimeSync(
const wsId = getCurrentWsId();
if (wsId) {
qc.invalidateQueries({ queryKey: projectKeys.all(wsId) });
+ // Workflow responses include the projects using them. Creating,
+ // deleting or changing a project also changes that usage list.
+ qc.invalidateQueries({ queryKey: issueWorkflowKeys.all(wsId) });
// The issue table can filter on a project's status, so a
// project create/update/delete changes which issues a filtered
// window holds. The payload carries no previous status to compare
@@ -882,6 +887,12 @@ export function useRealtimeSync(
});
}
},
+ // Workspace workflows (MUL-7420). Same contract as the status catalog:
+ // the event carries no row, so every write answers with one list read.
+ issue_workflow: () => {
+ const wsId = getCurrentWsId();
+ if (wsId) qc.invalidateQueries({ queryKey: issueWorkflowKeys.all(wsId) });
+ },
pin: () => {
const wsId = getCurrentWsId();
const userId = authStore.getState().user?.id;
diff --git a/packages/core/types/api.ts b/packages/core/types/api.ts
index 50b07951bd..ae31216179 100644
--- a/packages/core/types/api.ts
+++ b/packages/core/types/api.ts
@@ -80,6 +80,15 @@ export interface UpdateIssueRequest {
* MUL-3375). The assignee/status change still applies. Control field —
* strip from optimistic cache patches; never written onto the Issue. */
suppress_run?: boolean;
+ /** When a status change hands the issue off to a workflow step's handler,
+ * also stop the active runs of the agent it was taken from (MUL-7420).
+ * Control field — strip from optimistic cache patches. */
+ stop_previous_assignee_runs?: boolean;
+ /** With a project move: enter the destination workflow's column the issue
+ * lands on, handing it off like a status change (MUL-7420). Without it a
+ * project move is administrative. Control field — strip from optimistic
+ * cache patches. */
+ enter_workflow_step?: boolean;
/** Marks this issue as a duplicate of another issue (MUL-7349). The server
* also sets status to cancelled; any later status change away from
* cancelled removes the mark. Write-only — read it back through
@@ -108,6 +117,7 @@ export interface MoveIssueRequest
| "assignee_id"
| "parent_issue_id"
| "project_id"
+ | "stop_previous_assignee_runs"
> {
before_id: string | null;
after_id: string | null;
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index bc7d791f6a..2617b68c9b 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -79,6 +79,7 @@ export type WSEventType =
| "property:created"
| "property:updated"
| "issue_status:changed"
+ | "issue_workflow:changed"
| "pin:created"
| "pin:deleted"
| "pin:reordered"
@@ -170,6 +171,10 @@ export interface IssueStatusChangedPayload {
action?: "created" | "updated" | "archived" | "reordered";
}
+export interface IssueWorkflowChangedPayload {
+ action?: "created" | "updated" | "deleted";
+}
+
export interface AgentStatusPayload {
agent: Agent;
}
@@ -578,6 +583,7 @@ export interface WSEventPayloadMap {
"property:created": PropertyChangedPayload;
"property:updated": PropertyChangedPayload;
"issue_status:changed": IssueStatusChangedPayload;
+ "issue_workflow:changed": IssueWorkflowChangedPayload;
"issue_reaction:added": IssueReactionAddedPayload;
"issue_reaction:removed": IssueReactionRemovedPayload;
"comment:created": CommentCreatedPayload;
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index de65f707fc..ef70ded997 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -9,6 +9,24 @@ export type {
CreateIssueStatusRequest,
UpdateIssueStatusRequest,
} from "./issue-status";
+export type {
+ IssueWorkflow,
+ IssueWorkflowHandler,
+ IssueWorkflowHandlerType,
+ IssueWorkflowStep,
+ ListIssueWorkflowsResponse,
+ IssueWorkflowWriteRequest,
+ IssueWorkflowMappingRequirement,
+ IssueWorkflowMappingPlan,
+ IssueWorkflowDryRunResponse,
+ SetProjectWorkflowRequest,
+ IssueWorkflowStatusCount,
+ WorkflowHandoffPreview,
+ WorkflowHandoffRun,
+ NewWorkflowStatus,
+ IssueWorkflowStepInput,
+ SetWorkflowHandoffRequest,
+} from "./issue-workflow";
export type {
Agent,
AgentConversationStarter,
diff --git a/packages/core/types/issue-workflow.ts b/packages/core/types/issue-workflow.ts
new file mode 100644
index 0000000000..f464e5422a
--- /dev/null
+++ b/packages/core/types/issue-workflow.ts
@@ -0,0 +1,147 @@
+/**
+ * Workspace workflows (MUL-7420).
+ *
+ * A workflow is a whole pipeline: an ordered pick from the shared status
+ * catalog plus who each column hands an issue to. Every workflow lists todo,
+ * done and cancelled; backlog and blocked are optional, and the five keep fixed
+ * places at the ends. Entering a column through a status change assigns the
+ * issue to the column's handler and, for an agent, starts its run with the
+ * column's instructions. A project only picks a workflow; projects that name
+ * none use the workspace's Default workflow.
+ */
+
+export type IssueWorkflowHandlerType =
+ | "none"
+ | "agent"
+ | "squad"
+ | "member"
+ | "project_lead"
+ | "creator";
+
+export interface IssueWorkflowHandler {
+ type: IssueWorkflowHandlerType;
+ /** Set only for agent, squad and member handlers. */
+ id?: string;
+}
+
+/** A column with its handoff; handler "none" keeps the assignee. */
+export interface IssueWorkflowStep {
+ status_key: string;
+ handler: IssueWorkflowHandler;
+ instructions: string;
+ /** Suggested status once the step is done; named in the handler's brief. */
+ next_status_key?: string;
+ /** Status to send the issue back to when it needs changes. */
+ back_status_key?: string;
+}
+
+export interface IssueWorkflow {
+ id: string;
+ workspace_id: string;
+ name: string;
+ description: string;
+ /** The workspace Default: used by every project that names no workflow. */
+ is_default: boolean;
+ steps: IssueWorkflowStep[];
+ /** Projects currently using this workflow. */
+ project_ids: string[];
+ created_at: string;
+ updated_at: string;
+}
+
+export interface ListIssueWorkflowsResponse {
+ workflows: IssueWorkflow[];
+ total: number;
+}
+
+/** A status for a new column, created with the workflow write. */
+export interface NewWorkflowStatus {
+ name: string;
+ category?: string;
+ color?: string;
+}
+
+/** A column of a workflow write: an existing status or a new one, with its handoff. */
+export type IssueWorkflowStepInput = ({ status_key: string } | { new_status: NewWorkflowStatus }) &
+ Partial<SetWorkflowHandoffRequest>;
+
+export interface IssueWorkflowWriteRequest {
+ name?: string;
+ description?: string;
+ /**
+ * Every column with its handoff. The server adds todo, done and cancelled
+ * when missing and places the fixed columns; backlog and blocked are listed
+ * only when included.
+ */
+ steps?: IssueWorkflowStepInput[];
+ /** Destination for issues on statuses an edit removes, keyed by removed status. */
+ status_mapping?: Record<string, string>;
+ dry_run?: boolean;
+}
+
+/** A status some issues are on that the target workflow does not list. */
+export interface IssueWorkflowMappingRequirement {
+ status_key: string;
+ issue_count: number;
+ suggested_status_key: string;
+}
+
+/** A status some issues are on that both workflows list, so they keep it. */
+export interface IssueWorkflowStatusCount {
+ status_key: string;
+ issue_count: number;
+}
+
+export interface IssueWorkflowMappingPlan {
+ required: IssueWorkflowMappingRequirement[];
+ unchanged: IssueWorkflowStatusCount[];
+ total_issues: number;
+ affected_issues: number;
+}
+
+export interface SetProjectWorkflowRequest {
+ /** null switches the project back to the Default workflow. */
+ workflow_id: string | null;
+ status_mapping?: Record<string, string>;
+ dry_run?: boolean;
+}
+
+export interface IssueWorkflowDryRunResponse {
+ dry_run: true;
+ plan: IssueWorkflowMappingPlan;
+}
+
+/** An active run of the agent a handoff takes the issue from. */
+export interface WorkflowHandoffRun {
+ task_id: string;
+ agent_id: string;
+ status: string;
+ started_at: string | null;
+}
+
+/**
+ * What moving an issue to a status would do under its project's workflow
+ * (MUL-7420). `handoff` is false for the Default workflow and for steps that
+ * keep the assignee.
+ */
+export interface WorkflowHandoffPreview {
+ handoff: boolean;
+ workflow_name: string;
+ from_status: string;
+ to_status: string;
+ handler_type: "agent" | "squad" | "member" | null;
+ handler_id: string | null;
+ previous_assignee_type: string | null;
+ previous_assignee_id: string | null;
+ previous_runs: WorkflowHandoffRun[];
+ /** The brief the handler's run receives; empty for a member handler. */
+ brief: string;
+}
+
+/** A workflow's handoff for one column; handler "none" clears it. */
+export interface SetWorkflowHandoffRequest {
+ handler: IssueWorkflowHandler;
+ instructions?: string;
+ next_status_key?: string;
+ back_status_key?: string;
+}
diff --git a/packages/core/types/project.ts b/packages/core/types/project.ts
index 3200b91ac0..4de4d245f6 100644
--- a/packages/core/types/project.ts
+++ b/packages/core/types/project.ts
@@ -1,3 +1,4 @@
+
export type ProjectStatus = "planned" | "in_progress" | "paused" | "completed" | "cancelled";
export type ProjectPriority = "urgent" | "high" | "medium" | "low" | "none";
@@ -21,6 +22,11 @@ export interface Project {
issue_count: number;
done_count: number;
resource_count: number;
+ /**
+ * The workflow this project uses; null for the workspace Default workflow.
+ * Optional because older servers do not send it. (MUL-7420)
+ */
+ workflow_id?: string | null;
}
export interface CreateProjectRequest {
@@ -33,6 +39,8 @@ export interface CreateProjectRequest {
lead_id?: string;
start_date?: string;
due_date?: string;
+ /** Workflow to use from the start; omitted uses the Default workflow. */
+ workflow_id?: string | null;
// Resources to attach in the same transaction as the project. Server returns
// 4xx (and rolls back) if any one is invalid or duplicate.
resources?: CreateProjectResourceRequest[];
diff --git a/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx b/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx
index 615c21c9a1..121857a1b3 100644
--- a/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx
+++ b/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx
@@ -118,6 +118,8 @@ vi.mock("sonner", () => ({
const { apiMocks, copyTextMock } = vi.hoisted(() => ({
apiMocks: {
listTasksByIssue: vi.fn(),
+ listIssueWorkflows: vi.fn(),
+ listProjects: vi.fn(),
},
copyTextMock: vi.fn(),
}));
@@ -185,6 +187,10 @@ beforeEach(() => {
toastSuccessMock.mockReset();
listTasksByIssueMock.mockReset();
listTasksByIssueMock.mockResolvedValue([]);
+ apiMocks.listIssueWorkflows.mockReset();
+ apiMocks.listIssueWorkflows.mockResolvedValue({ workflows: [] });
+ apiMocks.listProjects.mockReset();
+ apiMocks.listProjects.mockResolvedValue({ projects: [] });
});
describe("IssueActionsDropdown", () => {
@@ -433,3 +439,53 @@ describe("IssueActionsContextMenu", () => {
expect(screen.getByText("Delete issue")).toBeInTheDocument();
});
});
+
+describe("Status in a workflow project (MUL-7420)", () => {
+ const workflowIssue = { ...mockIssue, project_id: "proj-1" } as Issue;
+
+ beforeEach(() => {
+ apiMocks.listProjects.mockResolvedValue({
+ projects: [{ id: "proj-1", title: "App", workflow_id: "wf-1", lead_type: null, lead_id: null }],
+ });
+ apiMocks.listIssueWorkflows.mockResolvedValue({
+ workflows: [
+ {
+ id: "wf-1",
+ name: "Delivery",
+ description: "",
+ is_default: false,
+ project_ids: ["proj-1"],
+ steps: [
+ { status_key: "todo", handler: { type: "none" }, instructions: "" },
+ { status_key: "in_progress", handler: { type: "agent", id: "agent-1" }, instructions: "" },
+ { status_key: "done", handler: { type: "none" }, instructions: "" },
+ ],
+ },
+ ],
+ });
+ });
+
+ it("offers only the workflow's statuses and confirms a handoff before applying it", async () => {
+ render(
+ wrap(
+ <IssueActionsDropdown
+ issue={workflowIssue}
+ trigger={<button data-testid="trigger">Menu</button>}
+ />,
+ ),
+ );
+
+ fireEvent.click(screen.getByTestId("trigger"));
+ fireEvent.click(await screen.findByText("Status"));
+
+ await waitFor(() => expect(screen.queryByText("Backlog")).not.toBeInTheDocument());
+ expect(screen.queryByText("In Review")).not.toBeInTheDocument();
+ fireEvent.click(await screen.findByText("In Progress"));
+
+ expect(mockOpenModal).toHaveBeenCalledWith("issue-workflow-handoff", {
+ issueId: "issue-1",
+ identifier: "TES-1",
+ status: "in_progress",
+ });
+ });
+});
diff --git a/packages/views/issues/actions/issue-actions-menu-items.tsx b/packages/views/issues/actions/issue-actions-menu-items.tsx
index b281dacd8c..142ba3234f 100644
--- a/packages/views/issues/actions/issue-actions-menu-items.tsx
+++ b/packages/views/issues/actions/issue-actions-menu-items.tsx
@@ -30,7 +30,9 @@ import {
} from "@multica/core/issues/config";
import { useWorkspaceId } from "@multica/core/hooks";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
-import { useStatusOptions } from "../utils/status-options";
+import { stepHandsOff, workflowAllowsStatus, workflowStep } from "@multica/core/issue-workflows";
+import { useModalStore } from "@multica/core/modals";
+import { useIssueStatusOptions } from "../utils/status-options";
import { issueKeys } from "@multica/core/issues/queries";
import { StatusIcon } from "../components/status-icon";
import { PriorityIcon } from "../components/priority-icon";
@@ -108,7 +110,17 @@ export function IssueActionsMenuItems({
}: IssueActionsMenuItemsProps) {
const { t } = useT("issues");
const wsId = useWorkspaceId();
- const statusOptions = useStatusOptions(wsId);
+ // Only the statuses the issue's workflow allows; entering a step that hands
+ // the issue off confirms first, as in the status picker. (MUL-7420)
+ const { options: statusOptions, workflow } = useIssueStatusOptions(wsId, issue.project_id);
+ const openModal = useModalStore((s) => s.open);
+ const setStatus = (status: string) => {
+ if (workflow && status !== issue.status && stepHandsOff(workflowStep(workflow, status))) {
+ openModal("issue-workflow-handoff", { issueId: issue.id, identifier: issue.identifier, status });
+ return;
+ }
+ updateField({ status });
+ };
const { categoryOf, colorOf, iconOf } = useIssueStatuses(wsId);
const {
isPinned,
@@ -186,14 +198,13 @@ export function IssueActionsMenuItems({
{t(($) => $.actions.status)}
</P.SubTrigger>
<P.SubContent>
- {/* Catalog-driven, like the picker and the filter: every entry point
- that can change a status must offer the same set, or a custom
- status is unreachable from the board's right-click menu. One flat
- list in canonical category order. (MUL-6243) */}
+ {/* The same set as the status picker: every entry point that can
+ change a status must offer it, or a custom status is unreachable
+ from the board's right-click menu. (MUL-6243) */}
{statusOptions.map((option) => (
<P.Item
key={option.key}
- onClick={() => updateField({ status: option.key })}
+ onClick={() => setStatus(option.key)}
>
<StatusIcon
status={option.key}
@@ -356,10 +367,13 @@ export function IssueActionsMenuItems({
<ArrowDown className="h-3.5 w-3.5" />
{t(($) => $.actions.add_sub_issue)}
</P.Item>
- <P.Item onClick={openMarkDuplicate}>
- <CircleEqual className="h-3.5 w-3.5" />
- {t(($) => $.actions.mark_duplicate)}
- </P.Item>
+ {/* Marking a duplicate cancels the issue. (MUL-7420) */}
+ {workflowAllowsStatus(workflow, "cancelled") && (
+ <P.Item onClick={openMarkDuplicate}>
+ <CircleEqual className="h-3.5 w-3.5" />
+ {t(($) => $.actions.mark_duplicate)}
+ </P.Item>
+ )}
</P.SubContent>
</P.Sub>
diff --git a/packages/views/issues/components/batch-action-toolbar.confirm.test.tsx b/packages/views/issues/components/batch-action-toolbar.confirm.test.tsx
index f8deac1746..6401ba6835 100644
--- a/packages/views/issues/components/batch-action-toolbar.confirm.test.tsx
+++ b/packages/views/issues/components/batch-action-toolbar.confirm.test.tsx
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
-import { render, screen, fireEvent } from "@testing-library/react";
+import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import type { Issue, UpdateIssueRequest } from "@multica/core/types";
import { BatchActionToolbar } from "./batch-action-toolbar";
@@ -18,20 +18,31 @@ vi.mock("@multica/core/issues/stores/selection-store", () => ({
useIssueSelectionStore: (selector: (s: typeof selection) => unknown) => selector(selection),
}));
-const batchUpdate = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+const batchUpdate = vi.hoisted(() => vi.fn().mockResolvedValue({ updated: 1 }));
const batchDelete = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
vi.mock("@multica/core/issues/mutations", () => ({
useBatchUpdateIssues: () => ({ mutateAsync: batchUpdate, isPending: false }),
useBatchDeleteIssues: () => ({ mutateAsync: batchDelete, isPending: false }),
}));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+vi.mock("@multica/core/issue-workflows", () => ({
+ useIssueWorkflows: () => ({ workflows: [] }),
+ sharedWorkflowStatusKeys: () => null,
+}));
+vi.mock("@tanstack/react-query", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),
+ useQuery: () => ({ data: [] }),
+}));
+
const openModal = vi.hoisted(() => vi.fn());
vi.mock("@multica/core/modals", () => ({
useModalStore: (selector: (s: { open: typeof openModal }) => unknown) => selector({ open: openModal }),
}));
vi.mock("../../i18n", () => ({ useT: () => ({ t: () => "label" }) }));
-vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+const toast = vi.hoisted(() => ({ success: vi.fn(), warning: vi.fn(), error: vi.fn() }));
+vi.mock("sonner", () => ({ toast }));
// Interactive picker stubs: each renders buttons that fire the real onUpdate the
// toolbar passes in, so we exercise handleBatchStatus / handleBatchAssignee.
@@ -97,6 +108,8 @@ beforeEach(() => {
batchUpdate.mockClear();
batchDelete.mockClear();
openModal.mockClear();
+ toast.success.mockClear();
+ toast.warning.mockClear();
});
describe("BatchActionToolbar status routing (MUL-4155)", () => {
@@ -114,6 +127,15 @@ describe("BatchActionToolbar status routing (MUL-4155)", () => {
}
});
+ it("warns instead of reporting success when the server skips some issues", async () => {
+ selection.selectedIds = new Set(["a", "b"]);
+ batchUpdate.mockResolvedValueOnce({ updated: 1 });
+ render(<BatchActionToolbar issues={[makeIssue({ id: "a" }), makeIssue({ id: "b" })]} />);
+ fireEvent.click(screen.getByTestId("status-done"));
+ await waitFor(() => expect(toast.warning).toHaveBeenCalled());
+ expect(toast.success).not.toHaveBeenCalled();
+ });
+
it("still routes agent assignment through the run-confirm modal", () => {
render(<BatchActionToolbar issues={[makeIssue({ status: "todo" })]} />);
fireEvent.click(screen.getByTestId("assign-agent"));
diff --git a/packages/views/issues/components/batch-action-toolbar.test.tsx b/packages/views/issues/components/batch-action-toolbar.test.tsx
index 703da00950..5dc079b49d 100644
--- a/packages/views/issues/components/batch-action-toolbar.test.tsx
+++ b/packages/views/issues/components/batch-action-toolbar.test.tsx
@@ -21,6 +21,42 @@ vi.mock("@multica/core/issues/mutations", () => ({
useBatchDeleteIssues: () => ({ mutateAsync: vi.fn(), isPending: false }),
}));
+const { WORKFLOWS, PROJECTS } = vi.hoisted(() => {
+ const workflow = (id: string, isDefault: boolean, keys: string[]) => ({
+ id,
+ workspace_id: "ws-1",
+ name: id,
+ description: "",
+ is_default: isDefault,
+ steps: keys.map((status_key) => ({ status_key, handler: { type: "none" }, instructions: "" })),
+ project_ids: [],
+ created_at: "",
+ updated_at: "",
+ });
+ return {
+ WORKFLOWS: [
+ workflow("default", true, ["todo", "in_progress", "done"]),
+ workflow("dev", false, ["todo", "in_progress", "code_review", "done"]),
+ workflow("design", false, ["todo", "mockup", "done"]),
+ ],
+ PROJECTS: [
+ { id: "p-dev", workflow_id: "dev" },
+ { id: "p-design", workflow_id: "design" },
+ { id: "p-default", workflow_id: null },
+ ],
+ };
+});
+
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+vi.mock("@multica/core/issue-workflows", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/issue-workflows")>()),
+ useIssueWorkflows: () => ({ workflows: WORKFLOWS }),
+}));
+vi.mock("@tanstack/react-query", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),
+ useQuery: () => ({ data: PROJECTS }),
+}));
+
vi.mock("../../i18n", () => ({
useT: () => ({ t: () => "label" }),
}));
@@ -28,8 +64,12 @@ vi.mock("../../i18n", () => ({
// Render each picker as a probe that surfaces the value the toolbar passed in,
// so the test asserts the wiring (real `commonIssueFields` runs underneath).
vi.mock("./pickers", () => ({
- StatusPicker: ({ status }: { status: string | null }) => (
- <div data-testid="status-picker" data-status={status ?? "__none__"} />
+ StatusPicker: ({ status, allowedStatuses }: { status: string | null; allowedStatuses?: ReadonlySet<string> | null }) => (
+ <div
+ data-testid="status-picker"
+ data-status={status ?? "__none__"}
+ data-allowed={allowedStatuses ? [...allowedStatuses].sort().join(",") : "__all__"}
+ />
),
PriorityPicker: ({ priority }: { priority: string | null }) => (
<div data-testid="priority-picker" data-priority={priority ?? "__none__"} />
@@ -131,6 +171,28 @@ describe("BatchActionToolbar picker wiring", () => {
expect(assignee).toHaveAttribute("data-assignee-id", "__null__");
});
+ it("offers only the statuses every selected project's workflow allows", () => {
+ const issues = [
+ makeIssue({ id: "a", project_id: "p-dev" }),
+ makeIssue({ id: "b", project_id: "p-design" }),
+ makeIssue({ id: "c", project_id: "p-default" }),
+ ];
+ selection.selectedIds = new Set(["a", "b", "c"]);
+
+ render(<BatchActionToolbar issues={issues} />);
+
+ expect(screen.getByTestId("status-picker")).toHaveAttribute("data-allowed", "done,todo");
+ });
+
+ it("offers every status when no selected issue has a named workflow", () => {
+ const issues = [makeIssue({ id: "a", project_id: "p-default" }), makeIssue({ id: "b" })];
+ selection.selectedIds = new Set(["a", "b"]);
+
+ render(<BatchActionToolbar issues={issues} />);
+
+ expect(screen.getByTestId("status-picker")).toHaveAttribute("data-allowed", "__all__");
+ });
+
it("renders nothing when nothing is selected", () => {
render(<BatchActionToolbar issues={[makeIssue({ id: "a" })]} />);
expect(screen.queryByTestId("status-picker")).toBeNull();
diff --git a/packages/views/issues/components/batch-action-toolbar.tsx b/packages/views/issues/components/batch-action-toolbar.tsx
index 11a67f83b2..1423a7acf3 100644
--- a/packages/views/issues/components/batch-action-toolbar.tsx
+++ b/packages/views/issues/components/batch-action-toolbar.tsx
@@ -15,8 +15,12 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "@multica/ui/components/ui/alert-dialog";
+import { useQuery } from "@tanstack/react-query";
import type { Issue, UpdateIssueRequest } from "@multica/core/types";
+import { useWorkspaceId } from "@multica/core/hooks";
import { commonIssueFields } from "@multica/core/issues/batch";
+import { sharedWorkflowStatusKeys, useIssueWorkflows } from "@multica/core/issue-workflows";
+import { projectListOptions } from "@multica/core/projects/queries";
import { useBatchUpdateIssues, useBatchDeleteIssues } from "@multica/core/issues/mutations";
import { useModalStore } from "@multica/core/modals";
import { StatusPicker, PriorityPicker, AssigneePicker } from "./pickers";
@@ -73,6 +77,21 @@ export function BatchActionToolbar({
[selectedIssues],
);
+ // A selection inside one project offers that project's workflow statuses;
+ // one spanning projects offers the statuses every selected issue's
+ // workflow allows. (MUL-7420)
+ const sharedProjectId = useMemo(() => {
+ const first = selectedIssues[0]?.project_id ?? null;
+ return first && selectedIssues.every((i) => i.project_id === first) ? first : null;
+ }, [selectedIssues]);
+ const wsId = useWorkspaceId();
+ const { workflows } = useIssueWorkflows(wsId);
+ const { data: projects } = useQuery({ ...projectListOptions(wsId), enabled: count > 0 && !sharedProjectId });
+ const allowedStatuses = useMemo(
+ () => (sharedProjectId ? null : sharedWorkflowStatusKeys(workflows, projects, selectedIssues)),
+ [sharedProjectId, workflows, projects, selectedIssues],
+ );
+
const [statusOpen, setStatusOpen] = useState(false);
const [priorityOpen, setPriorityOpen] = useState(false);
const [assigneeOpen, setAssigneeOpen] = useState(false);
@@ -95,12 +114,14 @@ export function BatchActionToolbar({
const handleBatchUpdate = async (updates: Partial<UpdateIssueRequest>) => {
try {
- if (surfaceActions) {
- await surfaceActions.batchUpdate(ids, updates);
+ const { updated } = surfaceActions
+ ? await surfaceActions.batchUpdate(ids, updates)
+ : await batchUpdate.mutateAsync({ ids, updates });
+ if (updated < count) {
+ toast.warning(t(($) => $.batch.update_partial, { updated, count }));
} else {
- await batchUpdate.mutateAsync({ ids, updates });
+ toast.success(t(($) => $.batch.update_success, { count }));
}
- toast.success(t(($) => $.batch.update_success, { count }));
} catch (err) {
toast.error(
err instanceof Error && err.message
@@ -222,6 +243,8 @@ export function BatchActionToolbar({
{/* Status */}
<StatusPicker
status={common.status}
+ projectId={sharedProjectId}
+ allowedStatuses={allowedStatuses}
onUpdate={handleBatchStatus}
open={statusOpen}
onOpenChange={setStatusOpen}
diff --git a/packages/views/issues/components/board-card-assignee-picker.test.tsx b/packages/views/issues/components/board-card-assignee-picker.test.tsx
index 39c9ddbaff..3c0670c05e 100644
--- a/packages/views/issues/components/board-card-assignee-picker.test.tsx
+++ b/packages/views/issues/components/board-card-assignee-picker.test.tsx
@@ -110,7 +110,7 @@ const actions: IssueSurfaceActions = {
createIssue: vi.fn(),
updateIssue: vi.fn(),
moveIssue: vi.fn(),
- batchUpdate: vi.fn().mockResolvedValue(undefined),
+ batchUpdate: vi.fn().mockResolvedValue({ updated: 1 }),
batchDelete: vi.fn().mockResolvedValue(undefined),
};
diff --git a/packages/views/issues/components/board-column.tsx b/packages/views/issues/components/board-column.tsx
index e1115f7e9d..526549c83f 100644
--- a/packages/views/issues/components/board-column.tsx
+++ b/packages/views/issues/components/board-column.tsx
@@ -2,7 +2,7 @@
import { memo, useCallback, useMemo, useState, type ReactNode } from "react";
import { Virtuoso } from "react-virtuoso";
-import { EyeOff, FolderMinus, MoreHorizontal, Plus, UserMinus } from "lucide-react";
+import { Ban, EyeOff, FolderMinus, MoreHorizontal, Plus, UserMinus } from "lucide-react";
import { useDroppable } from "@dnd-kit/core";
import { SortableContext, verticalListSortingStrategy } from "@dnd-kit/sortable";
import type {
@@ -20,7 +20,6 @@ import {
} from "@multica/ui/components/ui/dropdown-menu";
import { useWorkspaceId } from "@multica/core/hooks";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
-import { STATUS_CONFIG } from "@multica/core/issues/config";
import { useViewStoreApi } from "@multica/core/issues/stores/view-store-context";
import { useViewBaseline } from "../surface/view-baseline-context";
import { StatusHeading } from "./status-heading";
@@ -33,6 +32,8 @@ import { useRestoredScrollOffset, useRestoredScrollRef } from "../../platform";
import { DeferredPopup } from "../../common/deferred-popup";
import { DeferredTooltip } from "../../common/deferred-tooltip";
import { VirtuosoSeed } from "../../common/virtuoso-seed";
+import { useBoardWorkflow } from "./board-workflow-context";
+import { ColumnHandoff } from "../../workflows/column-handoff";
import type { IssueCreateDefaults } from "../surface/types";
// Insertion-position prediction intentionally omitted. The server's
@@ -122,11 +123,15 @@ export const BoardColumn = memo(function BoardColumn({
}) {
const status = group.status;
const wsId = useWorkspaceId();
- const { categoryOf, entryOf } = useIssueStatuses(wsId);
+ const { entryOf } = useIssueStatuses(wsId);
const archived = !!status && !!entryOf(status)?.archived_at;
- const cfg = status ? STATUS_CONFIG[categoryOf(status)] : null;
const { setNodeRef, isOver: droppableIsOver } = useDroppable({ id: group.id });
- const isOver = droppableIsOver && !archived;
+ // A dragged card whose project workflow does not list this status cannot
+ // land here; the column dims and says why. (MUL-7420)
+ const { dropBlockedReason, dropHint } = useBoardWorkflow();
+ const blockedReason = status ? dropBlockedReason(status) : null;
+ const isOver = droppableIsOver && !archived && !blockedReason;
+ const hint = isOver && status ? dropHint(status) : null;
const viewStoreApi = useViewStoreApi();
// A status fixed by the open saved view cannot be hidden from the board —
// that would silently strip one of the view's own conditions.
@@ -192,12 +197,31 @@ export const BoardColumn = memo(function BoardColumn({
);
return (
- <div style={{ width: BOARD_COL_WIDTH }} className={`flex shrink-0 flex-col rounded-xl ${cfg?.columnBg ?? "bg-muted/40"} p-2`}>
- <div className="mb-2 flex items-center justify-between px-1.5">
+ <div
+ style={{ width: BOARD_COL_WIDTH }}
+ className={`group/column relative flex shrink-0 flex-col rounded-xl bg-muted/40 p-2 ${
+ hint ? "ring-2 ring-brand/30" : ""
+ }`}
+ >
+ {/* A dragged card whose workflow lacks this status cannot land here: the
+ column is hatched over and says why. (MUL-7420) */}
+ {blockedReason && (
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-0 z-20 flex items-center justify-center rounded-xl bg-background/60 bg-[repeating-linear-gradient(135deg,transparent_0_8px,var(--color-border)_8px_9px)]"
+ >
+ <span className="flex items-center gap-1.5 rounded-md border border-surface-border bg-card px-2.5 py-1 text-caption text-muted-foreground shadow-sm">
+ <Ban className="size-3" />
+ {blockedReason}
+ </span>
+ </div>
+ )}
+ <div className="mb-2 flex items-center justify-between gap-2 px-1.5">
<BoardGroupHeading group={group} count={totalCount ?? issueIds.length} />
- {/* Right: add + menu */}
- <div className="flex items-center gap-1">
+ {/* Right: step handler + add + menu */}
+ <div className="flex min-w-0 items-center gap-1">
+ {status && <WorkflowStepHandlerBadge status={status} />}
{/* Column-header popups mount lazily: a board/swimlane renders one
header per column and almost none of these menus/tooltips are
ever opened — eagerly mounting them dominated surface mount
@@ -258,6 +282,16 @@ export const BoardColumn = memo(function BoardColumn({
</div>
</div>
<div className="relative min-h-[200px] flex-1 rounded-lg">
+ {hint && (
+ <div className="pointer-events-none absolute inset-x-1 bottom-1 z-10 flex items-center justify-center gap-1.5 rounded-lg border border-dashed border-brand/50 bg-card px-3 py-3 text-caption text-muted-foreground shadow-sm">
+ {hint.actor && <ActorAvatar actorType={hint.actor.type} actorId={hint.actor.id} size="xs" profileLink={false} />}
+ <span className="truncate">
+ {hint.run
+ ? t(($) => $.workflows.board.drop_hint_run, { name: hint.name })
+ : t(($) => $.workflows.board.drop_hint, { name: hint.name })}
+ </span>
+ </div>
+ )}
{isOver && sortLabel && (
<div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-lg bg-background/40">
<span className="rounded-md bg-popover px-2.5 py-1 text-caption font-medium text-popover-foreground shadow-sm border border-border">
@@ -341,6 +375,13 @@ export const BoardColumn = memo(function BoardColumn({
);
});
+/** On a project board, the column's handoff for that project. (MUL-7420) */
+function WorkflowStepHandlerBadge({ status }: { status: string }) {
+ const { scopeWorkflow, scopeProject } = useBoardWorkflow();
+ if (!scopeWorkflow || !scopeProject) return null;
+ return <ColumnHandoff status={status} workflow={scopeWorkflow} project={scopeProject} />;
+}
+
function BoardGroupHeading({
group,
count,
diff --git a/packages/views/issues/components/board-view.tsx b/packages/views/issues/components/board-view.tsx
index 7b9c6801a4..955d7ebed4 100644
--- a/packages/views/issues/components/board-view.tsx
+++ b/packages/views/issues/components/board-view.tsx
@@ -31,6 +31,17 @@ import { useWorkspaceId } from "@multica/core/hooks";
import type { IssueGrouping } from "@multica/core/issues/stores/view-store";
import { useActorName } from "@multica/core/workspace/hooks";
import { BoardColumn, BOARD_CARD_WIDTH, type BoardColumnGroup } from "./board-column";
+import { BoardWorkflowContext, type BoardWorkflowContextValue } from "./board-workflow-context";
+import {
+ resolveProjectWorkflow,
+ stepHandsOff,
+ useIssueWorkflows,
+ workflowAllowsStatus,
+ workflowStep,
+} from "@multica/core/issue-workflows";
+import { WorkflowHandoffConfirmDialog } from "../../workflows/handoff-confirm-dialog";
+import { stepHandlerActor, useStepHandlerLabel } from "../../workflows/step-handler";
+import { projectListOptions } from "@multica/core/projects/queries";
import { BoardCardContent } from "./board-card";
import { HiddenColumnsPanel, HiddenColumnRow } from "./hidden-columns-panel";
import { InfiniteScrollSentinel } from "./infinite-scroll-sentinel";
@@ -64,6 +75,7 @@ import {
propertyGroupId,
projectGroupId,
} from "../utils/drag-utils";
+import { useStatusLabel } from "../utils/status-label";
function isStatusGroup(
group: BoardColumnGroup,
@@ -275,6 +287,7 @@ function BoardViewImpl({
const sortBy = useViewStore((s) => s.sortBy);
const boardWsId = useWorkspaceId();
const catalog = useIssueStatuses(boardWsId);
+ const labelOf = useStatusLabel(boardWsId);
const { data: workspaceProperties = [] } = useQuery(propertyListOptions(boardWsId));
const groupingPropertyId = propertyIdFromViewKey(storeGrouping);
const groupingProperty = groupingPropertyId
@@ -472,6 +485,52 @@ function BoardViewImpl({
// --- Drag state ---
const [activeIssue, setActiveIssue] = useState<Issue | null>(null);
+ const [pendingHandoff, setPendingHandoff] = useState<{
+ issue: Issue;
+ status: IssueStatus;
+ updates: ReturnType<typeof getMoveUpdates>;
+ anchors: ReturnType<typeof getMoveAnchors>;
+ } | null>(null);
+
+ // Project workflows (MUL-7420): a card can only move to a status its
+ // project's workflow lists, and a project board names each step's handler.
+ const { workflows } = useIssueWorkflows(boardWsId);
+ const { data: workspaceProjects } = useQuery(projectListOptions(boardWsId));
+ const workflowOfIssue = useCallback(
+ (issue: Issue | null | undefined) => {
+ if (!issue?.project_id) return null;
+ return resolveProjectWorkflow(
+ workflows,
+ workspaceProjects?.find((p) => p.id === issue.project_id),
+ );
+ },
+ [workflows, workspaceProjects],
+ );
+ const scopeProject = projectId ? workspaceProjects?.find((p) => p.id === projectId) ?? null : null;
+ const activeWorkflow = workflowOfIssue(activeIssue);
+ const activeProject = activeIssue?.project_id
+ ? workspaceProjects?.find((p) => p.id === activeIssue.project_id) ?? null
+ : null;
+ const activeHandlerLabel = useStepHandlerLabel(activeProject);
+ const boardWorkflow = useMemo<BoardWorkflowContextValue>(
+ () => ({
+ scopeWorkflow: resolveProjectWorkflow(workflows, scopeProject),
+ scopeProject,
+ dropBlockedReason: (status) =>
+ activeWorkflow && activeIssue?.status !== status && !workflowAllowsStatus(activeWorkflow, status)
+ ? t(($) => $.workflows.not_in_workflow, { name: activeWorkflow.name })
+ : null,
+ dropHint: (status) => {
+ if (!activeWorkflow || activeIssue?.status === status) return null;
+ const step = workflowStep(activeWorkflow, status);
+ const name = activeHandlerLabel(step);
+ if (!step || !name) return null;
+ const actor = stepHandlerActor(step, activeProject);
+ return { name, actor, run: actor ? actor.type !== "member" : step.handler.type === "creator" };
+ },
+ }),
+ [activeHandlerLabel, activeIssue?.status, activeProject, activeWorkflow, scopeProject, t, workflows],
+ );
// Shared drag/settle primitive: owns the local column mirror, the
// dragging/settling locks, the post-move animation-frame throttle, and the
// settle callback. Shared with list-view (and swimlane) so the surfaces
@@ -548,6 +607,9 @@ function BoardViewImpl({
if (!activeCol || !overCol || activeCol === overCol) return prev;
const targetStatus = groups.find((group) => group.id === overCol)?.status;
if (targetStatus && catalog.entryOf(targetStatus)?.archived_at) return prev;
+ if (targetStatus && !workflowAllowsStatus(workflowOfIssue(issueMapRef.current.get(activeId)), targetStatus)) {
+ return prev;
+ }
if (sortBy !== "position") return prev;
@@ -560,7 +622,7 @@ function BoardViewImpl({
return { ...prev, [activeCol]: oldIds, [overCol]: newIds };
});
},
- [groupIds, groups, catalog, sortBy, recentlyMovedRef, setColumns],
+ [groupIds, groups, catalog, sortBy, recentlyMovedRef, setColumns, workflowOfIssue],
);
const handleDragEnd = useCallback(
@@ -619,6 +681,33 @@ function BoardViewImpl({
resetColumns();
return;
}
+ const movingWorkflow = workflowOfIssue(map.get(activeId));
+ if (
+ finalGroup.status &&
+ movingWorkflow &&
+ map.get(activeId)?.status !== finalGroup.status &&
+ !workflowAllowsStatus(movingWorkflow, finalGroup.status)
+ ) {
+ resetColumns();
+ toast.info(
+ t(($) => $.workflows.drop_blocked, {
+ status: labelOf(finalGroup.status),
+ name: movingWorkflow.name,
+ }),
+ );
+ return;
+ }
+
+ // Entering a step that hands the issue off is confirmed first: who it
+ // goes to, the previous agent's run, and the brief. The card returns to
+ // its column until then. (MUL-7420)
+ const handoffTarget =
+ finalGroup.status &&
+ movingWorkflow &&
+ map.get(activeId)?.status !== finalGroup.status &&
+ stepHandsOff(workflowStep(movingWorkflow, finalGroup.status))
+ ? finalGroup.status
+ : null;
if (sortBy !== "position") {
// Cross-column: only update group (status/assignee), keep original position.
@@ -632,6 +721,19 @@ function BoardViewImpl({
}
return;
}
+ if (handoffTarget) {
+ resetColumns();
+ setPendingHandoff({
+ issue: currentIssue,
+ status: handoffTarget,
+ updates: getMoveUpdates(finalGroup, currentIssue.position, currentIssue),
+ anchors: getMoveAnchors(
+ insertIdByPosition((cols[overCol] ?? []).filter((id) => id !== activeId), activeId, currentIssue.position, map),
+ activeId,
+ ),
+ });
+ return;
+ }
// Optimistically move the card into the target column *now*. Without
// this, the sortBy != "position" path never touches local columns on
// drop, so onDragOver having been a no-op leaves the card in its origin
@@ -673,6 +775,17 @@ function BoardViewImpl({
return;
}
+ if (handoffTarget && currentIssue) {
+ resetColumns();
+ setPendingHandoff({
+ issue: currentIssue,
+ status: handoffTarget,
+ updates: getMoveUpdates(finalGroup, newPosition, currentIssue),
+ anchors: getMoveAnchors(finalIds, activeId),
+ });
+ return;
+ }
+
// beginSettle() holds the lock and returns the onSettled callback that
// releases it and resyncs local columns from the cache: a no-op on
// success (onSuccess already patched the moved card in place), the revert
@@ -688,7 +801,7 @@ function BoardViewImpl({
);
applyPropertyGroupValue(finalGroup, activeId);
},
- [groupedIssues, groups, grouping, groupingOptionIds, onMoveIssue, groupIds, groupMap, sortBy, beginSettle, columnsRef, isDraggingRef, setColumns, applyPropertyGroupValue, catalog, t],
+ [groupedIssues, groups, grouping, groupingOptionIds, onMoveIssue, groupIds, groupMap, sortBy, beginSettle, columnsRef, isDraggingRef, setColumns, applyPropertyGroupValue, catalog, labelOf, t, workflowOfIssue],
);
// An aborted drag (pointercancel, window resize, tab hide, Escape) fires
@@ -702,6 +815,7 @@ function BoardViewImpl({
}, [groupedIssues, groups, grouping, groupingOptionIds, setColumns, isDraggingRef]);
return (
+ <BoardWorkflowContext.Provider value={boardWorkflow}>
<DndContext
sensors={sensors}
collisionDetection={collisionDetection}
@@ -819,6 +933,26 @@ function BoardViewImpl({
) : null}
</DragOverlay>
</DndContext>
+ <WorkflowHandoffConfirmDialog
+ issue={pendingHandoff?.issue ?? null}
+ toStatus={pendingHandoff?.status ?? ""}
+ onCancel={() => setPendingHandoff(null)}
+ onConfirm={({ stopPreviousRuns }) => {
+ const pending = pendingHandoff;
+ setPendingHandoff(null);
+ if (!pending) return;
+ onMoveIssue(
+ pending.issue.id,
+ {
+ ...pending.updates,
+ ...pending.anchors,
+ ...(stopPreviousRuns ? { stop_previous_assignee_runs: true } : {}),
+ },
+ beginSettle(),
+ );
+ }}
+ />
+ </BoardWorkflowContext.Provider>
);
}
diff --git a/packages/views/issues/components/board-workflow-context.tsx b/packages/views/issues/components/board-workflow-context.tsx
new file mode 100644
index 0000000000..09336e50e1
--- /dev/null
+++ b/packages/views/issues/components/board-workflow-context.tsx
@@ -0,0 +1,44 @@
+"use client";
+
+import { createContext, useContext } from "react";
+import type { IssueStatus, IssueWorkflow, Project } from "@multica/core/types";
+
+/**
+ * Workflow facts a board column needs (MUL-7420), provided once by BoardView
+ * so every column variant can read them without threading props.
+ */
+export interface BoardWorkflowContextValue {
+ /** Workflow of the project this board is scoped to; heads name each step's handler. */
+ scopeWorkflow: IssueWorkflow | null;
+ scopeProject: Project | null;
+ /**
+ * While a card is dragged, why it cannot be dropped on a status column —
+ * its project's workflow does not list the status — or null when it can.
+ */
+ dropBlockedReason: (status: IssueStatus) => string | null;
+ /**
+ * While a card is dragged, who dropping it on a status column hands it to
+ * (and whether their run starts), or null when the column keeps the
+ * assignee.
+ */
+ dropHint: (status: IssueStatus) => BoardDropHint | null;
+}
+
+export interface BoardDropHint {
+ name: string;
+ actor: { type: "agent" | "squad" | "member"; id: string } | null;
+ run: boolean;
+}
+
+const NO_WORKFLOW: BoardWorkflowContextValue = {
+ scopeWorkflow: null,
+ scopeProject: null,
+ dropBlockedReason: () => null,
+ dropHint: () => null,
+};
+
+export const BoardWorkflowContext = createContext<BoardWorkflowContextValue>(NO_WORKFLOW);
+
+export function useBoardWorkflow(): BoardWorkflowContextValue {
+ return useContext(BoardWorkflowContext);
+}
diff --git a/packages/views/issues/components/hidden-columns-panel.tsx b/packages/views/issues/components/hidden-columns-panel.tsx
index 49f274a9f2..4e1bf0c44d 100644
--- a/packages/views/issues/components/hidden-columns-panel.tsx
+++ b/packages/views/issues/components/hidden-columns-panel.tsx
@@ -1,6 +1,6 @@
"use client";
-import { Eye, MoreHorizontal } from "lucide-react";
+import { Eye, Filter, MoreHorizontal } from "lucide-react";
import type { IssueStatus } from "@multica/core/types";
import { Button } from "@multica/ui/components/ui/button";
import {
@@ -9,12 +9,15 @@ import {
DropdownMenuContent,
DropdownMenuItem,
} from "@multica/ui/components/ui/dropdown-menu";
-import { useViewStoreApi } from "@multica/core/issues/stores/view-store-context";
+import { useViewStore, useViewStoreApi } from "@multica/core/issues/stores/view-store-context";
import { StatusIcon } from "./status-icon";
import { useT } from "../../i18n";
import { useWorkspaceId } from "@multica/core/hooks";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import { useStatusLabel } from "../utils/status-label";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { AppLink } from "../../navigation";
+import { useWorkflowPermissions } from "../../workflows/permissions";
/**
* Single source of truth for the "Hidden columns" side panel rendered by
@@ -34,6 +37,8 @@ export function HiddenColumnsPanel({
renderRow: (status: IssueStatus) => React.ReactNode;
}) {
const { t } = useT("issues");
+ const viewerHidden = useViewStore((s) => s.hiddenStatuses);
+ const outsideWorkflow = hiddenStatuses.some((status) => !viewerHidden.includes(status));
return (
<div className="flex w-[240px] shrink-0 flex-col">
<div className="mb-2 flex items-center gap-2 px-1">
@@ -44,10 +49,31 @@ export function HiddenColumnsPanel({
<div className="flex-1 space-y-0.5">
{hiddenStatuses.map((status) => renderRow(status))}
</div>
+ {outsideWorkflow && <WorkflowColumnsNote />}
</div>
);
}
+/** Where a board's columns come from, under the rows its workflow leaves out. */
+function WorkflowColumnsNote() {
+ const { t } = useT("issues");
+ const paths = useWorkspacePaths();
+ const { isAdmin } = useWorkflowPermissions();
+ return (
+ <p className="mt-3 px-2.5 text-caption leading-5 text-muted-foreground">
+ {t(($) => $.board.workflow_columns_note)}
+ {isAdmin && (
+ <>
+ {" "}
+ <AppLink href={`${paths.settings()}?tab=workflows`} className="text-brand hover:underline">
+ {t(($) => $.workflows.project.manage)}
+ </AppLink>
+ </>
+ )}
+ </p>
+ );
+}
+
/**
* One row inside {@link HiddenColumnsPanel}. Pure presentational — the caller
* computes `total` however it likes (cached query vs. in-memory aggregate).
@@ -64,11 +90,19 @@ export function HiddenColumnRow({
const labelOf = useStatusLabel(wsId);
const { categoryOf, colorOf, iconOf } = useIssueStatuses(wsId);
const viewStoreApi = useViewStoreApi();
+ // Not hidden by the viewer: the column is outside the workflow this view
+ // follows (MUL-7420), so filtering by the status is how to see it.
+ const outsideWorkflow = !useViewStore((s) => s.hiddenStatuses.includes(status));
return (
<div className="flex items-center justify-between rounded-lg px-2.5 py-2 hover:bg-muted/50">
- <div className="flex items-center gap-2">
- <StatusIcon category={categoryOf(status)} color={colorOf(status)} icon={iconOf(status)} status={status} className="h-3.5 w-3.5" />
- <span className="text-body">{labelOf(status)}</span>
+ <div className="flex min-w-0 items-center gap-2">
+ <StatusIcon category={categoryOf(status)} color={colorOf(status)} icon={iconOf(status)} status={status} className="h-3.5 w-3.5 shrink-0" />
+ <span className="min-w-0">
+ <span className="block truncate text-body">{labelOf(status)}</span>
+ {outsideWorkflow && (
+ <span className="block truncate text-caption text-muted-foreground">{t(($) => $.board.outside_workflow)}</span>
+ )}
+ </span>
</div>
<div className="flex items-center gap-1.5">
{total !== undefined && (
@@ -89,12 +123,19 @@ export function HiddenColumnRow({
}
/>
<DropdownMenuContent align="end">
- <DropdownMenuItem
- onClick={() => viewStoreApi.getState().showStatus(status)}
- >
- <Eye className="size-3.5" />
- {t(($) => $.board.show_column)}
- </DropdownMenuItem>
+ {outsideWorkflow ? (
+ <DropdownMenuItem onClick={() => viewStoreApi.getState().toggleStatusFilter(status)}>
+ <Filter className="size-3.5" />
+ {t(($) => $.board.filter_to_status)}
+ </DropdownMenuItem>
+ ) : (
+ <DropdownMenuItem
+ onClick={() => viewStoreApi.getState().showStatus(status)}
+ >
+ <Eye className="size-3.5" />
+ {t(($) => $.board.show_column)}
+ </DropdownMenuItem>
+ )}
</DropdownMenuContent>
</DropdownMenu>
</div>
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 6ebdb1dace..9df9ba74ae 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -5,6 +5,7 @@ import {
issueBehavesAsAny,
issueStatusCategory,
} from "@multica/core/issues";
+import { IssueFlowCard } from "../../workflows/issue-flow-card";
import { useStatusLabel } from "../utils/status-label";
import { priorityLabel } from "../utils/priority-label";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
@@ -67,6 +68,7 @@ import { Command, CommandInput, CommandList, CommandEmpty, CommandGroup, Command
import { AvatarGroup, AvatarGroupCount } from "@multica/ui/components/ui/avatar";
import { ActorAvatar } from "../../common/actor-avatar";
import { PropRow } from "../../common/prop-row";
+import { TimelineHandoff } from "../../workflows/timeline-handoff";
import { PropertyIcon } from "../../common/property-icon";
import type { Attachment, Issue, IssueProperty, IssueStatus, IssueStatusCategory, IssuePriority, TimelineEntry, UpdateIssueRequest } from "@multica/core/types";
import { contentReferencesAttachment } from "@multica/core/types";
@@ -91,7 +93,7 @@ import { IssueActionsDropdown, useIssueActions, IssueActionsContextMenu, IssueCo
import { LabelChip } from "../../labels/label-chip";
import { IssueAgentActivityIndicator } from "./issue-agent-activity-indicator";
import { SubIssuesAgentWorkingChip } from "./sub-issues-agent-working-chip";
-import { ProjectPicker } from "../../projects/components/project-picker";
+import { IssueProjectPicker } from "../../projects/components/issue-project-picker";
import { IssuePropertyPills } from "./issue-property-pills";
import { LocalDirectoryHint } from "../../projects/components/local-directory-hint";
import { useNewRunIds } from "./use-run-comment-motion";
@@ -128,6 +130,9 @@ import { useAuthStore } from "@multica/core/auth";
import { useWorkspacePaths } from "@multica/core/paths";
import { useActorName } from "@multica/core/workspace/hooks";
import { useWorkspaceId } from "@multica/core/hooks";
+import {
+ useProjectWorkflow,
+} from "@multica/core/issue-workflows";
import { useRecentContextStore } from "@multica/core/chat";
import { useModalStore } from "@multica/core/modals";
import { issueListOptions, issueDetailOptions, childIssuesOptions, childIssueProgressOptions, issueAttachmentsOptions } from "@multica/core/issues/queries";
@@ -763,53 +768,47 @@ function ActivityBlock({
);
}
+ const handoff = isStatusChange && !!details.handoff_to_id;
return (
- <div key={entry.id} className="flex items-center text-caption text-muted-foreground">
- <div className="mr-2 flex w-4 shrink-0 justify-center">
- {leadIcon}
- </div>
- <div className="flex min-w-0 flex-1 items-center gap-1">
- {/* The platform's own entries read as a sentence without an actor. */}
- {!(isWakeup && entry.actor_type === "system") && (
- <span className="shrink-0 font-medium">
- {entry.actor_name || getActorName(entry.actor_type, entry.actor_id)}
- </span>
- )}
- <span className="truncate">
- <ActivityText
- entry={entry}
- text={
- isWakeup
+ <div key={entry.id} className="text-caption text-muted-foreground">
+ <div className="flex items-center">
+ <div className="mr-2 flex w-4 shrink-0 justify-center">{leadIcon}</div>
+ <div className="flex min-w-0 flex-1 items-center gap-1">
+ {/* The platform's own entries read as a sentence without an actor. */}
+ {!(isWakeup && entry.actor_type === "system") && (
+ <span className="shrink-0 font-medium">
+ {entry.actor_name || getActorName(entry.actor_type, entry.actor_id)}
+ </span>
+ )}
+ <span className="truncate">
+ <ActivityText
+ entry={entry}
+ text={isWakeup
? formatWakeupActivity(entry, t, wakeupText, getActorName)
- : formatActivity(entry, t, locale, getActorName, resolveStatusLabel)
- }
- />
- </span>
- {chip && (
- <span className="ml-auto inline-flex max-w-48 shrink-0 items-center gap-1 truncate rounded-xs bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">
- {chip}
+ : formatActivity(entry, t, locale, getActorName, resolveStatusLabel)}
+ />
</span>
- )}
- {(entry.coalesced_count ?? 1) > 1 &&
- entry.action !== "task_completed" &&
- entry.action !== "task_failed" && (
+ {chip && (
+ <span className="ml-auto inline-flex max-w-48 shrink-0 items-center gap-1 truncate rounded-xs bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">
+ {chip}
+ </span>
+ )}
+ {(entry.coalesced_count ?? 1) > 1 && entry.action !== "task_completed" && entry.action !== "task_failed" && (
<span className="shrink-0 rounded-xs bg-muted px-1.5 py-0.5 text-caption font-medium tabular-nums text-muted-foreground">
{t(($) => $.activity.coalesced_badge, { count: entry.coalesced_count ?? 1 })}
</span>
)}
- <Tooltip>
- <TooltipTrigger
- render={
+ <Tooltip>
+ <TooltipTrigger render={
<span className={cn("shrink-0 cursor-default", !chip && "ml-auto")}>
{timeAgo(entry.created_at)}
</span>
- }
- />
- <TooltipContent side="top">
- {new Date(entry.created_at).toLocaleString(locale)}
- </TooltipContent>
- </Tooltip>
+ } />
+ <TooltipContent side="top">{new Date(entry.created_at).toLocaleString(locale)}</TooltipContent>
+ </Tooltip>
+ </div>
</div>
+ {handoff && <div className="ml-6"><TimelineHandoff details={details} /></div>}
</div>
);
})}
@@ -914,6 +913,8 @@ function SubIssueRow({
<StatusPicker
status={child.status}
onUpdate={handleUpdate}
+ projectId={child.project_id}
+ issue={child}
align="start"
trigger={
<StatusIcon
@@ -2664,6 +2665,8 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
status={issue.status}
onUpdate={handleUpdateField}
align="start"
+ projectId={issue.project_id}
+ issue={issue}
onMarkDuplicate={actions.openMarkDuplicate}
isDuplicate={isDuplicateIssue(issue)}
/>
@@ -2672,11 +2675,13 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
<AssigneePicker assigneeType={issue.assignee_type} assigneeId={issue.assignee_id} onUpdate={handleUpdateField} align="start" />
</PropRow>
<PropRow label={t(($) => $.detail.prop_project)}>
- <ProjectPicker
+ <IssueProjectPicker
projectId={issue.project_id}
onUpdate={handleUpdateField}
+ issue={issue}
/>
</PropRow>
+ <IssueWorkflowPropRow projectId={issue.project_id} status={issue.status} label={t(($) => $.workflows.project.label)} />
{/* Optional props — rendered only when set on the issue OR added
via "+ Add property" in this session. Row order follows the
@@ -3954,3 +3959,23 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
</ResizablePanelGroup>,
);
}
+
+/** The workflow the issue follows through its project (MUL-7420). */
+function IssueWorkflowPropRow({
+ projectId,
+ status,
+ label,
+}: {
+ projectId: string | null;
+ status: string;
+ label: string;
+}) {
+ const wsId = useWorkspaceId();
+ const workflow = useProjectWorkflow(wsId, projectId);
+ if (!workflow) return null;
+ return (
+ <PropRow label={label}>
+ <IssueFlowCard projectId={projectId} currentStatus={status} />
+ </PropRow>
+ );
+}
diff --git a/packages/views/issues/components/list-view.test.tsx b/packages/views/issues/components/list-view.test.tsx
index 72a1a210ed..63044a7807 100644
--- a/packages/views/issues/components/list-view.test.tsx
+++ b/packages/views/issues/components/list-view.test.tsx
@@ -74,6 +74,7 @@ const mockViewState: {
listCollapsedStatuses: IssueStatus[];
toggleListCollapsed: (status: IssueStatus) => void;
showStatus: (status: IssueStatus) => void;
+ hiddenStatuses: IssueStatus[];
} = {
sortBy: "position",
sortDirection: "asc",
@@ -87,6 +88,7 @@ const mockViewState: {
: [...mockViewState.listCollapsedStatuses, status];
}),
showStatus: vi.fn(),
+ hiddenStatuses: ["cancelled"],
};
vi.mock("@multica/core/issues/stores/view-store-context", () => ({
diff --git a/packages/views/issues/components/pickers/status-picker.test.tsx b/packages/views/issues/components/pickers/status-picker.test.tsx
index b89eba69bd..dbcc1cd090 100644
--- a/packages/views/issues/components/pickers/status-picker.test.tsx
+++ b/packages/views/issues/components/pickers/status-picker.test.tsx
@@ -3,7 +3,7 @@
import { cleanup, fireEvent, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { buildIssueStatusCatalog } from "@multica/core/issue-statuses";
-import type { IssueStatusEntry } from "@multica/core/types";
+import type { IssueStatusEntry, IssueWorkflow } from "@multica/core/types";
import { renderWithI18n } from "../../../test/i18n";
import { StatusPicker } from "./status-picker";
@@ -21,6 +21,23 @@ vi.mock("@multica/core/issue-statuses/hooks", () => ({
useIssueStatuses: () => buildIssueStatusCatalog(catalogEntries),
}));
+// Project workflows (MUL-7420): the picker resolves the issue's project and its
+// workflow through one hook, fed directly here like the catalog.
+let projectWorkflow: IssueWorkflow | null = null;
+
+vi.mock("@multica/core/issue-workflows", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/issue-workflows")>()),
+ useProjectWithWorkflow: () => ({ project: null, workflow: projectWorkflow }),
+}));
+
+vi.mock("../../../common/actor-avatar", () => ({
+ ActorAvatar: ({ actorId }: { actorId: string }) => <span data-testid={`avatar-${actorId}`} />,
+}));
+
+vi.mock("@multica/core/workspace/hooks", () => ({
+ useActorName: () => ({ getActorName: (_type: string, id: string) => (id === "agent-1" ? "Sentinel" : "Unknown") }),
+}));
+
function entry(overrides: Partial<IssueStatusEntry>): IssueStatusEntry {
return {
id: overrides.key ?? "id",
@@ -71,6 +88,7 @@ function optionRow(label: string): HTMLElement {
afterEach(() => {
cleanup();
catalogEntries = undefined;
+ projectWorkflow = null;
});
describe("StatusPicker trigger color", () => {
@@ -163,3 +181,49 @@ describe("StatusPicker on an issue that already is a duplicate", () => {
expect(screen.getByRole("button", { name: "Change original" })).toBeTruthy();
});
});
+
+describe("StatusPicker in a project that uses a workflow", () => {
+ const TODO = entry({ id: "todo", key: "todo", name: "Todo", category: "unstarted", is_system: true, position: 0 });
+ const DONE = entry({ id: "done", key: "done", name: "Done", category: "done", is_system: true, position: 0 });
+
+ it("offers only the workflow's steps, in workflow order, naming each handoff", () => {
+ catalogEntries = [TODO, IN_REVIEW, QA, DONE];
+ projectWorkflow = {
+ id: "wf-1",
+ workspace_id: "workspace-1",
+ name: "Delivery",
+ description: "",
+ is_default: false,
+ steps: [
+ { status_key: "todo", handler: { type: "none" }, instructions: "" },
+ { status_key: "qa", handler: { type: "agent", id: "agent-1" }, instructions: "" },
+ { status_key: "done", handler: { type: "none" }, instructions: "" },
+ ],
+ project_ids: ["project-1"],
+ created_at: "",
+ updated_at: "",
+ };
+ renderWithI18n(
+ <StatusPicker status="todo" projectId="project-1" onUpdate={() => {}} open onOpenChange={() => {}} />,
+ );
+
+ const rows = Array.from(document.querySelectorAll("button[data-picker-item]")).map(
+ (el) => el.textContent?.trim(),
+ );
+ // Only a column with a handoff carries its handler's avatar.
+ expect(rows).toEqual(["Todo", "QAHands off to Sentinel", "Done"]);
+ expect(screen.getByText("Hands off to Sentinel").className).toContain("sr-only");
+ expect(screen.getByTestId("avatar-agent-1")).toBeTruthy();
+ expect(screen.getByText("Delivery")).toBeTruthy();
+ expect(screen.queryByText("In Review")).toBeNull();
+ });
+
+ it("offers the whole catalog when the project uses the Default workflow", () => {
+ catalogEntries = [TODO, IN_REVIEW, QA, DONE];
+ renderWithI18n(
+ <StatusPicker status="todo" projectId="project-1" onUpdate={() => {}} open onOpenChange={() => {}} />,
+ );
+ expect(optionRow("In Review")).toBeTruthy();
+ expect(screen.queryByText(/Hands off to/)).toBeNull();
+ });
+});
diff --git a/packages/views/issues/components/pickers/status-picker.tsx b/packages/views/issues/components/pickers/status-picker.tsx
index 19b9ec3289..9d4b759658 100644
--- a/packages/views/issues/components/pickers/status-picker.tsx
+++ b/packages/views/issues/components/pickers/status-picker.tsx
@@ -1,16 +1,21 @@
"use client";
import { useMemo, useState } from "react";
-import { CircleEqual } from "lucide-react";
+import { CircleEqual, CornerDownRight } from "lucide-react";
import type { IssueStatus, UpdateIssueRequest } from "@multica/core/types";
import { STATUS_CONFIG } from "@multica/core/issues/config";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import { useWorkspaceId } from "@multica/core/hooks";
+import { stepHandsOff, workflowStep } from "@multica/core/issue-workflows";
+import type { IssueWorkflowStep, Project } from "@multica/core/types";
import { StatusIcon } from "../status-icon";
import { PropertyPicker, PickerItem } from "./property-picker";
import { useT } from "../../../i18n";
import { useStatusLabel } from "../../utils/status-label";
-import { useStatusOptions } from "../../utils/status-options";
+import { useIssueStatusOptions } from "../../utils/status-options";
+import { stepHandlerActor, useStepHandlerLabel } from "../../../workflows/step-handler";
+import { WorkflowHandoffConfirmDialog } from "../../../workflows/handoff-confirm-dialog";
+import { ActorAvatar } from "../../../common/actor-avatar";
/** Above this many options the flat list stops being scannable. */
const SEARCH_THRESHOLD = 9;
@@ -25,6 +30,9 @@ export function StatusPicker({
align,
onMarkDuplicate,
isDuplicate,
+ projectId,
+ allowedStatuses,
+ issue,
}: {
/**
* The currently-selected status, used to check the matching row. `null`
@@ -47,6 +55,23 @@ export function StatusPicker({
onMarkDuplicate?: () => void;
/** The issue already carries a mark, so the action re-points it. */
isDuplicate?: boolean;
+ /**
+ * The issue's project. When it uses a workflow, only that workflow's steps
+ * are offered, in workflow order, each naming who entering it hands the
+ * issue to. Omit when the surface spans projects. (MUL-7420)
+ */
+ projectId?: string | null;
+ /**
+ * Narrows the options to these keys — for a selection spanning projects,
+ * the statuses every selected issue's workflow allows. Null offers all.
+ */
+ allowedStatuses?: ReadonlySet<string> | null;
+ /**
+ * The single issue being edited. With a workflow, choosing a step that
+ * hands the issue off first shows the handoff confirmation for it; the
+ * write carries the choice to stop the previous agent's run. (MUL-7420)
+ */
+ issue?: { id: string; identifier: string };
}) {
const [internalOpen, setInternalOpen] = useState(false);
const open = controlledOpen ?? internalOpen;
@@ -60,15 +85,13 @@ export function StatusPicker({
const { categoryOf, colorOf, iconOf } = useIssueStatuses(wsId);
const labelOf = useStatusLabel(wsId);
- /**
- * Offerable statuses as one flat list, in canonical category order.
- *
- * Archived statuses are excluded: archiving retires a status from future
- * assignment while leaving the issues already on it untouched. Falls back to
- * the 7 built-ins until the catalog lands, so a cold render offers exactly
- * what it always did instead of an empty popover. (MUL-6243)
- */
- const allOptions = useStatusOptions(wsId);
+ // The project workflow's steps, or the catalog in canonical category order
+ // without archived statuses (MUL-6243).
+ const { options: projectOptions, workflow, project } = useIssueStatusOptions(wsId, projectId);
+ const allOptions = useMemo(
+ () => (allowedStatuses ? projectOptions.filter((o) => allowedStatuses.has(o.key)) : projectOptions),
+ [projectOptions, allowedStatuses],
+ );
const options = useMemo(() => {
const q = query.trim().toLowerCase();
@@ -76,43 +99,54 @@ export function StatusPicker({
return allOptions.filter((o) => o.label.toLowerCase().includes(q));
}, [allOptions, query]);
- const searchable = allOptions.length > SEARCH_THRESHOLD;
+ const searchable = !!workflow || allOptions.length > SEARCH_THRESHOLD;
+ const [pendingStatus, setPendingStatus] = useState<IssueStatus | null>(null);
+
+ const markDuplicate = onMarkDuplicate ? (
+ // Rendered outside the arrow-key listbox so keyboard nav and search
+ // never treat the action as another status option.
+ <button
+ type="button"
+ onClick={() => {
+ setOpen(false);
+ setQuery("");
+ onMarkDuplicate();
+ }}
+ className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-body hover:bg-accent transition-colors"
+ >
+ <CircleEqual className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <span>
+ {t(($) =>
+ isDuplicate ? $.pickers.status.change_original : $.pickers.status.mark_duplicate,
+ )}
+ </span>
+ </button>
+ ) : null;
return (
+ <>
<PropertyPicker
open={open}
onOpenChange={(v) => {
if (!v) setQuery("");
setOpen(v);
}}
- width="w-52"
+ width={workflow ? "w-60" : "w-52"}
align={align}
triggerRender={triggerRender}
searchable={searchable}
searchPlaceholder={t(($) => $.filters.search_status)}
onSearchChange={setQuery}
- footer={
- onMarkDuplicate ? (
- // Rendered outside the arrow-key listbox so keyboard nav and search
- // never treat the action as another status option.
- <button
- type="button"
- onClick={() => {
- setOpen(false);
- setQuery("");
- onMarkDuplicate();
- }}
- className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-body hover:bg-accent transition-colors"
- >
- <CircleEqual className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
- <span>
- {t(($) =>
- isDuplicate ? $.pickers.status.change_original : $.pickers.status.mark_duplicate,
- )}
- </span>
- </button>
+ header={
+ workflow ? (
+ <div className="truncate px-2 pb-1 pt-1.5 text-caption text-muted-foreground">
+ {project
+ ? t(($) => $.workflows.picker.header, { workflow: workflow.name, project: project.title })
+ : workflow.name}
+ </div>
) : undefined
}
+ footer={markDuplicate ?? undefined}
trigger={
customTrigger ??
(status != null ? (
@@ -135,9 +169,13 @@ export function StatusPicker({
selected={option.key === status}
hoverClassName={STATUS_CONFIG[option.category].hoverBg}
onClick={() => {
- onUpdate({ status: option.key });
setOpen(false);
setQuery("");
+ if (workflow && issue && option.key !== status && stepHandsOff(workflowStep(workflow, option.key))) {
+ setPendingStatus(option.key);
+ return;
+ }
+ onUpdate({ status: option.key });
}}
>
<StatusIcon
@@ -147,9 +185,50 @@ export function StatusPicker({
icon={option.icon}
className="h-3.5 w-3.5"
/>
- <span className="truncate">{option.label}</span>
+ <span className="min-w-12 truncate">{option.label}</span>
+ {workflow && option.key !== status && (
+ <StepHandoffHint step={workflowStep(workflow, option.key)} project={project} />
+ )}
</PickerItem>
))}
</PropertyPicker>
+ {workflow && issue && (
+ <WorkflowHandoffConfirmDialog
+ issue={pendingStatus ? issue : null}
+ toStatus={pendingStatus ?? ""}
+ onCancel={() => setPendingStatus(null)}
+ onConfirm={({ stopPreviousRuns }) => {
+ const next = pendingStatus;
+ setPendingStatus(null);
+ if (next) onUpdate({ status: next, ...(stopPreviousRuns ? { stop_previous_assignee_runs: true } : {}) });
+ }}
+ />
+ )}
+ </>
+ );
+}
+
+/**
+ * The avatar of whoever entering a workflow column hands the issue to; the
+ * name is in the tooltip. Nothing for a column that keeps the assignee.
+ * (MUL-7420)
+ */
+function StepHandoffHint({ step, project }: { step: IssueWorkflowStep | undefined; project: Project | null }) {
+ const { t } = useT("issues");
+ const handlerLabel = useStepHandlerLabel(project);
+ const handler = handlerLabel(step);
+ if (!handler) return null;
+ const actor = stepHandlerActor(step, project);
+ const text = t(($) => $.workflows.hands_off_to, { name: handler });
+ return (
+ <span className="ml-auto flex shrink-0 items-center gap-1 pl-2 text-caption text-muted-foreground" title={text}>
+ <span className="sr-only">{text}</span>
+ <CornerDownRight aria-hidden className="size-3 shrink-0" />
+ {actor ? (
+ <ActorAvatar actorType={actor.type} actorId={actor.id} size="xs" profileLink={false} />
+ ) : (
+ <span aria-hidden className="max-w-20 truncate">{handler}</span>
+ )}
+ </span>
);
}
diff --git a/packages/views/issues/components/swimlane-view.test.tsx b/packages/views/issues/components/swimlane-view.test.tsx
index 06162f1a98..058b15b9c0 100644
--- a/packages/views/issues/components/swimlane-view.test.tsx
+++ b/packages/views/issues/components/swimlane-view.test.tsx
@@ -123,6 +123,7 @@ const mockViewState: {
toggleSwimlaneCollapsed: (key: string) => void;
hideStatus: (s: string) => void;
showStatus: (s: string) => void;
+ hiddenStatuses: string[];
priorityFilters?: string[];
assigneeFilters?: any[];
includeNoAssignee?: boolean;
@@ -145,6 +146,7 @@ const mockViewState: {
toggleSwimlaneCollapsed: vi.fn(),
hideStatus: vi.fn(),
showStatus: vi.fn(),
+ hiddenStatuses: [],
priorityFilters: [],
assigneeFilters: [],
includeNoAssignee: false,
diff --git a/packages/views/issues/components/table-view.tsx b/packages/views/issues/components/table-view.tsx
index fa51d5cd8b..9d76ca59c4 100644
--- a/packages/views/issues/components/table-view.tsx
+++ b/packages/views/issues/components/table-view.tsx
@@ -1174,6 +1174,8 @@ function IssueTableBodyCell({
<StatusPicker
status={issue.status}
onUpdate={onUpdate}
+ projectId={issue.project_id}
+ issue={issue}
align="start"
open={editorOpen}
onOpenChange={setEditorOpen}
diff --git a/packages/views/issues/surface/actions-context.tsx b/packages/views/issues/surface/actions-context.tsx
index c5318a1031..0458c96aa8 100644
--- a/packages/views/issues/surface/actions-context.tsx
+++ b/packages/views/issues/surface/actions-context.tsx
@@ -24,10 +24,11 @@ export interface IssueSurfaceActions {
updates: Partial<UpdateIssueRequest>,
options?: IssueSurfaceMutationOptions,
) => void;
+ /** Resolves with how many issues the server wrote; it skips the ones its per-issue guards refuse. */
batchUpdate: (
issueIds: string[],
updates: Partial<UpdateIssueRequest>,
- ) => Promise<void>;
+ ) => Promise<{ updated: number }>;
batchDelete: (issueIds: string[]) => Promise<void>;
}
diff --git a/packages/views/issues/surface/use-issue-surface-actions.ts b/packages/views/issues/surface/use-issue-surface-actions.ts
index 794b6e10a1..ee69539856 100644
--- a/packages/views/issues/surface/use-issue-surface-actions.ts
+++ b/packages/views/issues/surface/use-issue-surface-actions.ts
@@ -23,6 +23,7 @@ export type MoveIssueUpdates = Pick<
| "assignee_type"
| "assignee_id"
| "position"
+ | "stop_previous_assignee_runs"
| "parent_issue_id"
| "project_id"
> & {
@@ -131,9 +132,7 @@ export function useIssueSurfaceActions({
errorMessage: t(($) => $.detail.toast_move_issue_failed),
...options,
}),
- batchUpdate: async (issueIds, updates) => {
- await batchUpdateMutation.mutateAsync({ ids: issueIds, updates });
- },
+ batchUpdate: (issueIds, updates) => batchUpdateMutation.mutateAsync({ ids: issueIds, updates }),
batchDelete: async (issueIds) => {
await batchDeleteMutation.mutateAsync(issueIds);
},
diff --git a/packages/views/issues/surface/use-issue-surface-controller.ts b/packages/views/issues/surface/use-issue-surface-controller.ts
index 515a8e2b82..e30e0aa7c9 100644
--- a/packages/views/issues/surface/use-issue-surface-controller.ts
+++ b/packages/views/issues/surface/use-issue-surface-controller.ts
@@ -16,6 +16,7 @@ import type {
import { workspaceWorkingAgentsOptions } from "@multica/core/agents";
import { useWorkspaceId } from "@multica/core/hooks";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { useColumnWorkflow, workflowColumns } from "../utils/workflow-columns";
import { statusFilterColumns, visibleStatusKeys } from "@multica/core/issues";
import { dateOnlyToLocalDate } from "@multica/core/issues/date";
import type { IssueSortParam } from "@multica/core/issues/queries";
@@ -240,6 +241,7 @@ export function useIssueSurfaceController({
const listCollapsedStatuses = useViewStore((s) => s.listCollapsedStatuses);
const hiddenStatusKeys = useViewStore((s) => s.hiddenStatuses);
const catalog = useIssueStatuses(wsId);
+ const { workflow: projectWorkflow } = useColumnWorkflow(wsId, projectId, statusFilters.length > 0);
const [tableSearch, setTableSearch] = useState("");
const allowedModes = useMemo(() => new Set<IssueSurfaceMode>(modes), [modes]);
@@ -362,10 +364,13 @@ export function useIssueSurfaceController({
// select exact keys. Selecting a key explicitly restores its hidden column.
const serverStatuses = useMemo<IssueStatus[]>(
() => {
- const visible = visibleStatusKeys(
- statusFilters,
- hiddenStatusKeys,
- catalog,
+ const visible = workflowColumns(
+ visibleStatusKeys(
+ statusFilters,
+ hiddenStatusKeys,
+ catalog,
+ ),
+ projectWorkflow,
);
return effectiveViewMode === "list"
? visible.filter((status) => !listCollapsedStatuses.includes(status))
@@ -377,6 +382,7 @@ export function useIssueSurfaceController({
listCollapsedStatuses,
catalog,
statusFilters,
+ projectWorkflow,
],
);
diff --git a/packages/views/issues/surface/use-issue-surface-data.ts b/packages/views/issues/surface/use-issue-surface-data.ts
index 7b9174c252..93ffbffffd 100644
--- a/packages/views/issues/surface/use-issue-surface-data.ts
+++ b/packages/views/issues/surface/use-issue-surface-data.ts
@@ -9,6 +9,7 @@ import { issueSurfaceGanttOptions } from "@multica/core/issues/surface/repositor
import type { IssueSurfaceQueryPlan } from "@multica/core/issues/surface/query-plan";
import type { IssueStatus, ProjectStatus, PropertyFilterValue } from "@multica/core/types";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { surfaceStatusOrder, useColumnWorkflow, workflowColumns } from "../utils/workflow-columns";
import { issueBehavesAsAny, statusColumnKeys, visibleStatusKeys } from "@multica/core/issues";
import {
applyIssueFilters,
@@ -370,20 +371,26 @@ export function useIssueSurfaceData({
);
const catalog = useIssueStatuses(wsId);
+ // Columns follow the project's workflow, or Default outside a project.
+ // (MUL-7420)
+ const { workflow: projectWorkflow } = useColumnWorkflow(wsId, projectId, statusFilters.length > 0);
const visibleStatuses = useMemo<IssueStatus[]>(() => {
// An explicit exact-key filter wins over hidden column preferences.
- return visibleStatusKeys(
- statusFilters,
- hiddenStatusKeys,
- catalog,
+ return workflowColumns(
+ visibleStatusKeys(
+ statusFilters,
+ hiddenStatusKeys,
+ catalog,
+ ),
+ projectWorkflow,
);
- }, [statusFilters, hiddenStatusKeys, catalog]);
+ }, [statusFilters, hiddenStatusKeys, catalog, projectWorkflow]);
// Each catalog status can be hidden or restored independently.
const hiddenStatuses = useMemo<IssueStatus[]>(
- () => statusColumnKeys(catalog).filter((s) => !visibleStatuses.includes(s)),
- [catalog, visibleStatuses],
+ () => surfaceStatusOrder(statusColumnKeys(catalog), projectWorkflow).filter((s) => !visibleStatuses.includes(s)),
+ [catalog, projectWorkflow, visibleStatuses],
);
const activeFilters = useMemo(
diff --git a/packages/views/issues/utils/drag-utils.ts b/packages/views/issues/utils/drag-utils.ts
index 9f94e3e3b1..b8595053da 100644
--- a/packages/views/issues/utils/drag-utils.ts
+++ b/packages/views/issues/utils/drag-utils.ts
@@ -10,7 +10,7 @@ import type { BoardColumnGroup } from "../components/board-column";
export type DragMoveTargetUpdates = Pick<
UpdateIssueRequest,
- "status" | "assignee_type" | "assignee_id" | "project_id" | "position"
+ "status" | "assignee_type" | "assignee_id" | "project_id" | "position" | "stop_previous_assignee_runs"
>;
export type DragMoveUpdates = DragMoveTargetUpdates & {
diff --git a/packages/views/issues/utils/status-options.ts b/packages/views/issues/utils/status-options.ts
index e46f5104ae..a14086f952 100644
--- a/packages/views/issues/utils/status-options.ts
+++ b/packages/views/issues/utils/status-options.ts
@@ -7,11 +7,12 @@ import {
BUILT_IN_STATUS_ORDER,
} from "@multica/core/issues/config";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { useProjectWithWorkflow } from "@multica/core/issue-workflows";
import {
issueStatusColor,
normalizeIssueStatusCategory,
} from "@multica/core/issue-statuses/queries";
-import type { IssueStatus, IssueStatusCategory } from "@multica/core/types";
+import type { IssueStatus, IssueStatusCategory, IssueWorkflow, Project } from "@multica/core/types";
import { useStatusLabel } from "./status-label";
export interface StatusOption {
@@ -83,3 +84,34 @@ export function useStatusOptions(
[includeArchivedKeys, labelOf, statuses],
);
}
+
+/**
+ * The statuses an issue in `projectId` may take: its project workflow's steps
+ * in workflow order, or the whole catalog when the project has none. Every
+ * single-issue status control offers this set, so a status the workflow
+ * refuses is never on offer. (MUL-7420)
+ */
+export function useIssueStatusOptions(
+ wsId: string,
+ projectId: string | null | undefined,
+): { options: StatusOption[]; workflow: IssueWorkflow | null; project: Project | null } {
+ const catalogOptions = useStatusOptions(wsId);
+ const { categoryOf, colorOf, iconOf } = useIssueStatuses(wsId);
+ const labelOf = useStatusLabel(wsId);
+ const { workflow, project } = useProjectWithWorkflow(wsId, projectId);
+ const options = useMemo<StatusOption[]>(() => {
+ if (!workflow) return catalogOptions;
+ const byKey = new Map(catalogOptions.map((o) => [o.key, o]));
+ return workflow.steps.map(
+ (step) =>
+ byKey.get(step.status_key) ?? {
+ key: step.status_key,
+ category: categoryOf(step.status_key),
+ label: labelOf(step.status_key),
+ color: colorOf(step.status_key),
+ icon: iconOf(step.status_key),
+ },
+ );
+ }, [catalogOptions, categoryOf, colorOf, iconOf, labelOf, workflow]);
+ return { options, workflow, project };
+}
diff --git a/packages/views/issues/utils/workflow-columns.test.ts b/packages/views/issues/utils/workflow-columns.test.ts
new file mode 100644
index 0000000000..ac25e1b6a7
--- /dev/null
+++ b/packages/views/issues/utils/workflow-columns.test.ts
@@ -0,0 +1,94 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from "vitest";
+import type { IssueWorkflow } from "@multica/core/types";
+import { surfaceStatusOrder, useColumnWorkflow, workflowColumns } from "./workflow-columns";
+
+const workflow: IssueWorkflow = {
+ id: "wf-1",
+ workspace_id: "ws-1",
+ name: "Delivery",
+ description: "",
+ is_default: false,
+ steps: ["todo", "code_review", "in_progress", "done"].map((status_key) => ({
+ status_key,
+ handler: { type: "none" as const },
+ instructions: "",
+ })),
+ project_ids: [],
+ created_at: "",
+ updated_at: "",
+};
+
+const { defaultWithoutBlocked } = vi.hoisted(() => ({
+ defaultWithoutBlocked: {
+ id: "default",
+ workspace_id: "ws-1",
+ name: "Default",
+ description: "",
+ is_default: true,
+ steps: ["todo", "in_progress", "in_review", "done", "cancelled"].map((status_key) => ({
+ status_key,
+ handler: { type: "none" as const },
+ instructions: "",
+ })),
+ project_ids: [],
+ created_at: "",
+ updated_at: "",
+ },
+}));
+
+vi.mock("@multica/core/config", () => ({ useFeatureEnabled: () => true }));
+vi.mock("@multica/core/issue-workflows", () => ({
+ defaultWorkflow: () => defaultWithoutBlocked,
+ useIssueWorkflows: () => ({ workflows: [defaultWithoutBlocked] }),
+ useProjectWorkflow: () => defaultWithoutBlocked,
+}));
+
+describe("workflowColumns (MUL-7420)", () => {
+ it("passes catalog columns through for the Default workflow", () => {
+ expect(workflowColumns(["backlog", "todo", "done"], null)).toEqual(["backlog", "todo", "done"]);
+ });
+
+ it("uses workflow order and drops statuses the workflow does not list", () => {
+ expect(workflowColumns(["backlog", "todo", "in_progress", "done", "code_review"], workflow)).toEqual([
+ "todo",
+ "code_review",
+ "in_progress",
+ "done",
+ ]);
+ });
+
+ it("keeps hidden columns hidden", () => {
+ expect(workflowColumns(["todo", "done"], workflow)).toEqual(["todo", "done"]);
+ expect(workflowColumns(null, workflow)).toEqual(["todo", "code_review", "in_progress", "done"]);
+ });
+});
+
+describe("useColumnWorkflow (MUL-7420)", () => {
+ it("follows the project's workflow on a project board", () => {
+ expect(useColumnWorkflow("ws-1", "project-1", false).workflow).toBe(defaultWithoutBlocked);
+ });
+
+ it("lets an explicit status filter reach a status the project's workflow dropped", () => {
+ const { workflow: selected } = useColumnWorkflow("ws-1", "project-1", true);
+ expect(workflowColumns(["blocked"], selected)).toEqual(["blocked"]);
+ });
+});
+
+describe("surfaceStatusOrder (MUL-7420)", () => {
+ it("lists the workflow's steps, then the catalog statuses it leaves out", () => {
+ expect(surfaceStatusOrder(["backlog", "todo", "in_progress", "in_review", "done", "blocked"], workflow)).toEqual([
+ "todo",
+ "code_review",
+ "in_progress",
+ "done",
+ "backlog",
+ "in_review",
+ "blocked",
+ ]);
+ });
+
+ it("is the catalog order without a workflow", () => {
+ expect(surfaceStatusOrder(["backlog", "todo"], null)).toEqual(["backlog", "todo"]);
+ });
+});
diff --git a/packages/views/issues/utils/workflow-columns.ts b/packages/views/issues/utils/workflow-columns.ts
new file mode 100644
index 0000000000..08c824f2c0
--- /dev/null
+++ b/packages/views/issues/utils/workflow-columns.ts
@@ -0,0 +1,56 @@
+import { useFeatureEnabled } from "@multica/core/config";
+import { PROJECT_WORKFLOWS_V1_FLAG } from "@multica/core/feature-flags";
+import { defaultWorkflow, useIssueWorkflows, useProjectWorkflow } from "@multica/core/issue-workflows";
+import type { IssueStatus, IssueWorkflow } from "@multica/core/types";
+
+/**
+ * The status columns of a surface whose columns follow a workflow (MUL-7420):
+ * the workflow's steps, in workflow order, narrowed to `visible` (hidden-column
+ * preferences and status filters). Without a workflow the catalog-ordered
+ * `visible` list passes through unchanged. `visible === null` returns every
+ * step.
+ */
+export function workflowColumns(
+ visible: readonly IssueStatus[] | null,
+ workflow: IssueWorkflow | null,
+): IssueStatus[] {
+ if (!workflow) return visible ? [...visible] : [];
+ const keys = workflow.steps.map((s) => s.status_key as IssueStatus);
+ if (!visible) return keys;
+ const allowed = new Set(visible);
+ return keys.filter((key) => allowed.has(key));
+}
+
+/**
+ * The workflow a surface's columns follow (MUL-7420). A project surface shows
+ * its project's columns. Elsewhere, while workflows are on, columns follow
+ * Default. Statuses outside the workflow wait in the hidden-columns panel, and
+ * a status filter that picks keys explicitly shows exactly those — on a
+ * project too, which is how an issue left in a status its workflow no longer
+ * lists is found.
+ */
+export function useColumnWorkflow(
+ wsId: string,
+ projectId: string | null | undefined,
+ hasStatusFilter: boolean,
+): { workflow: IssueWorkflow | null } {
+ const enabled = useFeatureEnabled(PROJECT_WORKFLOWS_V1_FLAG, false);
+ const { workflows } = useIssueWorkflows(wsId);
+ const projectWorkflow = useProjectWorkflow(wsId, projectId);
+ if (hasStatusFilter) return { workflow: null };
+ if (projectId) return { workflow: projectWorkflow };
+ if (!enabled) return { workflow: null };
+ return { workflow: defaultWorkflow(workflows) };
+}
+
+/**
+ * Every status a surface can show, in column order: the workflow's steps, then
+ * the catalog statuses it leaves out. What is not visible of this list is the
+ * hidden-columns panel.
+ */
+export function surfaceStatusOrder(catalogKeys: readonly IssueStatus[], workflow: IssueWorkflow | null): IssueStatus[] {
+ if (!workflow) return [...catalogKeys];
+ const steps = workflowColumns(null, workflow);
+ const inWorkflow = new Set(steps);
+ return [...steps, ...catalogKeys.filter((key) => !inWorkflow.has(key))];
+}
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index d62026673d..6e6ee9538d 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -371,7 +371,10 @@
"empty_grouping": "No matching issues",
"no_value": "No value",
"ordered_by": "Board ordered by {{field}}",
- "manual_reorder_hint": "Switch to Manual ordering to rearrange issues within a column."
+ "manual_reorder_hint": "Switch to Manual ordering to rearrange issues within a column.",
+ "filter_to_status": "Filter to this status",
+ "outside_workflow": "Not in this board’s workflow",
+ "workflow_columns_note": "Columns come from the board’s workflow; views outside a project use Default."
},
"peek": {
"panel_label": "Issue preview",
@@ -848,6 +851,8 @@
"update_success_one": "Updated {{count}} issue",
"update_success_other": "Updated {{count}} issues",
"update_failed": "Failed to update issues",
+ "update_partial_one": "Updated {{updated}} of {{count}} issue. The rest don't allow this change and were left as they were.",
+ "update_partial_other": "Updated {{updated}} of {{count}} issues. The rest don't allow this change and were left as they were.",
"delete_success_one": "Deleted {{count}} issue",
"delete_success_other": "Deleted {{count}} issues",
"delete_failed": "Failed to delete issues",
@@ -1474,5 +1479,274 @@
"overview_close": "Close",
"overview_empty": "No deliverables of this type.",
"group_comment_by": "Comment by {{name}}"
+ },
+ "workflows": {
+ "default_name": "Default",
+ "default_summary": "Every status, no handoffs",
+ "hands_off_to": "Hands off to {{name}}",
+ "not_in_workflow": "Not in the {{name}} workflow",
+ "drop_blocked": "{{status}} isn't part of the {{name}} workflow",
+ "create_handoff_hint": "Will be handed to {{name}}",
+ "handler": {
+ "none": "Keep assignee",
+ "agent": "Agent",
+ "squad": "Squad",
+ "member": "Member",
+ "project_lead": "Project lead",
+ "creator": "Issue creator",
+ "project_lead_named": "{{name}} (project lead)"
+ },
+ "settings": {
+ "title": "Workflows",
+ "new": "New workflow",
+ "projects_one": "{{count}} project",
+ "projects_other": "{{count}} projects",
+ "default_projects": "Projects without a workflow",
+ "no_projects": "Not used yet",
+ "edit": "Edit",
+ "delete": "Delete",
+ "delete_title": "Delete {{name}}?",
+ "delete_description": "Issues keep their statuses.",
+ "delete_in_use": "Switch its projects to another workflow first.",
+ "deleted": "Workflow deleted",
+ "delete_error": "Couldn't delete the workflow",
+ "statuses_title": "Status library",
+ "statuses_one": "{{count}} status",
+ "statuses_other": "{{count}} statuses",
+ "handoffs_one": "{{count}} handoff step",
+ "handoffs_other": "{{count}} handoff steps",
+ "no_handoffs": "No handoffs",
+ "used_by_one": "Used by {{count}} project: {{names}}",
+ "used_by_other": "Used by {{count}} projects: {{names}}",
+ "used_by_default_one": "Used by {{count}} project: {{names}}, and issues without a project",
+ "used_by_default_other": "Used by {{count}} projects: {{names}}, and issues without a project",
+ "used_by_default_none": "Used by issues without a project",
+ "new_blank": "Blank workflow",
+ "from_template": "From a template"
+ },
+ "editor": {
+ "create_title": "New workflow",
+ "edit_title": "Edit workflow",
+ "name": "Name",
+ "name_placeholder": "e.g. Delivery",
+ "description": "Description",
+ "steps": "Steps",
+ "add_step": "Add step",
+ "start": "Start",
+ "set_start": "Make starting step",
+ "move_up": "Move up",
+ "move_down": "Move down",
+ "remove": "Remove column",
+ "on_enter": "On entering, hand to",
+ "choose_target": "Choose…",
+ "instructions": "Handoff instructions",
+ "instructions_placeholder": "What should happen in this step?",
+ "next": "When done, move to",
+ "back": "When changes are needed, move back to",
+ "none_option": "Not set",
+ "save": "Save",
+ "create": "Create",
+ "cancel": "Cancel",
+ "saved": "Workflow saved",
+ "created": "Workflow created",
+ "error": "Couldn't save the workflow",
+ "used_by_note_one": "Used by {{count}} project: {{names}}. Saved changes apply to it right away.",
+ "used_by_note_other": "Used by {{count}} projects: {{names}}. Saved changes apply to them right away.",
+ "unused_note": "No project uses it yet. Pick it in a project’s properties.",
+ "duplicate": "Duplicate as new workflow",
+ "copy_name": "{{name}} copy",
+ "more": "More actions",
+ "steps_hint": "Drag to reorder the middle columns. Backlog and Blocked are optional. A new status is created when you save.",
+ "reorder": "Reorder {{name}}",
+ "card_hand_to": "Hand to",
+ "card_then": "then → {{status}}",
+ "status": "Status",
+ "status_hint": "Statuses come from the library. Rename or recolor them there; the change reaches every workflow that uses them.",
+ "handler_hint_on": "When an issue enters this step, its assignee becomes this handler; an agent or squad starts working right away.",
+ "handler_hint_off": "Entering this step keeps the assignee and starts no run.",
+ "handler_hint_lead": "Resolved per project: each project’s lead.",
+ "handler_hint_creator": "Resolved per issue: whoever created it.",
+ "target_agent": "Agent",
+ "target_squad": "Squad · leader dispatches",
+ "target_member": "Member",
+ "instructions_hint": "Sent to the handler with this run, alongside the issue description and comments.",
+ "next_hint": "Written into the handler’s brief so it knows which status comes next. The system never advances the status when a run ends.",
+ "preview_brief": "Preview the agent’s brief",
+ "preview_title": "Brief for the “{{status}}” step",
+ "preview_description": "What the handler’s run receives when an issue enters this step. Saved changes are not required to preview.",
+ "description_placeholder": "Add a description",
+ "select_step": "Select a column to set who it hands issues to.",
+ "unsaved": "Unsaved changes",
+ "not_found": "This workflow no longer exists.",
+ "default_note": "Default is the board of every project that doesn’t pick a workflow, and of views outside a project.",
+ "new_badge": "New",
+ "columns": "Columns",
+ "include_status": "Include {{status}}",
+ "step_off_short": "Off",
+ "step_off": "Switched off: this workflow leaves the status out. Turn it on in the step list to use it.",
+ "status_new_hint": "A new status. It is added to the status library when you save.",
+ "no_other_status": "Every status is already a step.",
+ "no_handoff_step": "This step doesn't hand off: issues entering it keep their assignee and start no run.",
+ "new_step_handoff": "Save the workflow first; the new status can hand off after that."
+ },
+ "mapping": {
+ "title": "Move issues into {{name}}",
+ "description": "These statuses aren't in the workflow. Choose where their issues go; issues on other statuses stay put.",
+ "issues_one": "{{count}} issue",
+ "issues_other": "{{count}} issues",
+ "no_handoff": "Moving issues this way doesn't hand them off or start runs.",
+ "confirm": "Move and switch",
+ "confirm_save": "Move and save",
+ "cancel": "Cancel",
+ "switch_title": "Switch “{{project}}” to “{{workflow}}”?",
+ "switch_description_one": "{{project}} has {{count}} issue. Only issues on statuses “{{workflow}}” doesn’t have need a new status.",
+ "switch_description_other": "{{project}} has {{count}} issues. Only issues on statuses “{{workflow}}” doesn’t have need a new status.",
+ "needs_mapping_one": "Needs a new status · {{count}} issue",
+ "needs_mapping_other": "Needs a new status · {{count}} issues",
+ "unchanged_one": "The other {{count}} issue ({{statuses}}) keeps its status — both workflows have it.",
+ "unchanged_other": "The other {{count}} issues ({{statuses}}) keep their status — both workflows have it.",
+ "switch_note": "Switching is an admin change: it hands nothing off, starts no agents, and keeps assignees. Saved views and filters work by status and aren’t affected.",
+ "confirm_count_one": "Switch and update {{count}} issue",
+ "confirm_count_other": "Switch and update {{count}} issues",
+ "confirm_plain": "Switch",
+ "edit_title": "Save “{{workflow}}”?",
+ "edit_description": "Some issues in projects using this workflow are on statuses you removed. Choose where they go; everything else stays.",
+ "confirm_save_count_one": "Save and update {{count}} issue",
+ "confirm_save_count_other": "Save and update {{count}} issues",
+ "switched_one": "“{{project}}” now uses “{{workflow}}”; {{count}} issue updated",
+ "switched_other": "“{{project}}” now uses “{{workflow}}”; {{count}} issues updated",
+ "nothing_moves": "Every issue’s status is in both workflows, so nothing moves."
+ },
+ "project": {
+ "label": "Workflow",
+ "switched": "Workflow changed",
+ "error": "Couldn't change the workflow",
+ "picker_title": "Choose a workflow",
+ "default_badge": "Default",
+ "used_by_short": "Used by: {{names}}",
+ "used_by_nobody": "No projects yet",
+ "manage": "Manage workflows…",
+ "picker_more": "Create more workflows in Settings → Workflows."
+ },
+ "picker": {
+ "header": "{{workflow}} · from project “{{project}}”",
+ "footer": "Only this issue’s workflow statuses are shown. The right side is who entering the status hands it to."
+ },
+ "confirm": {
+ "title": "Move {{issue}} to “{{status}}”?",
+ "reassign_run": "The assignee changes from {{from}} to {{to}}, who starts working right away.",
+ "reassign": "The assignee changes from {{from}} to {{to}}.",
+ "same_handler_run": "{{to}} stays the assignee and starts on this step.",
+ "unassigned": "Unassigned",
+ "running_title": "{{name}} is still running (for {{duration}})",
+ "stop_label": "Stop {{name}}’s run",
+ "stop_hint": "Code and comments it already produced stay. If you don’t stop it, two agents work on this issue at once.",
+ "queued_title": "{{name}}’s run is still queued",
+ "cancel_queued_label": "Cancel {{name}}’s queued run",
+ "queued_hint": "If you don’t cancel it, {{name}} still starts on this issue later.",
+ "brief_toggle": "What {{name}} receives",
+ "confirm": "Move to {{status}}",
+ "cancel": "Cancel",
+ "minutes_one": "{{count}} minute",
+ "minutes_other": "{{count}} minutes",
+ "hours_one": "{{count}} hour",
+ "hours_other": "{{count}} hours",
+ "under_minute": "under a minute",
+ "error": "Couldn’t move the issue",
+ "project_title": "Move {{issue}} to {{project}}?",
+ "project_confirm": "Move to {{project}}"
+ },
+ "board": {
+ "drop_hint_run": "Drop to hand to {{name}} and start the run",
+ "drop_hint": "Drop to hand to {{name}}"
+ },
+ "timeline": {
+ "handed_to": "Handed to",
+ "run_started": "and started a run ·",
+ "member_no_run": "(member, no run)",
+ "show_brief": "View handoff brief",
+ "hide_brief": "Hide handoff brief",
+ "brief_header": "The workflow brief this run received"
+ },
+ "detail": {
+ "follows_project": "(from project)",
+ "card_title": "{{workflow}} · from {{project}}",
+ "card_hint": "The project’s workflow decides these columns and handoffs."
+ },
+ "list_separator": ", ",
+ "handoff": {
+ "add": "Hand to…",
+ "title": "When an issue enters “{{status}}”",
+ "next_default": "Next column ({{status}})",
+ "saved": "Handoff saved",
+ "error": "Couldn't save the handoff",
+ "read_only": "Handoffs belong to the workflow; workspace admins change them.",
+ "to": "Hand to",
+ "members": "Members",
+ "mode_none": "No handoff",
+ "mode_none_hint": "The assignee stays the same",
+ "mode_agent": "Hand to an agent",
+ "mode_agent_hint": "Starts a run right away",
+ "mode_member": "Hand to a member",
+ "mode_member_hint": "Changes the assignee; nothing runs",
+ "project_lead_hint": "If the project lead is an agent, it starts a run.",
+ "pick_agent": "Choose an agent",
+ "pick_member": "Choose a member",
+ "search_agents": "Search agents",
+ "search_members": "Search members",
+ "instructions": "What this step does",
+ "scope_line": "Part of the {{workflow}} workflow",
+ "scope_line_shared": "Part of {{workflow}}, also used by {{projects}}",
+ "scope_more": "{{names}} and {{count}} more",
+ "scope_question": "Where should this change apply?",
+ "scope_all": "All {{count}} projects using {{workflow}}",
+ "scope_all_hint": "{{projects}} all use the new handoff",
+ "scope_project": "Only {{project}}",
+ "scope_project_hint": "Copies the workflow as “{{copy}}” for {{project}}; other projects stay as they are",
+ "saved_copy": "Saved to “{{workflow}}”, used only by {{project}}"
+ },
+ "columns": {
+ "new_status": "New status…",
+ "name_placeholder": "Status name",
+ "add": "Add"
+ },
+ "menu": {
+ "view_flow": "View full flow",
+ "switch": "Switch workflow"
+ },
+ "flow": {
+ "title": "{{workflow}} workflow",
+ "scope_own": "Only this project uses this workflow.",
+ "no_handoff_here": "No handoff",
+ "scope_shared_one": "{{count}} project uses this workflow. Its handoffs apply to every project using it.",
+ "scope_shared_other": "{{count}} projects use this workflow. Its handoffs apply to all of them."
+ },
+ "templates": {
+ "delivery": {
+ "name": "Delivery",
+ "summary": "Build, review, then QA before done",
+ "statuses": {
+ "qa": "QA"
+ }
+ },
+ "content": {
+ "name": "Content",
+ "summary": "Draft, edit and schedule",
+ "statuses": {
+ "drafting": "Drafting",
+ "editing": "Editing",
+ "scheduled": "Scheduled"
+ }
+ },
+ "community": {
+ "name": "Community",
+ "summary": "Triage, reply, wait on the reporter",
+ "statuses": {
+ "triage": "Triage",
+ "replying": "Replying",
+ "waiting": "Waiting on reporter"
+ }
+ }
+ }
}
}
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 4e37ee3db2..d1ae1f277d 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -79,7 +79,11 @@
"cancelled": "Decided not to do."
},
"pr_auto_complete_badge": "Set when PRs merge",
- "built_in_locked": "Built-in statuses drive system behavior, so they can't be edited or archived. You can still reorder them."
+ "built_in_locked": "Built-in statuses drive system behavior, so they can't be edited or archived. You can still reorder them.",
+ "builtin_badge": "Built-in",
+ "workflow_usage_one": "{{count}} workflow uses it",
+ "workflow_usage_other": "{{count}} workflows use it",
+ "workflow_usage_none": "In no workflow"
},
"wakeups": {
"description": "Platform rules that apply to every issue. Each issue can change them in its Wakeups section.",
@@ -405,7 +409,8 @@
"billing": "Billing",
"code": "Code",
"channels": "Messaging",
- "apps": "Connected apps"
+ "apps": "Connected apps",
+ "workflows": "Workflows"
},
"groups": {
"personal": "Personal",
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index b454515d97..d9509196f0 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -371,7 +371,10 @@
"empty_grouping": "Aucune tâche correspondante",
"no_value": "Aucune valeur",
"ordered_by": "Tableau trié par {{field}}",
- "manual_reorder_hint": "Passez au tri Manuel pour réorganiser les tâches dans une colonne."
+ "manual_reorder_hint": "Passez au tri Manuel pour réorganiser les tâches dans une colonne.",
+ "filter_to_status": "Filtrer sur cet état",
+ "outside_workflow": "Hors du workflow de ce tableau",
+ "workflow_columns_note": "Les colonnes viennent du workflow du tableau ; hors projet, les vues utilisent Default."
},
"peek": {
"panel_label": "Aperçu de la tâche",
@@ -848,6 +851,8 @@
"update_success_one": "{{count}} tâche mise à jour",
"update_success_other": "{{count}} tâches mises à jour",
"update_failed": "Échec de la mise à jour des tâches",
+ "update_partial_one": "{{updated}} tâche sur {{count}} mise à jour. Les autres n'acceptent pas cette modification et n'ont pas changé.",
+ "update_partial_other": "{{updated}} tâches sur {{count}} mises à jour. Les autres n'acceptent pas cette modification et n'ont pas changé.",
"delete_success_one": "{{count}} tâche supprimée",
"delete_success_other": "{{count}} tâches supprimées",
"delete_failed": "Échec de la suppression des tâches",
@@ -1474,5 +1479,274 @@
"overview_close": "Fermer",
"overview_empty": "Aucun livrable de ce type.",
"group_comment_by": "Commentaire de {{name}}"
+ },
+ "workflows": {
+ "default_name": "Default",
+ "default_summary": "Tous les états, sans passage de relais",
+ "hands_off_to": "Confiée à {{name}}",
+ "not_in_workflow": "Absent du workflow {{name}}",
+ "drop_blocked": "{{status}} ne fait pas partie du workflow {{name}}",
+ "create_handoff_hint": "Sera confiée à {{name}}",
+ "handler": {
+ "none": "Garder l’assigné",
+ "agent": "Agent",
+ "squad": "Squad",
+ "member": "Membre",
+ "project_lead": "Responsable du projet",
+ "creator": "Créateur de la tâche",
+ "project_lead_named": "{{name}} (responsable du projet)"
+ },
+ "settings": {
+ "title": "Workflows",
+ "new": "Nouveau workflow",
+ "projects_one": "{{count}} projet",
+ "projects_other": "{{count}} projets",
+ "default_projects": "Projets sans workflow",
+ "no_projects": "Pas encore utilisé",
+ "edit": "Modifier",
+ "delete": "Supprimer",
+ "delete_title": "Supprimer {{name}} ?",
+ "delete_description": "Les tâches conservent leur état.",
+ "delete_in_use": "Passez d’abord ses projets à un autre workflow.",
+ "deleted": "Workflow supprimé",
+ "delete_error": "Impossible de supprimer le workflow",
+ "statuses_title": "Bibliothèque d’états",
+ "statuses_one": "{{count}} état",
+ "statuses_other": "{{count}} états",
+ "handoffs_one": "{{count}} étape de passage",
+ "handoffs_other": "{{count}} étapes de passage",
+ "no_handoffs": "Sans passage de relais",
+ "used_by_one": "Utilisé par {{count}} projet : {{names}}",
+ "used_by_other": "Utilisé par {{count}} projets : {{names}}",
+ "used_by_default_one": "Utilisé par {{count}} projet : {{names}}, et les tâches sans projet",
+ "used_by_default_other": "Utilisé par {{count}} projets : {{names}}, et les tâches sans projet",
+ "used_by_default_none": "Utilisé par les tâches sans projet",
+ "new_blank": "Workflow vide",
+ "from_template": "À partir d’un modèle"
+ },
+ "editor": {
+ "create_title": "Nouveau workflow",
+ "edit_title": "Modifier le workflow",
+ "name": "Nom",
+ "name_placeholder": "ex. Livraison",
+ "description": "Description",
+ "steps": "Étapes",
+ "add_step": "Ajouter une étape",
+ "start": "Début",
+ "set_start": "Définir comme étape de départ",
+ "move_up": "Monter",
+ "move_down": "Descendre",
+ "remove": "Retirer la colonne",
+ "on_enter": "À l’entrée, confier à",
+ "choose_target": "Choisir…",
+ "instructions": "Instructions de passage",
+ "instructions_placeholder": "Que doit-il se passer à cette étape ?",
+ "next": "Une fois terminé, passer à",
+ "back": "Si des changements sont nécessaires, revenir à",
+ "none_option": "Non défini",
+ "save": "Enregistrer",
+ "create": "Créer",
+ "cancel": "Annuler",
+ "saved": "Workflow enregistré",
+ "created": "Workflow créé",
+ "error": "Impossible d’enregistrer le workflow",
+ "used_by_note_one": "Utilisé par {{count}} projet : {{names}}. Les modifications enregistrées s’appliquent aussitôt.",
+ "used_by_note_other": "Utilisé par {{count}} projets : {{names}}. Les modifications enregistrées s’appliquent aussitôt.",
+ "unused_note": "Aucun projet ne l’utilise encore. Choisissez-le dans les propriétés d’un projet.",
+ "duplicate": "Dupliquer en nouveau workflow",
+ "copy_name": "Copie de {{name}}",
+ "more": "Plus d’actions",
+ "steps_hint": "Faites glisser pour réordonner les colonnes du milieu. Backlog et Blocked sont facultatives. Un nouveau statut est créé à l’enregistrement.",
+ "reorder": "Réordonner {{name}}",
+ "card_hand_to": "Confier à",
+ "card_then": "puis → {{status}}",
+ "status": "État",
+ "status_hint": "Les états viennent de la bibliothèque. Renommez-les ou changez leur couleur là-bas ; tous les workflows qui les utilisent suivent.",
+ "handler_hint_on": "Quand une tâche entre dans cette étape, son assigné devient ce responsable ; un agent ou un squad commence aussitôt.",
+ "handler_hint_off": "Entrer dans cette étape garde l’assigné et ne lance aucune exécution.",
+ "handler_hint_lead": "Résolu par projet : le responsable de chaque projet.",
+ "handler_hint_creator": "Résolu par tâche : la personne qui l’a créée.",
+ "target_agent": "Agent",
+ "target_squad": "Squad · le leader répartit",
+ "target_member": "Membre",
+ "instructions_hint": "Envoyées au responsable avec cette exécution, avec la description et les commentaires de la tâche.",
+ "next_hint": "Inscrit dans les consignes du responsable pour qu’il sache quel état vient ensuite. Le système n’avance jamais l’état à la fin d’une exécution.",
+ "preview_brief": "Aperçu des consignes de l’agent",
+ "preview_title": "Consignes de l’étape « {{status}} »",
+ "preview_description": "Ce que reçoit l’exécution du responsable quand une tâche entre dans cette étape. Pas besoin d’enregistrer pour prévisualiser.",
+ "description_placeholder": "Ajouter une description",
+ "select_step": "Sélectionnez une colonne pour choisir à qui elle transmet les tickets.",
+ "unsaved": "Modifications non enregistrées",
+ "not_found": "Ce workflow n’existe plus.",
+ "default_note": "Default est le tableau de tout projet sans workflow choisi, et des vues hors projet.",
+ "new_badge": "Nouveau",
+ "columns": "Colonnes",
+ "include_status": "Inclure {{status}}",
+ "step_off_short": "Désactivé",
+ "step_off": "Désactivé : ce workflow n’utilise pas ce statut. Activez-le dans la liste des étapes pour l’utiliser.",
+ "status_new_hint": "Nouveau statut. Il sera ajouté à la bibliothèque de statuts à l’enregistrement.",
+ "no_other_status": "Tous les statuts sont déjà des étapes.",
+ "no_handoff_step": "Cette étape ne relaie pas : le responsable ne change pas et aucune exécution ne démarre.",
+ "new_step_handoff": "Enregistrez d’abord le workflow ; le nouveau statut pourra relayer ensuite."
+ },
+ "mapping": {
+ "title": "Déplacer les tâches vers {{name}}",
+ "description": "Ces états ne font pas partie du workflow. Choisissez où vont leurs tâches ; les autres ne bougent pas.",
+ "issues_one": "{{count}} tâche",
+ "issues_other": "{{count}} tâches",
+ "no_handoff": "Ce déplacement ne confie pas les tâches et ne lance aucune exécution.",
+ "confirm": "Déplacer et changer",
+ "confirm_save": "Déplacer et enregistrer",
+ "cancel": "Annuler",
+ "switch_title": "Passer « {{project}} » à « {{workflow}} » ?",
+ "switch_description_one": "{{project}} compte {{count}} tâche. Seules les tâches dont l’état n’existe pas dans « {{workflow}} » doivent changer d’état.",
+ "switch_description_other": "{{project}} compte {{count}} tâches. Seules les tâches dont l’état n’existe pas dans « {{workflow}} » doivent changer d’état.",
+ "needs_mapping_one": "Nouvel état requis · {{count}} tâche",
+ "needs_mapping_other": "Nouvel état requis · {{count}} tâches",
+ "unchanged_one": "L’autre tâche ({{statuses}}) garde son état : les deux workflows l’ont.",
+ "unchanged_other": "Les {{count}} autres tâches ({{statuses}}) gardent leur état : les deux workflows l’ont.",
+ "switch_note": "Changer de workflow est une opération d’administration : aucun passage de relais, aucun agent lancé, les assignés restent. Les vues et filtres enregistrés fonctionnent par état et ne changent pas.",
+ "confirm_count_one": "Changer et mettre à jour {{count}} tâche",
+ "confirm_count_other": "Changer et mettre à jour {{count}} tâches",
+ "confirm_plain": "Changer",
+ "edit_title": "Enregistrer « {{workflow}} » ?",
+ "edit_description": "Des tâches des projets qui utilisent ce workflow sont sur des états retirés. Choisissez où elles vont ; le reste ne bouge pas.",
+ "confirm_save_count_one": "Enregistrer et mettre à jour {{count}} tâche",
+ "confirm_save_count_other": "Enregistrer et mettre à jour {{count}} tâches",
+ "switched_one": "« {{project}} » utilise désormais « {{workflow}} » ; {{count}} tâche mise à jour",
+ "switched_other": "« {{project}} » utilise désormais « {{workflow}} » ; {{count}} tâches mises à jour",
+ "nothing_moves": "Chaque tâche a un état présent dans les deux workflows : rien ne bouge."
+ },
+ "project": {
+ "label": "Workflow",
+ "switched": "Workflow modifié",
+ "error": "Impossible de changer le workflow",
+ "picker_title": "Choisir un workflow",
+ "default_badge": "Par défaut",
+ "used_by_short": "Utilisé par : {{names}}",
+ "used_by_nobody": "Aucun projet pour l’instant",
+ "manage": "Gérer les workflows…",
+ "picker_more": "Créez d’autres workflows dans Paramètres → Workflows."
+ },
+ "picker": {
+ "header": "{{workflow}} · selon le projet « {{project}} »",
+ "footer": "Seuls les états du workflow de cette tâche sont affichés. À droite : à qui elle est confiée en entrant dans l’état."
+ },
+ "confirm": {
+ "title": "Déplacer {{issue}} vers « {{status}} » ?",
+ "reassign_run": "L’assigné passe de {{from}} à {{to}}, qui commence aussitôt.",
+ "reassign": "L’assigné passe de {{from}} à {{to}}.",
+ "same_handler_run": "{{to}} reste assigné et commence cette étape.",
+ "unassigned": "Non assigné",
+ "running_title": "{{name}} est encore en cours (depuis {{duration}})",
+ "stop_label": "Arrêter l’exécution de {{name}}",
+ "stop_hint": "Le code et les commentaires déjà produits restent. Sans arrêt, deux agents travaillent sur cette tâche en même temps.",
+ "queued_title": "L’exécution de {{name}} est encore en file d’attente",
+ "cancel_queued_label": "Annuler l’exécution en attente de {{name}}",
+ "queued_hint": "Sans annulation, {{name}} commencera quand même cette tâche plus tard.",
+ "brief_toggle": "Ce que reçoit {{name}}",
+ "confirm": "Déplacer vers {{status}}",
+ "cancel": "Annuler",
+ "minutes_one": "{{count}} minute",
+ "minutes_other": "{{count}} minutes",
+ "hours_one": "{{count}} heure",
+ "hours_other": "{{count}} heures",
+ "under_minute": "moins d’une minute",
+ "error": "Impossible de déplacer la tâche",
+ "project_title": "Déplacer {{issue}} vers {{project}} ?",
+ "project_confirm": "Déplacer vers {{project}}"
+ },
+ "board": {
+ "drop_hint_run": "Déposer pour confier à {{name}} et lancer l’exécution",
+ "drop_hint": "Déposer pour confier à {{name}}"
+ },
+ "timeline": {
+ "handed_to": "Confiée à",
+ "run_started": "exécution lancée ·",
+ "member_no_run": "(membre, sans exécution)",
+ "show_brief": "Voir les consignes",
+ "hide_brief": "Masquer les consignes",
+ "brief_header": "Les consignes de workflow reçues par cette exécution"
+ },
+ "detail": {
+ "follows_project": "(selon le projet)",
+ "card_title": "{{workflow}} · selon {{project}}",
+ "card_hint": "Le workflow du projet décide de ces colonnes et transferts."
+ },
+ "list_separator": ", ",
+ "handoff": {
+ "add": "Confier à…",
+ "title": "Quand une tâche entre dans « {{status}} »",
+ "next_default": "Colonne suivante ({{status}})",
+ "saved": "Passage de relais enregistré",
+ "error": "Impossible d’enregistrer le passage de relais",
+ "read_only": "Les transferts appartiennent au workflow ; les administrateurs de l’espace les modifient.",
+ "to": "Confier à",
+ "members": "Membres",
+ "mode_none": "Pas de relais",
+ "mode_none_hint": "L’assigné reste le même",
+ "mode_agent": "Confier à un agent",
+ "mode_agent_hint": "Démarre une exécution aussitôt",
+ "mode_member": "Confier à un membre",
+ "mode_member_hint": "Change l’assigné ; rien ne s’exécute",
+ "project_lead_hint": "Si le responsable du projet est un agent, il démarre une exécution.",
+ "pick_agent": "Choisir un agent",
+ "pick_member": "Choisir un membre",
+ "search_agents": "Rechercher des agents",
+ "search_members": "Rechercher des membres",
+ "instructions": "Ce que fait cette étape",
+ "scope_line": "Fait partie du workflow {{workflow}}",
+ "scope_line_shared": "Fait partie de {{workflow}}, aussi utilisé par {{projects}}",
+ "scope_more": "{{names}} et {{count}} autres",
+ "scope_question": "Où appliquer cette modification ?",
+ "scope_all": "Les {{count}} projets qui utilisent {{workflow}}",
+ "scope_all_hint": "{{projects}} suivent tous le nouveau relais",
+ "scope_project": "Seulement {{project}}",
+ "scope_project_hint": "Copie le workflow sous « {{copy}} » pour {{project}} ; les autres projets ne changent pas",
+ "saved_copy": "Enregistré dans « {{workflow}} », utilisé seulement par {{project}}"
+ },
+ "columns": {
+ "new_status": "Nouvel état…",
+ "name_placeholder": "Nom de l’état",
+ "add": "Ajouter"
+ },
+ "menu": {
+ "view_flow": "Voir tout le flux",
+ "switch": "Changer de workflow"
+ },
+ "flow": {
+ "title": "Workflow {{workflow}}",
+ "scope_own": "Seul ce projet utilise ce workflow.",
+ "no_handoff_here": "Pas de relais",
+ "scope_shared_one": "{{count}} projet utilise ce workflow. Ses transferts s’appliquent à chaque projet qui l’utilise.",
+ "scope_shared_other": "{{count}} projets utilisent ce workflow. Ses transferts s’appliquent à tous."
+ },
+ "templates": {
+ "delivery": {
+ "name": "Livraison",
+ "summary": "Développer, relire, puis QA avant la fin",
+ "statuses": {
+ "qa": "QA"
+ }
+ },
+ "content": {
+ "name": "Contenu",
+ "summary": "Rédiger, relire et planifier",
+ "statuses": {
+ "drafting": "Rédaction",
+ "editing": "Relecture",
+ "scheduled": "Planifié"
+ }
+ },
+ "community": {
+ "name": "Communauté",
+ "summary": "Trier, répondre, attendre le retour",
+ "statuses": {
+ "triage": "Tri",
+ "replying": "Réponse en cours",
+ "waiting": "En attente du retour"
+ }
+ }
+ }
}
}
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index 36764c3f27..a2d02db685 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -79,7 +79,11 @@
"cancelled": "Abandonné."
},
"pr_auto_complete_badge": "Définie à la fusion des PR",
- "built_in_locked": "Les états intégrés pilotent le comportement du système : ils ne peuvent être ni modifiés ni archivés, mais vous pouvez les réordonner."
+ "built_in_locked": "Les états intégrés pilotent le comportement du système : ils ne peuvent être ni modifiés ni archivés, mais vous pouvez les réordonner.",
+ "builtin_badge": "Intégré",
+ "workflow_usage_one": "{{count}} workflow l’utilise",
+ "workflow_usage_other": "{{count}} workflows l’utilisent",
+ "workflow_usage_none": "Dans aucun workflow"
},
"wakeups": {
"description": "Règles de la plateforme appliquées à chaque tâche. Chaque tâche peut les modifier dans sa section Réveils.",
@@ -405,7 +409,8 @@
"billing": "Facturation",
"code": "Code",
"channels": "Messagerie",
- "apps": "Applications connectées"
+ "apps": "Applications connectées",
+ "workflows": "Workflows"
},
"groups": {
"personal": "Personnel",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 274cf8c05d..6245ce4e46 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -367,7 +367,10 @@
"empty_grouping": "一致するタスクがありません",
"no_value": "値なし",
"ordered_by": "{{field}} 順に並べたボード",
- "manual_reorder_hint": "列内の順序を変更するには、並び順を「手動」に切り替えてください。"
+ "manual_reorder_hint": "列内の順序を変更するには、並び順を「手動」に切り替えてください。",
+ "filter_to_status": "このステータスで絞り込む",
+ "outside_workflow": "このボードのワークフローにはありません",
+ "workflow_columns_note": "ボードの列はワークフローで決まります。プロジェクト外のビューは Default を使います。"
},
"peek": {
"panel_label": "タスクのプレビュー",
@@ -811,6 +814,7 @@
"delete": "削除",
"update_success_other": "タスク {{count}} 件を更新しました",
"update_failed": "タスクを更新できませんでした",
+ "update_partial_other": "{{count}} 件中 {{updated}} 件のタスクを更新しました。残りはこの変更に対応していないため、そのままです。",
"delete_success_other": "タスク {{count}} 件を削除しました",
"delete_failed": "タスクを削除できませんでした",
"delete_dialog_title_other": "タスク {{count}} 件を削除しますか?",
@@ -1426,5 +1430,258 @@
"overview_close": "閉じる",
"overview_empty": "この種類の成果物はありません。",
"group_comment_by": "{{name}} のコメント"
+ },
+ "workflows": {
+ "default_name": "Default",
+ "default_summary": "すべてのステータス、引き継ぎなし",
+ "hands_off_to": "{{name}} に引き継ぐ",
+ "not_in_workflow": "「{{name}}」にこのステータスはありません",
+ "drop_blocked": "「{{status}}」はワークフロー「{{name}}」に含まれていません",
+ "create_handoff_hint": "作成後に {{name}} に引き継ぎます",
+ "handler": {
+ "none": "担当者を変更しない",
+ "agent": "エージェント",
+ "squad": "スクワッド",
+ "member": "メンバー",
+ "project_lead": "プロジェクトリード",
+ "creator": "タスク作成者",
+ "project_lead_named": "{{name}}(プロジェクトリード)"
+ },
+ "settings": {
+ "title": "ワークフロー",
+ "new": "新規ワークフロー",
+ "projects_other": "{{count}} 件のプロジェクト",
+ "default_projects": "ワークフロー未設定のプロジェクト",
+ "no_projects": "未使用",
+ "edit": "編集",
+ "delete": "削除",
+ "delete_title": "「{{name}}」を削除しますか?",
+ "delete_description": "タスクのステータスはそのまま残ります。",
+ "delete_in_use": "先に、使用中のプロジェクトを別のワークフローに切り替えてください。",
+ "deleted": "ワークフローを削除しました",
+ "delete_error": "ワークフローを削除できませんでした",
+ "statuses_title": "ステータスライブラリ",
+ "statuses_other": "ステータス {{count}} 件",
+ "handoffs_other": "自動引き継ぎ {{count}} ステップ",
+ "no_handoffs": "自動引き継ぎなし",
+ "used_by_other": "{{count}} 件のプロジェクトで使用中:{{names}}",
+ "used_by_default_other": "{{count}} 件のプロジェクト({{names}})とプロジェクトのないタスクで使用中",
+ "used_by_default_none": "プロジェクトのないタスクで使用中",
+ "new_blank": "空のワークフロー",
+ "from_template": "テンプレートから"
+ },
+ "editor": {
+ "create_title": "新規ワークフロー",
+ "edit_title": "ワークフローを編集",
+ "name": "名前",
+ "name_placeholder": "例:開発フロー",
+ "description": "説明",
+ "steps": "ステップ",
+ "add_step": "ステップを追加",
+ "start": "開始",
+ "set_start": "開始ステップにする",
+ "move_up": "上へ移動",
+ "move_down": "下へ移動",
+ "remove": "列を削除",
+ "on_enter": "このステップに入ったら引き継ぐ相手",
+ "choose_target": "選択…",
+ "instructions": "引き継ぎの指示",
+ "instructions_placeholder": "このステップで何をしますか?",
+ "next": "完了したら移動",
+ "back": "修正が必要なら戻す先",
+ "none_option": "指定しない",
+ "save": "保存",
+ "create": "作成",
+ "cancel": "キャンセル",
+ "saved": "ワークフローを保存しました",
+ "created": "ワークフローを作成しました",
+ "error": "ワークフローを保存できませんでした",
+ "used_by_note_other": "{{count}} 件のプロジェクトで使用中:{{names}}。保存するとすぐに反映されます。",
+ "unused_note": "まだどのプロジェクトも使っていません。プロジェクトのプロパティで選べます。",
+ "duplicate": "新しいワークフローとして複製",
+ "copy_name": "{{name}} のコピー",
+ "more": "その他の操作",
+ "steps_hint": "ドラッグで中間の列を並べ替えます。Backlog と Blocked は任意です。新しいステータスは保存時に作成されます。",
+ "reorder": "「{{name}}」を並べ替え",
+ "card_hand_to": "引き継ぎ先",
+ "card_then": "完了後 → {{status}}",
+ "status": "ステータス",
+ "status_hint": "ステータスはライブラリから来ます。名前や色はライブラリで変更すると、使用中のすべてのワークフローに反映されます。",
+ "handler_hint_on": "タスクがこのステップに入ると、担当者がここの処理者に変わります。エージェントやスクワッドならすぐに実行を始めます。",
+ "handler_hint_off": "このステップに入っても担当者は変わらず、実行も始まりません。",
+ "handler_hint_lead": "プロジェクトごとに解決:各プロジェクトのリード。",
+ "handler_hint_creator": "タスクごとに解決:作成した人。",
+ "target_agent": "エージェント",
+ "target_squad": "スクワッド · リーダーが割り振り",
+ "target_member": "メンバー",
+ "instructions_hint": "今回の実行の指示として処理者に送られ、タスクの説明やコメントと一緒にコンテキストになります。",
+ "next_hint": "処理者が受け取る説明に書き込まれ、次にどのステータスへ変えるかを伝えます。実行が終わってもシステムはステータスを自動で進めません。",
+ "preview_brief": "エージェントが受け取る説明をプレビュー",
+ "preview_title": "「{{status}}」ステップの説明",
+ "preview_description": "タスクがこのステップに入ったとき、処理者の実行が受け取る内容です。プレビューに保存は不要です。",
+ "description_placeholder": "説明を追加",
+ "select_step": "列を選択して、課題の引き継ぎ先を設定します。",
+ "unsaved": "未保存の変更があります",
+ "not_found": "このワークフローはもう存在しません。",
+ "default_note": "Default は、ワークフローを選んでいないプロジェクトと、プロジェクト外のビューで使うボードです。",
+ "new_badge": "新規",
+ "columns": "列",
+ "include_status": "{{status}} を含める",
+ "step_off_short": "オフ",
+ "step_off": "オフ:このワークフローはこのステータスを使いません。左のリストでオンにすると使えます。",
+ "status_new_hint": "新しいステータスです。保存時にステータスライブラリに追加されます。",
+ "no_other_status": "すべてのステータスがすでにステップです。",
+ "no_handoff_step": "このステップは引き継ぎません。入っても担当者は変わらず、実行も始まりません。",
+ "new_step_handoff": "先にワークフローを保存してください。保存後に新しいステータスの引き継ぎを設定できます。"
+ },
+ "mapping": {
+ "title": "タスクを「{{name}}」に移動",
+ "description": "以下のステータスはワークフローに含まれていません。これらのタスクの移動先を選んでください。ほかのタスクはそのままです。",
+ "issues_other": "タスク {{count}} 件",
+ "no_handoff": "この移動では引き継ぎも実行の開始も行われません。",
+ "confirm": "移動して切り替える",
+ "confirm_save": "移動して保存",
+ "cancel": "キャンセル",
+ "switch_title": "「{{project}}」を「{{workflow}}」に切り替えますか?",
+ "switch_description_other": "{{project}} にはタスクが {{count}} 件あります。「{{workflow}}」にないステータスのタスクだけ、新しいステータスを選ぶ必要があります。",
+ "needs_mapping_other": "新しいステータスが必要 · {{count}} 件",
+ "unchanged_other": "残りの {{count}} 件({{statuses}})は両方のワークフローにあるステータスなので、そのままです。",
+ "switch_note": "切り替えは管理操作です。引き継ぎもエージェントの起動も行わず、担当者も変わりません。保存済みビューとフィルターはステータスで動くので影響を受けません。",
+ "confirm_count_other": "切り替えて {{count}} 件を更新",
+ "confirm_plain": "切り替える",
+ "edit_title": "「{{workflow}}」を保存しますか?",
+ "edit_description": "このワークフローを使うプロジェクトに、削除したステータスのタスクがあります。移動先を選んでください。ほかのタスクはそのままです。",
+ "confirm_save_count_other": "保存して {{count}} 件を更新",
+ "switched_other": "「{{project}}」を「{{workflow}}」に切り替え、{{count}} 件を更新しました",
+ "nothing_moves": "すべてのタスクのステータスが両方のワークフローにあるため、何も移動しません。"
+ },
+ "project": {
+ "label": "ワークフロー",
+ "switched": "ワークフローを変更しました",
+ "error": "ワークフローを変更できませんでした",
+ "picker_title": "ワークフローを選択",
+ "default_badge": "デフォルト",
+ "used_by_short": "使用中:{{names}}",
+ "used_by_nobody": "まだプロジェクトがありません",
+ "manage": "ワークフローを管理…",
+ "picker_more": "「設定 → ワークフロー」でワークフローを追加できます。"
+ },
+ "picker": {
+ "header": "{{workflow}} · プロジェクト「{{project}}」に従う",
+ "footer": "このタスクのワークフローのステータスだけを表示しています。右側はそのステータスに入ったときの引き継ぎ先です。"
+ },
+ "confirm": {
+ "title": "{{issue}} を「{{status}}」に移動しますか?",
+ "reassign_run": "担当者が {{from}} から {{to}} に変わり、すぐに実行を始めます。",
+ "reassign": "担当者が {{from}} から {{to}} に変わります。",
+ "same_handler_run": "担当者は {{to}} のままで、このステップの実行を始めます。",
+ "unassigned": "未割り当て",
+ "running_title": "{{name}} はまだ実行中です({{duration}} 経過)",
+ "stop_label": "{{name}} の実行を停止",
+ "stop_hint": "すでに提出したコードやコメントは残ります。停止しない場合、2 つのエージェントが同時にこのタスクを処理します。",
+ "queued_title": "{{name}} の実行はまだ待機中です",
+ "cancel_queued_label": "{{name}} の待機中の実行をキャンセル",
+ "queued_hint": "キャンセルしない場合、{{name}} は後でこのタスクの処理を始めます。",
+ "brief_toggle": "{{name}} が受け取る説明",
+ "confirm": "{{status}}に移動",
+ "cancel": "キャンセル",
+ "minutes_other": "{{count}} 分",
+ "hours_other": "{{count}} 時間",
+ "under_minute": "1 分未満",
+ "error": "タスクを移動できませんでした",
+ "project_title": "{{issue}} を「{{project}}」に移動しますか?",
+ "project_confirm": "{{project}} に移動"
+ },
+ "board": {
+ "drop_hint_run": "ドロップすると {{name}} に引き継いで実行を開始",
+ "drop_hint": "ドロップすると {{name}} に引き継ぎ"
+ },
+ "timeline": {
+ "handed_to": "引き継ぎ先",
+ "run_started": "実行を開始 ·",
+ "member_no_run": "(メンバー、実行なし)",
+ "show_brief": "引き継ぎの説明を見る",
+ "hide_brief": "引き継ぎの説明を閉じる",
+ "brief_header": "この実行が受け取ったワークフローの説明"
+ },
+ "detail": {
+ "follows_project": "(プロジェクトに従う)",
+ "card_title": "「{{workflow}}」· プロジェクト「{{project}}」に従う",
+ "card_hint": "これらの列と引き継ぎはプロジェクトのワークフローで決まります。"
+ },
+ "list_separator": "、",
+ "handoff": {
+ "add": "引き継ぐ…",
+ "title": "タスクが「{{status}}」に入ったとき",
+ "next_default": "次の列({{status}})",
+ "saved": "引き継ぎを保存しました",
+ "error": "引き継ぎを保存できませんでした",
+ "read_only": "引き継ぎはワークフローに属し、ワークスペース管理者が変更します。",
+ "to": "引き継ぎ先",
+ "members": "メンバー",
+ "mode_none": "引き継がない",
+ "mode_none_hint": "担当者はそのまま",
+ "mode_agent": "エージェントに渡す",
+ "mode_agent_hint": "すぐに実行を始めます",
+ "mode_member": "メンバーに渡す",
+ "mode_member_hint": "担当者だけが変わり、自動では実行されません",
+ "project_lead_hint": "プロジェクトリードがエージェントの場合は実行を始めます。",
+ "pick_agent": "エージェントを選択",
+ "pick_member": "メンバーを選択",
+ "search_agents": "エージェントを検索",
+ "search_members": "メンバーを検索",
+ "instructions": "このステップでやること",
+ "scope_line": "「{{workflow}}」ワークフローの一部",
+ "scope_line_shared": "「{{workflow}}」の一部。{{projects}} でも使用中",
+ "scope_more": "{{names}} ほか {{count}} 件",
+ "scope_question": "この変更をどこに適用しますか?",
+ "scope_all": "「{{workflow}}」を使う {{count}} 件のプロジェクト",
+ "scope_all_hint": "{{projects}} すべてに新しい引き継ぎを適用",
+ "scope_project": "{{project}} のみ",
+ "scope_project_hint": "「{{copy}}」としてコピーし {{project}} で使用。他のプロジェクトは変わりません",
+ "saved_copy": "「{{workflow}}」に保存しました({{project}} のみ使用)"
+ },
+ "columns": {
+ "new_status": "新しいステータス…",
+ "name_placeholder": "ステータス名",
+ "add": "追加"
+ },
+ "menu": {
+ "view_flow": "フロー全体を見る",
+ "switch": "ワークフローを切り替え"
+ },
+ "flow": {
+ "title": "ワークフロー「{{workflow}}」",
+ "scope_own": "このワークフローを使用しているのはこのプロジェクトだけです。",
+ "no_handoff_here": "引き継ぎなし",
+ "scope_shared_other": "{{count}} 件のプロジェクトがこのワークフローを使用しています。引き継ぎはそのすべてに適用されます。"
+ },
+ "templates": {
+ "delivery": {
+ "name": "開発デリバリー",
+ "summary": "開発・レビューのあと QA を経て完了",
+ "statuses": {
+ "qa": "QA"
+ }
+ },
+ "content": {
+ "name": "コンテンツ制作",
+ "summary": "執筆・編集・公開予約",
+ "statuses": {
+ "drafting": "執筆中",
+ "editing": "編集中",
+ "scheduled": "公開予約済み"
+ }
+ },
+ "community": {
+ "name": "コミュニティ運営",
+ "summary": "振り分け・返信・返答待ち",
+ "statuses": {
+ "triage": "振り分け",
+ "replying": "返信中",
+ "waiting": "返答待ち"
+ }
+ }
+ }
}
}
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 26d33572c7..6c640daa62 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -79,7 +79,10 @@
"cancelled": "見送り。"
},
"pr_auto_complete_badge": "PR のマージで自動設定",
- "built_in_locked": "組み込みステータスはシステムの動作に使われるため、編集やアーカイブはできません。並び順は変更できます。"
+ "built_in_locked": "組み込みステータスはシステムの動作に使われるため、編集やアーカイブはできません。並び順は変更できます。",
+ "builtin_badge": "組み込み",
+ "workflow_usage_other": "{{count}} 件のワークフローで使用中",
+ "workflow_usage_none": "ワークフローで未使用"
},
"wakeups": {
"description": "すべてのタスクに適用されるプラットフォームのルールです。各タスクの「ウェイクアップ」セクションで個別に変更できます。",
@@ -404,7 +407,8 @@
"billing": "請求とプラン",
"code": "コード",
"channels": "メッセージング",
- "apps": "接続済みアプリ"
+ "apps": "接続済みアプリ",
+ "workflows": "ワークフロー"
},
"groups": {
"personal": "個人",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index f3a57965e4..afec7a7437 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -367,7 +367,10 @@
"empty_grouping": "일치하는 태스크가 없습니다",
"no_value": "값 없음",
"ordered_by": "{{field}} 기준으로 정렬된 보드",
- "manual_reorder_hint": "열 안의 순서를 바꾸려면 정렬을 '수동'으로 전환하세요."
+ "manual_reorder_hint": "열 안의 순서를 바꾸려면 정렬을 '수동'으로 전환하세요.",
+ "filter_to_status": "이 상태로 필터",
+ "outside_workflow": "이 보드의 워크플로에 없음",
+ "workflow_columns_note": "보드의 열은 워크플로가 정합니다. 프로젝트 밖의 보기는 Default를 사용합니다."
},
"peek": {
"panel_label": "태스크 미리보기",
@@ -811,6 +814,7 @@
"delete": "삭제",
"update_success_other": "태스크 {{count}}개를 업데이트했습니다",
"update_failed": "태스크를 업데이트하지 못했습니다",
+ "update_partial_other": "태스크 {{count}}개 중 {{updated}}개를 업데이트했습니다. 나머지는 이 변경을 적용할 수 없어 그대로 두었습니다.",
"delete_success_other": "태스크 {{count}}개를 삭제했습니다",
"delete_failed": "태스크를 삭제하지 못했습니다",
"delete_dialog_title_other": "태스크 {{count}}개를 삭제할까요?",
@@ -1426,5 +1430,258 @@
"overview_close": "닫기",
"overview_empty": "이 유형의 산출물이 없습니다.",
"group_comment_by": "{{name}}의 댓글"
+ },
+ "workflows": {
+ "default_name": "Default",
+ "default_summary": "모든 상태, 인계 없음",
+ "hands_off_to": "{{name}}에게 인계",
+ "not_in_workflow": "{{name}}에 이 상태가 없습니다",
+ "drop_blocked": "{{status}}은(는) {{name}} 워크플로에 없습니다",
+ "create_handoff_hint": "생성 후 {{name}}에게 인계됩니다",
+ "handler": {
+ "none": "담당자 유지",
+ "agent": "에이전트",
+ "squad": "스쿼드",
+ "member": "멤버",
+ "project_lead": "프로젝트 리드",
+ "creator": "태스크 작성자",
+ "project_lead_named": "{{name}} (프로젝트 리드)"
+ },
+ "settings": {
+ "title": "워크플로",
+ "new": "새 워크플로",
+ "projects_other": "프로젝트 {{count}}개",
+ "default_projects": "워크플로가 없는 프로젝트",
+ "no_projects": "아직 사용하지 않음",
+ "edit": "편집",
+ "delete": "삭제",
+ "delete_title": "{{name}}을(를) 삭제할까요?",
+ "delete_description": "태스크의 상태는 그대로 유지됩니다.",
+ "delete_in_use": "먼저 사용 중인 프로젝트를 다른 워크플로로 전환하세요.",
+ "deleted": "워크플로를 삭제했습니다",
+ "delete_error": "워크플로를 삭제하지 못했습니다",
+ "statuses_title": "상태 라이브러리",
+ "statuses_other": "상태 {{count}}개",
+ "handoffs_other": "자동 인계 {{count}}단계",
+ "no_handoffs": "자동 인계 없음",
+ "used_by_other": "프로젝트 {{count}}개에서 사용 중: {{names}}",
+ "used_by_default_other": "프로젝트 {{count}}개({{names}})와 프로젝트가 없는 태스크에서 사용 중",
+ "used_by_default_none": "프로젝트가 없는 태스크에서 사용 중",
+ "new_blank": "빈 워크플로",
+ "from_template": "템플릿으로"
+ },
+ "editor": {
+ "create_title": "새 워크플로",
+ "edit_title": "워크플로 편집",
+ "name": "이름",
+ "name_placeholder": "예: 개발 흐름",
+ "description": "설명",
+ "steps": "단계",
+ "add_step": "단계 추가",
+ "start": "시작",
+ "set_start": "시작 단계로 지정",
+ "move_up": "위로 이동",
+ "move_down": "아래로 이동",
+ "remove": "열 제거",
+ "on_enter": "진입 시 인계 대상",
+ "choose_target": "선택…",
+ "instructions": "인계 지침",
+ "instructions_placeholder": "이 단계에서 무엇을 해야 하나요?",
+ "next": "완료 후 이동",
+ "back": "수정이 필요하면 되돌릴 단계",
+ "none_option": "지정 안 함",
+ "save": "저장",
+ "create": "만들기",
+ "cancel": "취소",
+ "saved": "워크플로를 저장했습니다",
+ "created": "워크플로를 만들었습니다",
+ "error": "워크플로를 저장하지 못했습니다",
+ "used_by_note_other": "프로젝트 {{count}}개에서 사용 중: {{names}}. 저장하면 바로 적용됩니다.",
+ "unused_note": "아직 사용하는 프로젝트가 없습니다. 프로젝트 속성에서 선택하세요.",
+ "duplicate": "새 워크플로로 복제",
+ "copy_name": "{{name}} 사본",
+ "more": "더 보기",
+ "steps_hint": "드래그해 가운데 열의 순서를 바꿉니다. Backlog와 Blocked는 선택 사항입니다. 새 상태는 저장할 때 만들어집니다.",
+ "reorder": "{{name}} 순서 변경",
+ "card_hand_to": "인계 대상",
+ "card_then": "완료 후 → {{status}}",
+ "status": "상태",
+ "status_hint": "상태는 라이브러리에서 가져옵니다. 이름과 색은 라이브러리에서 바꾸면 이를 쓰는 모든 워크플로에 반영됩니다.",
+ "handler_hint_on": "태스크가 이 단계에 들어오면 담당자가 이 처리자로 바뀌며, 에이전트나 스쿼드라면 바로 실행을 시작합니다.",
+ "handler_hint_off": "이 단계에 들어와도 담당자는 그대로이며 실행도 시작되지 않습니다.",
+ "handler_hint_lead": "프로젝트별로 정해집니다: 각 프로젝트의 리드.",
+ "handler_hint_creator": "태스크별로 정해집니다: 태스크를 만든 사람.",
+ "target_agent": "에이전트",
+ "target_squad": "스쿼드 · 리더가 배분",
+ "target_member": "멤버",
+ "instructions_hint": "이번 실행의 지침으로 처리자에게 전달되며, 태스크 설명·댓글과 함께 맥락이 됩니다.",
+ "next_hint": "처리자가 받는 설명에 적혀 다음에 어떤 상태로 바꿀지 알려 줍니다. 실행이 끝나도 시스템이 상태를 자동으로 넘기지 않습니다.",
+ "preview_brief": "에이전트가 받는 설명 미리 보기",
+ "preview_title": "“{{status}}” 단계 설명",
+ "preview_description": "태스크가 이 단계에 들어오면 처리자의 실행이 받는 내용입니다. 미리 보기에는 저장이 필요 없습니다.",
+ "description_placeholder": "설명 추가",
+ "select_step": "열을 선택해 이슈를 누구에게 넘길지 설정하세요.",
+ "unsaved": "저장하지 않은 변경 사항",
+ "not_found": "이 워크플로는 더 이상 없습니다.",
+ "default_note": "Default는 워크플로를 고르지 않은 프로젝트와 프로젝트 밖 보기에서 쓰는 보드입니다.",
+ "new_badge": "새로 만듦",
+ "columns": "열",
+ "include_status": "{{status}} 포함",
+ "step_off_short": "꺼짐",
+ "step_off": "꺼짐: 이 워크플로는 이 상태를 쓰지 않습니다. 왼쪽 목록에서 켜면 사용할 수 있습니다.",
+ "status_new_hint": "새 상태입니다. 저장할 때 상태 라이브러리에 추가됩니다.",
+ "no_other_status": "모든 상태가 이미 단계입니다.",
+ "no_handoff_step": "이 단계는 인계하지 않습니다. 들어와도 담당자는 그대로이고 실행도 시작되지 않습니다.",
+ "new_step_handoff": "먼저 워크플로를 저장하세요. 저장한 뒤 새 상태의 인계를 설정할 수 있습니다."
+ },
+ "mapping": {
+ "title": "{{name}}(으)로 태스크 이동",
+ "description": "아래 상태는 워크플로에 없습니다. 해당 태스크를 옮길 상태를 고르세요. 다른 태스크는 그대로입니다.",
+ "issues_other": "태스크 {{count}}개",
+ "no_handoff": "이렇게 옮기면 인계되거나 실행이 시작되지 않습니다.",
+ "confirm": "이동 후 전환",
+ "confirm_save": "이동 후 저장",
+ "cancel": "취소",
+ "switch_title": "“{{project}}”을(를) “{{workflow}}”(으)로 전환할까요?",
+ "switch_description_other": "{{project}}에는 태스크가 {{count}}개 있습니다. “{{workflow}}”에 없는 상태의 태스크만 새 상태를 골라야 합니다.",
+ "needs_mapping_other": "새 상태 필요 · {{count}}개",
+ "unchanged_other": "나머지 {{count}}개({{statuses}})는 두 워크플로 모두에 있는 상태라 그대로 유지됩니다.",
+ "switch_note": "전환은 관리 작업입니다. 인계나 에이전트 실행이 일어나지 않고 담당자도 그대로입니다. 저장된 보기와 필터는 상태 기준이라 영향을 받지 않습니다.",
+ "confirm_count_other": "전환하고 {{count}}개 업데이트",
+ "confirm_plain": "전환",
+ "edit_title": "“{{workflow}}”을(를) 저장할까요?",
+ "edit_description": "이 워크플로를 쓰는 프로젝트에 제거한 상태의 태스크가 있습니다. 옮길 곳을 고르세요. 나머지는 그대로입니다.",
+ "confirm_save_count_other": "저장하고 {{count}}개 업데이트",
+ "switched_other": "“{{project}}”을(를) “{{workflow}}”(으)로 전환하고 {{count}}개를 업데이트했습니다",
+ "nothing_moves": "모든 태스크의 상태가 두 워크플로에 모두 있어 아무것도 옮기지 않습니다."
+ },
+ "project": {
+ "label": "워크플로",
+ "switched": "워크플로를 변경했습니다",
+ "error": "워크플로를 변경하지 못했습니다",
+ "picker_title": "워크플로 선택",
+ "default_badge": "기본",
+ "used_by_short": "사용 중: {{names}}",
+ "used_by_nobody": "아직 프로젝트 없음",
+ "manage": "워크플로 관리…",
+ "picker_more": "설정 → 워크플로에서 워크플로를 더 만들 수 있습니다."
+ },
+ "picker": {
+ "header": "{{workflow}} · 프로젝트 “{{project}}” 기준",
+ "footer": "이 태스크 워크플로의 상태만 표시합니다. 오른쪽은 해당 상태에 들어갈 때의 처리자입니다."
+ },
+ "confirm": {
+ "title": "{{issue}}을(를) “{{status}}”(으)로 옮길까요?",
+ "reassign_run": "담당자가 {{from}}에서 {{to}}(으)로 바뀌고 바로 실행을 시작합니다.",
+ "reassign": "담당자가 {{from}}에서 {{to}}(으)로 바뀝니다.",
+ "same_handler_run": "담당자는 {{to}} 그대로이며 이 단계를 시작합니다.",
+ "unassigned": "미할당",
+ "running_title": "{{name}}이(가) 아직 실행 중입니다({{duration}} 경과)",
+ "stop_label": "{{name}} 실행 중지",
+ "stop_hint": "이미 올린 코드와 댓글은 남습니다. 중지하지 않으면 두 에이전트가 이 태스크를 동시에 처리합니다.",
+ "queued_title": "{{name}}의 실행이 아직 대기 중입니다",
+ "cancel_queued_label": "{{name}}의 대기 중인 실행 취소",
+ "queued_hint": "취소하지 않으면 {{name}}이(가) 나중에 이 태스크 처리를 시작합니다.",
+ "brief_toggle": "{{name}}이(가) 받는 설명",
+ "confirm": "{{status}}(으)로 이동",
+ "cancel": "취소",
+ "minutes_other": "{{count}}분",
+ "hours_other": "{{count}}시간",
+ "under_minute": "1분 미만",
+ "error": "태스크를 옮기지 못했습니다",
+ "project_title": "{{issue}}을(를) {{project}}(으)로 옮길까요?",
+ "project_confirm": "{{project}}(으)로 이동"
+ },
+ "board": {
+ "drop_hint_run": "놓으면 {{name}}에게 인계하고 실행을 시작합니다",
+ "drop_hint": "놓으면 {{name}}에게 인계합니다"
+ },
+ "timeline": {
+ "handed_to": "인계 대상",
+ "run_started": "실행 시작 ·",
+ "member_no_run": "(멤버, 실행 없음)",
+ "show_brief": "인계 설명 보기",
+ "hide_brief": "인계 설명 접기",
+ "brief_header": "이번 실행이 받은 워크플로 설명"
+ },
+ "detail": {
+ "follows_project": "(프로젝트 기준)",
+ "card_title": "“{{workflow}}” · “{{project}}” 기준",
+ "card_hint": "이 열과 인계는 프로젝트의 워크플로가 정합니다."
+ },
+ "list_separator": ", ",
+ "handoff": {
+ "add": "넘기기…",
+ "title": "태스크가 “{{status}}”에 들어오면",
+ "next_default": "다음 열 ({{status}})",
+ "saved": "인계를 저장했습니다",
+ "error": "인계를 저장하지 못했습니다",
+ "read_only": "인계는 워크플로에 속하며 워크스페이스 관리자가 변경합니다.",
+ "to": "넘길 대상",
+ "members": "멤버",
+ "mode_none": "넘기지 않음",
+ "mode_none_hint": "담당자 유지",
+ "mode_agent": "에이전트에게 넘기기",
+ "mode_agent_hint": "바로 실행을 시작합니다",
+ "mode_member": "멤버에게 넘기기",
+ "mode_member_hint": "담당자만 바뀌고 자동으로 실행되지 않습니다",
+ "project_lead_hint": "프로젝트 리드가 에이전트라면 실행을 시작합니다.",
+ "pick_agent": "에이전트 선택",
+ "pick_member": "멤버 선택",
+ "search_agents": "에이전트 검색",
+ "search_members": "멤버 검색",
+ "instructions": "이 단계에서 할 일",
+ "scope_line": "{{workflow}} 워크플로의 일부",
+ "scope_line_shared": "{{workflow}}의 일부, {{projects}}에서도 사용 중",
+ "scope_more": "{{names}} 외 {{count}}개",
+ "scope_question": "이 변경을 어디에 적용할까요?",
+ "scope_all": "{{workflow}}을(를) 쓰는 프로젝트 {{count}}개",
+ "scope_all_hint": "{{projects}} 모두 새 인계를 따릅니다",
+ "scope_project": "{{project}}에만",
+ "scope_project_hint": "“{{copy}}”(으)로 복사해 {{project}}에서 사용합니다. 다른 프로젝트는 그대로입니다",
+ "saved_copy": "“{{workflow}}”에 저장했습니다. {{project}}만 사용합니다"
+ },
+ "columns": {
+ "new_status": "새 상태…",
+ "name_placeholder": "상태 이름",
+ "add": "추가"
+ },
+ "menu": {
+ "view_flow": "전체 흐름 보기",
+ "switch": "워크플로 전환"
+ },
+ "flow": {
+ "title": "“{{workflow}}” 워크플로",
+ "scope_own": "이 워크플로는 이 프로젝트만 사용합니다.",
+ "no_handoff_here": "인계 없음",
+ "scope_shared_other": "프로젝트 {{count}}개가 이 워크플로를 사용합니다. 인계는 모두에 적용됩니다."
+ },
+ "templates": {
+ "delivery": {
+ "name": "개발 딜리버리",
+ "summary": "개발·리뷰 후 QA를 거쳐 완료",
+ "statuses": {
+ "qa": "QA"
+ }
+ },
+ "content": {
+ "name": "콘텐츠 제작",
+ "summary": "작성·편집·예약 발행",
+ "statuses": {
+ "drafting": "작성 중",
+ "editing": "편집 중",
+ "scheduled": "예약됨"
+ }
+ },
+ "community": {
+ "name": "커뮤니티 운영",
+ "summary": "분류·답변·회신 대기",
+ "statuses": {
+ "triage": "분류",
+ "replying": "답변 중",
+ "waiting": "회신 대기"
+ }
+ }
+ }
}
}
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 56dbe60529..35b7f3b443 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -79,7 +79,10 @@
"cancelled": "진행하지 않기로 함."
},
"pr_auto_complete_badge": "PR 병합 시 자동 설정",
- "built_in_locked": "기본 상태는 시스템 동작에 쓰이므로 편집하거나 보관할 수 없습니다. 순서는 바꿀 수 있습니다."
+ "built_in_locked": "기본 상태는 시스템 동작에 쓰이므로 편집하거나 보관할 수 없습니다. 순서는 바꿀 수 있습니다.",
+ "builtin_badge": "기본 제공",
+ "workflow_usage_other": "워크플로 {{count}}개에서 사용 중",
+ "workflow_usage_none": "사용하는 워크플로 없음"
},
"wakeups": {
"description": "모든 태스크에 적용되는 플랫폼 규칙입니다. 각 태스크의 깨우기 섹션에서 따로 바꿀 수 있습니다.",
@@ -404,7 +407,8 @@
"billing": "결제 및 요금제",
"code": "코드",
"channels": "메신저",
- "apps": "연결된 앱"
+ "apps": "연결된 앱",
+ "workflows": "워크플로"
},
"groups": {
"personal": "개인",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 2fe23f0a29..d813d0d511 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -367,7 +367,10 @@
"empty_grouping": "没有匹配的任务",
"no_value": "未设置",
"ordered_by": "按{{field}}排序",
- "manual_reorder_hint": "切换到“手动”排序后,才能调整同一列内的顺序。"
+ "manual_reorder_hint": "切换到“手动”排序后,才能调整同一列内的顺序。",
+ "filter_to_status": "按此状态筛选",
+ "outside_workflow": "不在当前看板的工作流里",
+ "workflow_columns_note": "看板的列由工作流决定,项目外的视图使用 Default 工作流。"
},
"peek": {
"panel_label": "任务预览",
@@ -811,6 +814,7 @@
"delete": "删除",
"update_success_other": "已更新 {{count}} 个任务",
"update_failed": "更新任务失败",
+ "update_partial_other": "已更新 {{updated}}/{{count}} 个任务,其余任务不支持这项修改,保持不变。",
"delete_success_other": "已删除 {{count}} 个任务",
"delete_failed": "删除任务失败",
"delete_dialog_title_other": "删除 {{count}} 个任务?",
@@ -1426,5 +1430,258 @@
"overview_close": "关闭",
"overview_empty": "没有这类产物。",
"group_comment_by": "{{name}} 的评论"
+ },
+ "workflows": {
+ "default_name": "Default",
+ "default_summary": "全部状态,不自动交接",
+ "hands_off_to": "交给 {{name}}",
+ "not_in_workflow": "「{{name}}」里没有这个状态",
+ "drop_blocked": "「{{status}}」不在「{{name}}」工作流中",
+ "create_handoff_hint": "创建后交给 {{name}}",
+ "handler": {
+ "none": "负责人不变",
+ "agent": "智能体",
+ "squad": "小队",
+ "member": "成员",
+ "project_lead": "项目负责人",
+ "creator": "任务创建者",
+ "project_lead_named": "{{name}}(项目负责人)"
+ },
+ "settings": {
+ "title": "工作流",
+ "new": "新建工作流",
+ "projects_other": "{{count}} 个项目",
+ "default_projects": "未选用工作流的项目",
+ "no_projects": "暂未使用",
+ "edit": "编辑",
+ "delete": "删除",
+ "delete_title": "删除「{{name}}」?",
+ "delete_description": "任务会保留当前状态。",
+ "delete_in_use": "请先把使用它的项目切换到其他工作流。",
+ "deleted": "工作流已删除",
+ "delete_error": "无法删除工作流",
+ "statuses_title": "状态库",
+ "statuses_other": "{{count}} 个状态",
+ "handoffs_other": "{{count}} 步自动交接",
+ "no_handoffs": "无自动交接",
+ "used_by_other": "用于 {{count}} 个项目:{{names}}",
+ "used_by_default_other": "用于 {{count}} 个项目:{{names}},以及没有项目的任务",
+ "used_by_default_none": "用于没有项目的任务",
+ "new_blank": "空白工作流",
+ "from_template": "从模板创建"
+ },
+ "editor": {
+ "create_title": "新建工作流",
+ "edit_title": "编辑工作流",
+ "name": "名称",
+ "name_placeholder": "例如:研发流程",
+ "description": "描述",
+ "steps": "步骤",
+ "add_step": "添加步骤",
+ "start": "起始",
+ "set_start": "设为起始步骤",
+ "move_up": "上移",
+ "move_down": "下移",
+ "remove": "移除列",
+ "on_enter": "进入时交给",
+ "choose_target": "请选择…",
+ "instructions": "交接说明",
+ "instructions_placeholder": "这一步要做什么?",
+ "next": "完成后进入",
+ "back": "需要修改时退回",
+ "none_option": "不指定",
+ "save": "保存",
+ "create": "创建",
+ "cancel": "取消",
+ "saved": "工作流已保存",
+ "created": "工作流已创建",
+ "error": "无法保存工作流",
+ "used_by_note_other": "用于 {{count}} 个项目:{{names}}。修改保存后对这些项目立即生效。",
+ "unused_note": "暂无项目使用。在项目属性里选择它即可使用。",
+ "duplicate": "复制为新工作流",
+ "copy_name": "{{name}} 副本",
+ "more": "更多操作",
+ "steps_hint": "拖动调整中间列的顺序。Backlog 和 Blocked 可以关闭。新建的状态会在保存时创建。",
+ "reorder": "调整「{{name}}」的顺序",
+ "card_hand_to": "交给",
+ "card_then": "完成后 → {{status}}",
+ "status": "状态",
+ "status_hint": "状态来自状态库。改名和颜色在状态库里改,会同步到所有使用它的工作流。",
+ "handler_hint_on": "任务进入这一步时,负责人改为这里的处理人;处理人是智能体或小队时立即开始运行。",
+ "handler_hint_off": "进入这一步时负责人不变,也不会启动运行。",
+ "handler_hint_lead": "按项目解析:每个项目的负责人。",
+ "handler_hint_creator": "按任务解析:创建这个任务的人。",
+ "target_agent": "智能体",
+ "target_squad": "小队 · 由 leader 分派",
+ "target_member": "成员",
+ "instructions_hint": "作为这次运行的说明发给处理人,和任务描述、评论一起作为上下文。",
+ "next_hint": "写进处理人收到的说明里,告诉它下一步该把状态改成什么。系统不会在运行结束后自动推进状态。",
+ "preview_brief": "预览智能体收到的说明",
+ "preview_title": "「{{status}}」这一步的说明",
+ "preview_description": "任务进入这一步时,处理人的运行会收到这段说明。预览不需要先保存。",
+ "description_placeholder": "添加描述",
+ "select_step": "选择一列,设置任务进入时交给谁。",
+ "unsaved": "有未保存的修改",
+ "not_found": "这个工作流已不存在。",
+ "default_note": "Default 是所有未选择工作流的项目、以及项目之外视图使用的看板。",
+ "new_badge": "新建",
+ "columns": "列",
+ "include_status": "包含「{{status}}」",
+ "step_off_short": "未启用",
+ "step_off": "已关闭:这个工作流不使用这个状态。在左侧列表打开开关即可使用。",
+ "status_new_hint": "新状态,保存时加入状态库。",
+ "no_other_status": "所有状态都已经是步骤了。",
+ "no_handoff_step": "这一步不交接:任务进入时负责人不变,也不会启动运行。",
+ "new_step_handoff": "先保存工作流,新状态保存后就可以设置交接。"
+ },
+ "mapping": {
+ "title": "将任务移入「{{name}}」",
+ "description": "以下状态不在该工作流中,请为这些任务选择新状态;其他任务保持不变。",
+ "issues_other": "{{count}} 个任务",
+ "no_handoff": "这样移动不会触发交接,也不会启动运行。",
+ "confirm": "移动并切换",
+ "confirm_save": "移动并保存",
+ "cancel": "取消",
+ "switch_title": "把「{{project}}」切换到「{{workflow}}」?",
+ "switch_description_other": "{{project}} 共 {{count}} 个任务。只有状态不在「{{workflow}}」里的任务需要重新选择状态。",
+ "needs_mapping_other": "需要映射 · {{count}} 个任务",
+ "unchanged_other": "其余 {{count}} 个任务的状态({{statuses}})两个工作流都有,保持不变。",
+ "switch_note": "切换是管理操作:不会触发交接,也不会启动智能体,负责人保持不变。已保存的视图和筛选按状态工作,不受影响。",
+ "confirm_count_other": "切换并更新 {{count}} 个任务",
+ "confirm_plain": "切换",
+ "edit_title": "保存「{{workflow}}」?",
+ "edit_description": "使用这个工作流的项目里,有任务处在被移除的状态上。请为它们选择新状态,其他任务不变。",
+ "confirm_save_count_other": "保存并更新 {{count}} 个任务",
+ "switched_other": "「{{project}}」已切换到「{{workflow}}」,{{count}} 个任务已更新状态",
+ "nothing_moves": "所有任务的状态两个工作流都有,保持不变。"
+ },
+ "project": {
+ "label": "工作流",
+ "switched": "已切换工作流",
+ "error": "无法切换工作流",
+ "picker_title": "选择工作流",
+ "default_badge": "默认",
+ "used_by_short": "用于:{{names}}",
+ "used_by_nobody": "暂无项目",
+ "manage": "管理工作流…",
+ "picker_more": "在「设置 → 工作流」里可以新建更多工作流。"
+ },
+ "picker": {
+ "header": "{{workflow}} · 跟随项目「{{project}}」",
+ "footer": "只显示这个任务所在工作流里的状态。右侧是进入该状态时的处理人。"
+ },
+ "confirm": {
+ "title": "将 {{issue}} 移到「{{status}}」?",
+ "reassign_run": "负责人将从 {{from}} 改为 {{to}},它会立即开始运行。",
+ "reassign": "负责人将从 {{from}} 改为 {{to}}。",
+ "same_handler_run": "负责人仍是 {{to}},它会开始处理这一步。",
+ "unassigned": "未分配",
+ "running_title": "{{name}} 还在运行(已运行 {{duration}})",
+ "stop_label": "停止 {{name}} 的运行",
+ "stop_hint": "已经提交的代码和评论会保留。不停止的话,两个智能体会同时处理这个任务。",
+ "queued_title": "{{name}} 的运行还在排队",
+ "cancel_queued_label": "取消 {{name}} 排队中的运行",
+ "queued_hint": "不取消的话,{{name}} 之后仍会开始处理这个任务。",
+ "brief_toggle": "{{name}} 会收到的说明",
+ "confirm": "移到{{status}}",
+ "cancel": "取消",
+ "minutes_other": "{{count}} 分钟",
+ "hours_other": "{{count}} 小时",
+ "under_minute": "不到 1 分钟",
+ "error": "无法移动任务",
+ "project_title": "将 {{issue}} 移到「{{project}}」?",
+ "project_confirm": "移到{{project}}"
+ },
+ "board": {
+ "drop_hint_run": "松开后交给 {{name}},并开始运行",
+ "drop_hint": "松开后交给 {{name}}"
+ },
+ "timeline": {
+ "handed_to": "已交给",
+ "run_started": "并开始运行 ·",
+ "member_no_run": "(成员,不启动运行)",
+ "show_brief": "查看交接说明",
+ "hide_brief": "收起交接说明",
+ "brief_header": "这次运行收到的工作流说明"
+ },
+ "detail": {
+ "follows_project": "(跟随项目)",
+ "card_title": "「{{workflow}}」· 跟随项目「{{project}}」",
+ "card_hint": "这些列和交接由项目的工作流决定。"
+ },
+ "list_separator": "、",
+ "handoff": {
+ "add": "交给…",
+ "title": "任务进入「{{status}}」时",
+ "next_default": "下一列({{status}})",
+ "saved": "交接已保存",
+ "error": "无法保存交接",
+ "read_only": "交接属于工作流,由工作区管理员修改。",
+ "to": "交给谁",
+ "members": "成员",
+ "mode_none": "不交接",
+ "mode_none_hint": "负责人不变",
+ "mode_agent": "交给智能体",
+ "mode_agent_hint": "立即开始运行",
+ "mode_member": "交给成员",
+ "mode_member_hint": "只改负责人,不会自动运行",
+ "project_lead_hint": "项目负责人是智能体时,会开始运行。",
+ "pick_agent": "选择智能体",
+ "pick_member": "选择成员",
+ "search_agents": "搜索智能体",
+ "search_members": "搜索成员",
+ "instructions": "这一步要做什么",
+ "scope_line": "属于「{{workflow}}」工作流",
+ "scope_line_shared": "属于「{{workflow}}」,也用于 {{projects}}",
+ "scope_more": "{{names}} 等 {{count}} 个项目",
+ "scope_question": "这次修改用在哪?",
+ "scope_all": "用于「{{workflow}}」的 {{count}} 个项目",
+ "scope_all_hint": "{{projects}} 都按新的交接执行",
+ "scope_project": "只用于{{project}}",
+ "scope_project_hint": "复制一份「{{copy}}」给{{project}}用,其他项目不变",
+ "saved_copy": "已保存到「{{workflow}}」,只有{{project}}使用"
+ },
+ "columns": {
+ "new_status": "新建状态…",
+ "name_placeholder": "状态名称",
+ "add": "添加"
+ },
+ "menu": {
+ "view_flow": "查看完整流程",
+ "switch": "切换工作流"
+ },
+ "flow": {
+ "title": "「{{workflow}}」工作流",
+ "scope_own": "只有这个项目使用这个工作流。",
+ "no_handoff_here": "不交接",
+ "scope_shared_other": "{{count}} 个项目使用这个工作流,它的交接对这些项目都生效。"
+ },
+ "templates": {
+ "delivery": {
+ "name": "研发交付",
+ "summary": "开发、评审,再经过 QA 完成",
+ "statuses": {
+ "qa": "QA"
+ }
+ },
+ "content": {
+ "name": "内容生产",
+ "summary": "撰写、编辑、排期发布",
+ "statuses": {
+ "drafting": "撰写中",
+ "editing": "编辑中",
+ "scheduled": "已排期"
+ }
+ },
+ "community": {
+ "name": "社区维护",
+ "summary": "分诊、回复、等待反馈",
+ "statuses": {
+ "triage": "待分诊",
+ "replying": "回复中",
+ "waiting": "等待反馈"
+ }
+ }
+ }
}
}
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 9076af0977..ec7ffbd2e7 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -79,7 +79,10 @@
"cancelled": "决定不做。"
},
"pr_auto_complete_badge": "PR 合并后自动进入",
- "built_in_locked": "内置状态驱动系统行为,不能编辑或归档,但可以调整顺序。"
+ "built_in_locked": "内置状态驱动系统行为,不能编辑或归档,但可以调整顺序。",
+ "builtin_badge": "内置",
+ "workflow_usage_other": "{{count}} 个工作流在用",
+ "workflow_usage_none": "未被工作流使用"
},
"wakeups": {
"description": "平台对所有任务生效的规则。每个任务可以在自己的「唤醒」区域单独修改。",
@@ -404,7 +407,8 @@
"billing": "账单与套餐",
"code": "代码",
"channels": "消息渠道",
- "apps": "已连接应用"
+ "apps": "已连接应用",
+ "workflows": "工作流"
},
"groups": {
"personal": "个人",
diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsx
index 663e609b95..a8ec38d3c3 100644
--- a/packages/views/modals/create-issue.tsx
+++ b/packages/views/modals/create-issue.tsx
@@ -63,6 +63,9 @@ import { useActorName } from "@multica/core/workspace/hooks";
import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
import { useWorkspaceId } from "@multica/core/hooks";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { useProjectWorkflow, workflowAllowsStatus, workflowStep } from "@multica/core/issue-workflows";
+import { projectListOptions } from "@multica/core/projects/queries";
+import { stepHandlerActor, useStepHandlerLabel } from "../workflows/step-handler";
import { useIssueDraftStore, type IssueCreateDraft } from "@multica/core/issues/stores/draft-store";
import { useCreateModeStore } from "@multica/core/issues/stores/create-mode-store";
import { useQuickCreateStore } from "@multica/core/issues/stores/quick-create-store";
@@ -194,6 +197,29 @@ function CreateRunHint({
);
}
+/**
+ * Names who a new issue will be handed to when its project's workflow starts
+ * it on a step with a handler and no assignee was picked. (MUL-7420)
+ */
+function WorkflowHandoffHint({ projectId, status }: { projectId?: string; status: IssueStatus }) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const workflow = useProjectWorkflow(wsId, projectId);
+ const { data: projects } = useQuery({ ...projectListOptions(wsId), enabled: !!workflow });
+ const project = projects?.find((p) => p.id === projectId);
+ const handlerLabel = useStepHandlerLabel(project);
+ const step = workflowStep(workflow, status);
+ const label = handlerLabel(step);
+ if (!label) return null;
+ const actor = stepHandlerActor(step, project);
+ return (
+ <div aria-live="polite" className="flex items-center gap-1.5 px-4 pb-1 pt-0.5 text-micro text-muted-foreground">
+ {actor && <ActorAvatar actorType={actor.type} actorId={actor.id} size="sm" profileLink={false} />}
+ <span className="truncate">{t(($) => $.workflows.create_handoff_hint, { name: label })}</span>
+ </div>
+ );
+}
+
export function ManualCreatePanel({
onClose,
onSwitchMode,
@@ -384,6 +410,14 @@ export function ManualCreatePanel({
setManual({ assigneeType: type, assigneeId: id });
};
const updateProject = (id?: string) => { setProjectId(id); setShared({ projectId: id }); };
+ // A project using a named workflow only accepts its columns: a status it
+ // does not list moves to todo, which every workflow keeps. (MUL-7420)
+ const createWorkflow = useProjectWorkflow(wsId, projectId);
+ useEffect(() => {
+ if (createWorkflow && !workflowAllowsStatus(createWorkflow, status)) {
+ setStatus("todo");
+ }
+ }, [createWorkflow, status]);
const updateStartDate = (v: string | null) => { setStartDate(v); setManual({ startDate: v }); };
const updateDueDate = (v: string | null) => { setDueDate(v); setShared({ dueDate: v }); };
const updateLabelIds = (ids: string[]) => { setLabelIds(ids); setManual({ labelIds: ids }); };
@@ -992,7 +1026,11 @@ export function ManualCreatePanel({
{/* Pre-trigger preview — a passive caption above the toolbar; reveals
when an agent assignee will pick the issue up. */}
- <CreateRunHint assigneeType={assigneeType} assigneeId={assigneeId} status={status} />
+ {assigneeId ? (
+ <CreateRunHint assigneeType={assigneeType} assigneeId={assigneeId} status={status} />
+ ) : (
+ <WorkflowHandoffHint projectId={projectId} status={status} />
+ )}
{/* Property toolbar — each field renders per the Settings → Preferences → Issue creation
selection (see showField above). */}
@@ -1001,6 +1039,7 @@ export function ManualCreatePanel({
{showField.status && (
<StatusPicker
status={status}
+ projectId={projectId ?? null}
onUpdate={(u) => { if (u.status) updateStatus(u.status); }}
triggerRender={<PillButton />}
align="start"
diff --git a/packages/views/modals/create-project-local-mode.test.tsx b/packages/views/modals/create-project-local-mode.test.tsx
index ea9d5fec9d..e69e1021c1 100644
--- a/packages/views/modals/create-project-local-mode.test.tsx
+++ b/packages/views/modals/create-project-local-mode.test.tsx
@@ -96,6 +96,7 @@ vi.mock("@multica/core/config", () => ({
}));
vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));
+vi.mock("../workflows/workflow-pill", () => ({ WorkflowPill: () => null }));
vi.mock("@multica/core/paths", () => ({
useCurrentWorkspace: () => ({ id: "workspace-1", slug: "ws", repos: [] }),
useWorkspacePaths: () => ({ projectDetail: (id: string) => `/ws/projects/${id}` }),
diff --git a/packages/views/modals/create-project.tsx b/packages/views/modals/create-project.tsx
index 40de5b887c..acf2a4542d 100644
--- a/packages/views/modals/create-project.tsx
+++ b/packages/views/modals/create-project.tsx
@@ -61,6 +61,7 @@ import {
import { ProjectStartDatePicker } from "../projects/components/project-start-date-picker";
import { ProjectDueDatePicker } from "../projects/components/project-due-date-picker";
import { PillButton } from "../common/pill-button";
+import { WorkflowPill } from "../workflows/workflow-pill";
import { githubShortLabel } from "../common/github-url";
import {
GithubRefField,
@@ -311,6 +312,8 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {
setLocalMode(null);
};
+ const [workflowId, setWorkflowId] = useState<string | null>(null);
+
// Sync field changes to draft store
const updateTitle = (v: string) => { setTitle(v); setDraft({ title: v }); };
const updateStatus = (v: ProjectStatus) => { setStatus(v); setDraft({ status: v }); };
@@ -395,6 +398,7 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {
lead_id: leadId,
start_date: startDate || undefined,
due_date: dueDate || undefined,
+ ...(workflowId ? { workflow_id: workflowId } : {}),
// Server attaches these in the same transaction as the project.
resources,
});
@@ -611,6 +615,8 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {
</DropdownMenuContent>
</DropdownMenu>
+ <WorkflowPill value={workflowId} onChange={setWorkflowId} />
+
<Popover
open={leadOpen}
onOpenChange={(v) => {
diff --git a/packages/views/modals/registry.tsx b/packages/views/modals/registry.tsx
index 40fb5215d6..94773bf220 100644
--- a/packages/views/modals/registry.tsx
+++ b/packages/views/modals/registry.tsx
@@ -11,6 +11,7 @@ import { MarkDuplicateIssueModal } from "./mark-duplicate-issue";
import { AddChildIssueModal } from "./add-child-issue";
import { DeleteIssueConfirmModal } from "./delete-issue-confirm";
import { RunConfirmModal } from "./run-confirm";
+import { WorkflowHandoffModal } from "./workflow-handoff";
import { IssueLimitUpgradeDialog } from "./issue-limit-upgrade-dialog";
export function ModalRegistry() {
@@ -64,6 +65,9 @@ export function ModalRegistry() {
case "issue-run-confirm":
activeModal = <RunConfirmModal onClose={close} data={data} />;
break;
+ case "issue-workflow-handoff":
+ activeModal = <WorkflowHandoffModal onClose={close} data={data} />;
+ break;
}
return (
diff --git a/packages/views/modals/workflow-handoff.tsx b/packages/views/modals/workflow-handoff.tsx
new file mode 100644
index 0000000000..45c4631e6d
--- /dev/null
+++ b/packages/views/modals/workflow-handoff.tsx
@@ -0,0 +1,43 @@
+"use client";
+
+import { toast } from "sonner";
+import { useUpdateIssue } from "@multica/core/issues/mutations";
+import { useT } from "../i18n";
+import { WorkflowHandoffConfirmDialog } from "../workflows/handoff-confirm-dialog";
+
+/**
+ * The workflow handoff confirmation for entry points that cannot host the
+ * dialog themselves, such as an issue's context menu (MUL-7420). Applies the
+ * status change once confirmed.
+ */
+export function WorkflowHandoffModal({
+ onClose,
+ data,
+}: {
+ onClose: () => void;
+ data: Record<string, unknown> | null;
+}) {
+ const { t } = useT("issues");
+ const updateIssue = useUpdateIssue();
+ const issueId = typeof data?.issueId === "string" ? data.issueId : "";
+ const identifier = typeof data?.identifier === "string" ? data.identifier : "";
+ const status = typeof data?.status === "string" ? data.status : "";
+ if (!issueId || !status) return null;
+ return (
+ <WorkflowHandoffConfirmDialog
+ issue={{ id: issueId, identifier }}
+ toStatus={status}
+ onCancel={onClose}
+ onConfirm={({ stopPreviousRuns }) => {
+ onClose();
+ updateIssue.mutate(
+ { id: issueId, status, ...(stopPreviousRuns ? { stop_previous_assignee_runs: true } : {}) },
+ {
+ onError: (err) =>
+ toast.error(err instanceof Error && err.message ? err.message : t(($) => $.detail.update_failed)),
+ },
+ );
+ }}
+ />
+ );
+}
diff --git a/packages/views/projects/components/issue-project-picker.tsx b/packages/views/projects/components/issue-project-picker.tsx
new file mode 100644
index 0000000000..5b05be2f9d
--- /dev/null
+++ b/packages/views/projects/components/issue-project-picker.tsx
@@ -0,0 +1,66 @@
+"use client";
+
+import { useState, type ComponentProps } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { projectMoveMayHandOff, resolveProjectWorkflow, useIssueWorkflows } from "@multica/core/issue-workflows";
+import { projectListOptions } from "@multica/core/projects/queries";
+import type { Project, UpdateIssueRequest } from "@multica/core/types";
+import { WorkflowHandoffConfirmDialog } from "../../workflows/handoff-confirm-dialog";
+import { ProjectPicker } from "./project-picker";
+
+/**
+ * The project picker of a single issue (MUL-7420). Moving the issue into a
+ * project whose workflow hands off the column it lands on first confirms the
+ * handoff, like a status change would; the write then enters that column.
+ * Create and batch surfaces use the plain picker, where a move stays
+ * administrative.
+ */
+export function IssueProjectPicker({
+ issue,
+ onUpdate,
+ ...props
+}: ComponentProps<typeof ProjectPicker> & {
+ issue: { id: string; identifier: string; status: string; project_id: string | null };
+}) {
+ const wsId = useWorkspaceId();
+ const { data: projects = [] } = useQuery(projectListOptions(wsId));
+ const { workflows } = useIssueWorkflows(wsId);
+ const [pending, setPending] = useState<Project | null>(null);
+
+ const update = (updates: Partial<UpdateIssueRequest>) => {
+ const target = updates.project_id ? projects.find((p) => p.id === updates.project_id) : undefined;
+ if (
+ target &&
+ target.id !== issue.project_id &&
+ projectMoveMayHandOff(resolveProjectWorkflow(workflows, target), issue.status)
+ ) {
+ setPending(target);
+ return;
+ }
+ onUpdate(updates);
+ };
+
+ return (
+ <>
+ <ProjectPicker {...props} onUpdate={update} />
+ <WorkflowHandoffConfirmDialog
+ issue={pending ? issue : null}
+ toStatus=""
+ toProject={pending}
+ onCancel={() => setPending(null)}
+ onConfirm={({ stopPreviousRuns }) => {
+ const next = pending;
+ setPending(null);
+ if (next) {
+ onUpdate({
+ project_id: next.id,
+ enter_workflow_step: true,
+ ...(stopPreviousRuns ? { stop_previous_assignee_runs: true } : {}),
+ });
+ }
+ }}
+ />
+ </>
+ );
+}
diff --git a/packages/views/projects/components/project-detail.test.tsx b/packages/views/projects/components/project-detail.test.tsx
index b9c23ab80e..58f011c94a 100644
--- a/packages/views/projects/components/project-detail.test.tsx
+++ b/packages/views/projects/components/project-detail.test.tsx
@@ -21,6 +21,8 @@ vi.mock("@multica/ui/lib/clipboard", () => ({
copyText: mocks.copyText,
}));
+vi.mock("../../workflows/project-workflow-menu", () => ({ ProjectWorkflowMenu: () => null }));
+
vi.mock("@tanstack/react-query", () => ({
useQuery: (options: { queryKey?: readonly unknown[] }) => {
switch (options.queryKey?.[0]) {
diff --git a/packages/views/projects/components/project-detail.tsx b/packages/views/projects/components/project-detail.tsx
index bc3de74975..d9c1f4da08 100644
--- a/packages/views/projects/components/project-detail.tsx
+++ b/packages/views/projects/components/project-detail.tsx
@@ -7,7 +7,9 @@ import { useQuery } from "@tanstack/react-query";
import { cn } from "@multica/ui/lib/utils";
import { copyText } from "@multica/ui/lib/clipboard";
import { toast } from "sonner";
-import type { ProjectStatus, ProjectPriority } from "@multica/core/types";
+import type { Project, ProjectStatus, ProjectPriority } from "@multica/core/types";
+import { useFeatureEnabled } from "@multica/core/config";
+import { PROJECT_WORKFLOWS_V1_FLAG } from "@multica/core/feature-flags";
import { useAuthStore } from "@multica/core/auth";
import { projectDetailOptions } from "@multica/core/projects/queries";
import { useUpdateProject, useDeleteProject } from "@multica/core/projects/mutations";
@@ -28,6 +30,8 @@ import { PriorityIcon } from "../../issues/components/priority-icon";
import { ProjectResourcesSection } from "./project-resources-section";
import { ProjectStartDatePicker } from "./project-start-date-picker";
import { ProjectDueDatePicker } from "./project-due-date-picker";
+import { ProjectWorkflowControl } from "../../workflows/project-workflow-row";
+import { ProjectWorkflowMenu } from "../../workflows/project-workflow-menu";
import { IssueSurface } from "../../issues/surface/issue-surface";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { Button } from "@multica/ui/components/ui/button";
@@ -93,6 +97,19 @@ function PropRow({
);
}
+// The project's workflow (MUL-7420). Hidden while workflows are off, unless the
+// project already uses one — it can always switch back to Default.
+function ProjectWorkflowPropRow({ project }: { project: Project }) {
+ const { t } = useT("issues");
+ const enabled = useFeatureEnabled(PROJECT_WORKFLOWS_V1_FLAG, false);
+ if (!enabled && !project.workflow_id) return null;
+ return (
+ <PropRow label={t(($) => $.workflows.project.label)}>
+ <ProjectWorkflowControl project={project} />
+ </PropRow>
+ );
+}
+
// ProjectDetail
export function ProjectDetail({ projectId }: { projectId: string }) {
@@ -408,6 +425,7 @@ export function ProjectDetail({ projectId }: { projectId: string }) {
<PropRow label={t(($) => $.detail.prop_due_date)}>
<ProjectDueDatePicker dueDate={project.due_date} onUpdate={handleUpdateField} />
</PropRow>
+ <ProjectWorkflowPropRow project={project} />
</div>}
</div>
@@ -479,6 +497,7 @@ export function ProjectDetail({ projectId }: { projectId: string }) {
leaf={<span className="truncate font-medium text-foreground">{project.title}</span>}
actions={
<>
+ <ProjectWorkflowMenu project={project} />
<Button
variant="ghost"
size="icon-sm"
diff --git a/packages/views/settings/components/issue-statuses-tab.tsx b/packages/views/settings/components/issue-statuses-tab.tsx
index a5ce288b02..efd685decf 100644
--- a/packages/views/settings/components/issue-statuses-tab.tsx
+++ b/packages/views/settings/components/issue-statuses-tab.tsx
@@ -135,6 +135,9 @@ interface StatusDraft {
icon: IssueStatusIcon | "";
}
+/** Built-ins whose note says what moving an issue there does; the rest only restate the name. */
+const BEHAVIOR_STATUSES = new Set<string>(["backlog", "todo", "in_review"]);
+
const EMPTY_DRAFT: StatusDraft = {
name: "",
description: "",
@@ -143,7 +146,18 @@ const EMPTY_DRAFT: StatusDraft = {
icon: "",
};
-export function IssueStatusesTab() {
+/**
+ * The status library. Rendered as its own settings tab, or `embedded` under
+ * Settings → Workflows (MUL-7420), where each row also says how many
+ * workflows use the status.
+ */
+export function IssueStatusesTab({
+ embedded,
+ workflowUsage,
+}: {
+ embedded?: { title: string };
+ workflowUsage?: (statusKey: string) => number;
+} = {}) {
const { t } = useT("settings");
const wsId = useWorkspaceId();
const navigation = useNavigation();
@@ -196,49 +210,50 @@ export function IssueStatusesTab() {
setInspectionOpen(true);
};
- return (
- <SettingsTab
- title={t(($) => $.page.tabs.issue_statuses)}
- description={isAdmin ? t(($) => $.issue_statuses.reorder_hint) : undefined}
- scope="workspace"
- actions={
- // Offered only once the workspace has something archived. A
- // permanently disabled "Show archived (0)" is a control that can
- // never do anything.
- archivedCount > 0 ? (
- <label className="flex items-center gap-2 text-caption text-muted-foreground">
- {t(($) => $.issue_statuses.show_archived, { count: archivedCount })}
- <Switch checked={showArchived} onCheckedChange={setShowArchived} />
- </label>
- ) : undefined
- }
- >
+ // Offered only once the workspace has something archived. A permanently
+ // disabled "Show archived (0)" is a control that can never do anything.
+ const archivedToggle = archivedCount > 0 ? (
+ <label className="flex items-center justify-end gap-2 text-caption text-muted-foreground">
+ {t(($) => $.issue_statuses.show_archived, { count: archivedCount })}
+ <Switch checked={showArchived} onCheckedChange={setShowArchived} />
+ </label>
+ ) : undefined;
+
+ const body = (
+ <>
{myRole && !isAdmin ? <SettingsReadOnlyNotice wsId={wsId} /> : null}
- {isLoading ? (
- <div className="rounded-lg border border-surface-border bg-card px-4 py-12 text-center text-body text-muted-foreground">
- {t(($) => $.issue_statuses.loading)}
- </div>
- ) : (
- // The four categories are sections of a single
- // workflow, and separate borders made them read as unrelated
- // settings.
- <div className="overflow-hidden rounded-lg border border-surface-border bg-card">
- {groups.map((group) => (
- <CategorySection
- key={`${wsId}:${group.category}`}
- category={group.category}
- entries={group.entries}
- canManage={isAdmin}
- mergeTarget={mergeTarget}
- mergeSettingsHref={mergeSettingsHref}
- onCreate={() => setCreateCategory(group.category)}
- onEdit={(entry) => setEditing(entry)}
- onArchive={(entry) => { setPendingArchive(entry); setArchiveOpen(true); }}
- onViewIssues={viewIssues}
- />
- ))}
- </div>
- )}
+ <div className="space-y-4">
+ {embedded && archivedToggle}
+
+ {isLoading ? (
+ <div className="rounded-lg border border-surface-border bg-card px-4 py-12 text-center text-body text-muted-foreground">
+ {t(($) => $.issue_statuses.loading)}
+ </div>
+ ) : (
+ // The four categories are sections of a single
+ // workflow, and separate borders made them read as unrelated
+ // settings.
+ <div className="overflow-hidden rounded-lg border border-surface-border bg-card">
+ {groups.map((group) => (
+ <CategorySection
+ key={`${wsId}:${group.category}`}
+ category={group.category}
+ entries={group.entries}
+ canManage={isAdmin}
+ workflowUsage={workflowUsage}
+ mergeTarget={mergeTarget}
+ mergeSettingsHref={mergeSettingsHref}
+ onCreate={() => setCreateCategory(group.category)}
+ onEdit={(entry) => setEditing(entry)}
+ onArchive={(entry) => {
+ setPendingArchive(entry); setArchiveOpen(true);
+ }}
+ onViewIssues={viewIssues}
+ />
+ ))}
+ </div>
+ )}
+ </div>
<StatusEditorDialog
open={createCategory !== null}
@@ -259,6 +274,22 @@ export function IssueStatusesTab() {
{inspection?.workspaceId === wsId && <StatusIssueInspection key={`${wsId}:${inspection.status.key}`} status={inspection.status} onClose={() => setInspectionOpen(false)} />}
</DialogContent>
</Dialog>
+ </>
+ );
+
+ return embedded ? (
+ <section id="status-library" className="space-y-4">
+ <h3 className="text-title-sm font-semibold">{embedded.title}</h3>
+ {body}
+ </section>
+ ) : (
+ <SettingsTab
+ title={t(($) => $.page.tabs.issue_statuses)}
+ description={isAdmin ? t(($) => $.issue_statuses.reorder_hint) : undefined}
+ scope="workspace"
+ actions={archivedToggle}
+ >
+ {body}
</SettingsTab>
);
}
@@ -267,6 +298,7 @@ function CategorySection({
category,
entries,
canManage,
+ workflowUsage,
mergeTarget,
mergeSettingsHref,
onCreate,
@@ -278,6 +310,7 @@ function CategorySection({
entries: IssueStatusEntry[];
canManage: boolean;
/** Badge the built-in Done row: PR auto-complete writes that status. */
+ workflowUsage?: (statusKey: string) => number;
mergeTarget: string;
mergeSettingsHref: string;
onCreate: () => void;
@@ -383,10 +416,14 @@ function CategorySection({
entry={entry}
mergeBadgeHref={entry.key === mergeTarget && !entry.archived_at ? mergeSettingsHref : null}
label={entry.is_system ? labelOf(entry.key) : entry.name}
- description={entry.is_system
- ? t(($) => $.issue_statuses.built_in_descriptions[entry.key as BuiltInIssueStatus])
- : entry.description}
+ description={!entry.is_system
+ ? entry.description
+ : workflowUsage && !BEHAVIOR_STATUSES.has(entry.key)
+ ? ""
+ : t(($) => $.issue_statuses.built_in_descriptions[entry.key as BuiltInIssueStatus])}
canManage={canManage}
+ workflowUsage={entry.is_system ? undefined : workflowUsage?.(entry.key)}
+ showKey={Boolean(workflowUsage)}
canReorder={canReorder && !entry.archived_at}
isReordering={reorder.isPending}
onEdit={() => onEdit(entry)}
@@ -414,6 +451,8 @@ function StatusRow({
label,
description,
canManage,
+ workflowUsage,
+ showKey,
canReorder,
isReordering,
onEdit,
@@ -428,6 +467,9 @@ function StatusRow({
label: string;
description: string;
canManage: boolean;
+ /** How many workflows list a custom status; undefined for built-ins and outside Workflows. */
+ workflowUsage?: number;
+ showKey: boolean;
canReorder: boolean;
isReordering: boolean;
onEdit: () => void;
@@ -475,6 +517,14 @@ function StatusRow({
<div className="min-w-0 flex-1">
<div className="flex min-w-0 items-center gap-2">
<span className="truncate text-body font-medium">{label}</span>
+ {showKey && entry.is_system && (
+ <span className="shrink-0 rounded-xs bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">
+ {t(($) => $.issue_statuses.builtin_badge)}
+ </span>
+ )}
+ {showKey && (
+ <span className="shrink-0 font-mono text-caption text-muted-foreground">{entry.key}</span>
+ )}
{mergeBadgeHref && (
<AppLink
href={mergeBadgeHref}
@@ -501,6 +551,13 @@ function StatusRow({
<p className="truncate text-caption text-muted-foreground">{description}</p>
)}
</div>
+ {workflowUsage !== undefined && !archived && (
+ <span className="shrink-0 text-caption text-muted-foreground">
+ {workflowUsage > 0
+ ? t(($) => $.issue_statuses.workflow_usage, { count: workflowUsage })
+ : t(($) => $.issue_statuses.workflow_usage_none)}
+ </span>
+ )}
{archived && <StatusIssuesButton variant="outline" onClick={onViewIssues} />}
{canManage && !archived && (
<DropdownMenu>
diff --git a/packages/views/settings/components/settings-page.test.tsx b/packages/views/settings/components/settings-page.test.tsx
index 85002cb247..c5e821aa3b 100644
--- a/packages/views/settings/components/settings-page.test.tsx
+++ b/packages/views/settings/components/settings-page.test.tsx
@@ -6,6 +6,7 @@ import { configStore } from "@multica/core/config";
import {
BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,
PLUGINS_V1_FLAG,
+ PROJECT_WORKFLOWS_V1_FLAG,
} from "@multica/core/feature-flags";
import { renderWithI18n } from "../../test/i18n";
@@ -24,6 +25,7 @@ vi.mock("./channels-tab", stub("ChannelsTab"));
vi.mock("./notifications-tab", stub("NotificationsTab"));
vi.mock("./labels-tab", stub("LabelsTab"));
vi.mock("./issue-statuses-tab", stub("IssueStatusesTab"));
+vi.mock("../../workflows/workflows-tab", stub("WorkflowsTab"));
vi.mock("./properties-tab", stub("PropertiesTab"));
vi.mock("./quick-actions-tab", stub("QuickActionsTab"));
vi.mock("./keyboard-shortcuts-tab", stub("KeyboardShortcutsTab"));
@@ -173,6 +175,30 @@ describe("SettingsPage Plugin feature flag", () => {
});
});
+describe("SettingsPage workflow feature flag", () => {
+ it("mounts workflows in workspace settings without losing wakeups", () => {
+ navigationState.search = "tab=workflows";
+ configStore.getState().setFeatureFlags({ [PROJECT_WORKFLOWS_V1_FLAG]: true });
+
+ renderWithI18n(<SettingsPage />);
+
+ expect(screen.getByText("WorkflowsTab")).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "Workflows" })).toHaveAttribute("aria-current", "page");
+ expect(screen.queryByRole("link", { name: "Issue Statuses" })).not.toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "Wakeups" })).toBeInTheDocument();
+ });
+
+ it("keeps the status catalog when workflows are disabled", () => {
+ navigationState.search = "tab=issue-statuses";
+
+ renderWithI18n(<SettingsPage />);
+
+ expect(screen.getByText("IssueStatusesTab")).toBeInTheDocument();
+ expect(screen.queryByRole("link", { name: "Workflows" })).not.toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "Wakeups" })).toBeInTheDocument();
+ });
+});
+
describe("SettingsPage workspace subscription feature flag", () => {
it("hides Billing and falls back to Workspace General from a direct URL", () => {
navigationState.search = "tab=billing";
diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsx
index f933b307c1..8c14b2b0f6 100644
--- a/packages/views/settings/components/settings-page.tsx
+++ b/packages/views/settings/components/settings-page.tsx
@@ -23,6 +23,7 @@ import {
User,
Users,
X,
+ Workflow,
Zap,
} from "lucide-react";
import { useAuthStore } from "@multica/core/auth";
@@ -32,6 +33,7 @@ import { useCurrentMember } from "@multica/core/permissions";
import {
BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,
PLUGINS_V1_FLAG,
+ PROJECT_WORKFLOWS_V1_FLAG,
} from "@multica/core/feature-flags";
import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";
@@ -50,6 +52,7 @@ import { ConnectedAppsTab, useComposioAvailable } from "./connected-apps-tab";
import { NotificationsTab } from "./notifications-tab";
import { LabelsTab } from "./labels-tab";
import { IssueStatusesTab } from "./issue-statuses-tab";
+import { WorkflowsTab } from "../../workflows/workflows-tab";
import { PropertiesTab } from "./properties-tab";
import { QuickActionsTab } from "./quick-actions-tab";
import { KeyboardShortcutsTab } from "./keyboard-shortcuts-tab";
@@ -110,6 +113,7 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {
const isMember = role === "member";
const navigation = useNavigation();
const pluginsEnabled = useFeatureEnabled(PLUGINS_V1_FLAG, false);
+ const workflowsEnabled = useFeatureEnabled(PROJECT_WORKFLOWS_V1_FLAG, false);
const billingEnabled = useFeatureEnabled(
BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,
false,
@@ -205,13 +209,15 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {
key: "issues",
label: t(($) => $.page.groups.issues),
entries: [
- entry(
- "issue-statuses",
- t(($) => $.page.tabs.issue_statuses),
- CircleDot,
- <IssueStatusesTab />,
- { wide: true, adminOnly: true },
- ),
+ ...(workflowsEnabled
+ ? [entry("workflows", t(($) => $.page.tabs.workflows), Workflow, <WorkflowsTab />, {
+ wide: true,
+ adminOnly: true,
+ })]
+ : [entry("issue-statuses", t(($) => $.page.tabs.issue_statuses), CircleDot, <IssueStatusesTab />, {
+ wide: true,
+ adminOnly: true,
+ })]),
entry("wakeups", t(($) => $.page.tabs.wakeups), AlarmClock, <WakeupsTab />, {
wide: true,
adminOnly: true,
diff --git a/packages/views/workflows/column-handoff.tsx b/packages/views/workflows/column-handoff.tsx
new file mode 100644
index 0000000000..f0ec78c90f
--- /dev/null
+++ b/packages/views/workflows/column-handoff.tsx
@@ -0,0 +1,92 @@
+"use client";
+
+import { useState } from "react";
+import { Plus, Workflow } from "lucide-react";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { statusAcceptsHandoff, workflowStep } from "@multica/core/issue-workflows";
+import { useActorName } from "@multica/core/workspace/hooks";
+import type { IssueWorkflow, Project } from "@multica/core/types";
+import { Popover, PopoverContent, PopoverTrigger } from "@multica/ui/components/ui/popover";
+import { ActorAvatar } from "../common/actor-avatar";
+import { useStatusLabel } from "../issues/utils/status-label";
+import { useT } from "../i18n";
+import { useWorkflowSharing, WorkflowHandoffForm } from "./handoff-form";
+import { useWorkflowPermissions } from "./permissions";
+import { stepHandlerActor, useStepHandlerLabel } from "./step-handler";
+
+/**
+ * A project board column's handoff (MUL-7420): the handler badge, or a
+ * "Hand to…" affordance for admins. Either opens the column's handoff form;
+ * it edits the workflow, so it says how many projects the change reaches.
+ */
+export function ColumnHandoff({
+ status,
+ workflow,
+ project,
+}: {
+ status: string;
+ workflow: IssueWorkflow;
+ project: Project;
+}) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const labelOf = useStatusLabel(wsId);
+ const handlerLabel = useStepHandlerLabel(project);
+ const { getActorName } = useActorName();
+ const { isAdmin } = useWorkflowPermissions(project);
+ const [open, setOpen] = useState(false);
+ const sharing = useWorkflowSharing(workflow, project.id);
+ const step = workflowStep(workflow, status);
+ if (!step || !statusAcceptsHandoff(status)) return null;
+ const label = handlerLabel(step);
+ if (!label && !isAdmin) return null;
+ const actor = stepHandlerActor(step, project);
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger
+ render={
+ label ? (
+ <button
+ type="button"
+ className="inline-flex min-w-0 max-w-32 items-center gap-1 rounded-full border border-surface-border bg-background/70 py-0.5 pl-0.5 pr-2 text-caption transition-colors hover:bg-accent"
+ aria-label={t(($) => $.workflows.hands_off_to, { name: label })}
+ title={t(($) => $.workflows.hands_off_to, { name: label })}
+ >
+ {actor && <ActorAvatar actorType={actor.type} actorId={actor.id} size="xs" profileLink={false} />}
+ <span className="truncate">{actor ? getActorName(actor.type, actor.id) : label}</span>
+ </button>
+ ) : (
+ <button
+ type="button"
+ className="inline-flex items-center gap-0.5 rounded-full px-1.5 py-0.5 text-caption text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground focus-visible:opacity-100 group-hover/column:opacity-100 data-popup-open:opacity-100"
+ >
+ <Plus aria-hidden className="size-3" />
+ {t(($) => $.workflows.handoff.add)}
+ </button>
+ )
+ }
+ />
+ <PopoverContent align="end" className="w-[26rem] max-w-[calc(100vw-2rem)] p-4">
+ <div className="mb-3 space-y-0.5">
+ <p className="text-body font-medium">{t(($) => $.workflows.handoff.title, { status: labelOf(status) })}</p>
+ <p className="flex items-start gap-1.5 text-caption text-muted-foreground">
+ <Workflow aria-hidden className="mt-0.5 size-3 shrink-0" />
+ <span>
+ {sharing.others.length > 0
+ ? t(($) => $.workflows.handoff.scope_line_shared, { workflow: workflow.name, projects: sharing.label })
+ : t(($) => $.workflows.handoff.scope_line, { workflow: workflow.name })}
+ </span>
+ </p>
+ </div>
+ <WorkflowHandoffForm
+ workflow={workflow}
+ statusKey={status}
+ canEdit={isAdmin}
+ project={project}
+ onSaved={() => setOpen(false)}
+ />
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/packages/views/workflows/handoff-confirm-dialog.test.tsx b/packages/views/workflows/handoff-confirm-dialog.test.tsx
new file mode 100644
index 0000000000..6d75f64da9
--- /dev/null
+++ b/packages/views/workflows/handoff-confirm-dialog.test.tsx
@@ -0,0 +1,111 @@
+// @vitest-environment jsdom
+
+import { cleanup, fireEvent, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { buildIssueStatusCatalog } from "@multica/core/issue-statuses";
+import type { WorkflowHandoffPreview } from "@multica/core/types";
+import { renderWithI18n } from "../test/i18n";
+import { WorkflowHandoffConfirmDialog } from "./handoff-confirm-dialog";
+
+const previewWorkflowHandoff = vi.fn<(issueId: string, status: string) => Promise<WorkflowHandoffPreview>>();
+
+vi.mock("@multica/core/api", () => ({
+ api: { previewWorkflowHandoff: (issueId: string, status: string) => previewWorkflowHandoff(issueId, status) },
+}));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+vi.mock("@multica/core/issue-statuses/hooks", () => ({
+ useIssueStatuses: () =>
+ buildIssueStatusCatalog([
+ { id: "a", workspace_id: "ws-1", key: "implement", name: "Implement", description: "", category: "started", color: "#3b82f6", is_system: false, position: 1, archived_at: null, created_at: "", updated_at: "" },
+ { id: "b", workspace_id: "ws-1", key: "code_review", name: "Code review", description: "", category: "started", color: "#a855f7", is_system: false, position: 2, archived_at: null, created_at: "", updated_at: "" },
+ ]),
+}));
+vi.mock("@multica/core/workspace/hooks", () => ({
+ useActorName: () => ({ getActorName: (_type: string, id: string) => ({ forge: "Forge", sentinel: "Sentinel" })[id] ?? "?" }),
+}));
+vi.mock("../common/actor-avatar", () => ({
+ ActorAvatar: ({ actorId }: { actorId: string }) => <span data-testid={`avatar-${actorId}`} />,
+}));
+
+const handoff: WorkflowHandoffPreview = {
+ handoff: true,
+ workflow_name: "Delivery",
+ from_status: "implement",
+ to_status: "code_review",
+ handler_type: "agent",
+ handler_id: "sentinel",
+ previous_assignee_type: "agent",
+ previous_assignee_id: "forge",
+ previous_runs: [{ task_id: "t1", agent_id: "forge", status: "running", started_at: new Date(Date.now() - 6 * 60_000).toISOString() }],
+ brief: "This project's workflow — Delivery\nReview the PR.",
+};
+
+function renderDialog(onConfirm = vi.fn(), onCancel = vi.fn()) {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ renderWithI18n(
+ <QueryClientProvider client={qc}>
+ <WorkflowHandoffConfirmDialog
+ issue={{ id: "issue-1", identifier: "MUL-8121" }}
+ toStatus="code_review"
+ onCancel={onCancel}
+ onConfirm={onConfirm}
+ />
+ </QueryClientProvider>,
+ );
+ return { onConfirm, onCancel };
+}
+
+afterEach(() => {
+ cleanup();
+ previewWorkflowHandoff.mockReset();
+});
+
+describe("WorkflowHandoffConfirmDialog (MUL-7420)", () => {
+ it("names the handoff, warns about the running agent and stops it by default", async () => {
+ previewWorkflowHandoff.mockResolvedValue(handoff);
+ const { onConfirm } = renderDialog();
+
+ expect(await screen.findByText(/Move MUL-8121 to “Code review”\?/)).toBeTruthy();
+ expect(await screen.findByText(/who starts working right away/)).toBeTruthy();
+ expect(screen.getByTestId("avatar-forge")).toBeTruthy();
+ expect(screen.getByTestId("avatar-sentinel")).toBeTruthy();
+ expect(screen.getByText(/Forge is still running \(for 6 minutes\)/)).toBeTruthy();
+ expect(screen.queryByText(/Review the PR\./)).toBeNull();
+ fireEvent.click(screen.getByRole("button", { expanded: false }));
+ expect(screen.getByText(/Review the PR\./)).toBeTruthy();
+ expect(previewWorkflowHandoff).toHaveBeenCalledWith("issue-1", "code_review");
+
+ fireEvent.click(screen.getByRole("button", { name: "Move to Code review" }));
+ expect(onConfirm).toHaveBeenCalledWith({ stopPreviousRuns: true });
+ });
+
+ it("keeps the previous run when the stop box is cleared", async () => {
+ previewWorkflowHandoff.mockResolvedValue(handoff);
+ const { onConfirm } = renderDialog();
+ fireEvent.click(await screen.findByRole("checkbox"));
+ fireEvent.click(screen.getByRole("button", { name: "Move to Code review" }));
+ expect(onConfirm).toHaveBeenCalledWith({ stopPreviousRuns: false });
+ });
+
+ it("words a run that has not started as queued and cancels it", async () => {
+ previewWorkflowHandoff.mockResolvedValue({
+ ...handoff,
+ previous_runs: [{ task_id: "t1", agent_id: "forge", status: "queued", started_at: new Date().toISOString() }],
+ });
+ const { onConfirm } = renderDialog();
+
+ expect(await screen.findByText(/Forge’s run is still queued/)).toBeTruthy();
+ expect(screen.queryByText(/still running/)).toBeNull();
+ expect(screen.getByText(/Cancel Forge’s queued run/)).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: "Move to Code review" }));
+ expect(onConfirm).toHaveBeenCalledWith({ stopPreviousRuns: true });
+ });
+
+ it("applies without asking when the server finds no handoff", async () => {
+ previewWorkflowHandoff.mockResolvedValue({ ...handoff, handoff: false, handler_type: null, handler_id: null });
+ const { onConfirm } = renderDialog();
+ await waitFor(() => expect(onConfirm).toHaveBeenCalledWith({ stopPreviousRuns: false }));
+ expect(screen.queryByText(/Move MUL-8121/)).toBeNull();
+ });
+});
diff --git a/packages/views/workflows/handoff-confirm-dialog.tsx b/packages/views/workflows/handoff-confirm-dialog.tsx
new file mode 100644
index 0000000000..55f62846d9
--- /dev/null
+++ b/packages/views/workflows/handoff-confirm-dialog.tsx
@@ -0,0 +1,245 @@
+"use client";
+
+import { Fragment, useEffect, useState, type ReactNode } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { ArrowRight, ChevronDown, ChevronRight, TriangleAlert } from "lucide-react";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { workflowHandoffPreviewOptions } from "@multica/core/issue-workflows";
+import { useActorName } from "@multica/core/workspace/hooks";
+import { Button } from "@multica/ui/components/ui/button";
+import { Checkbox } from "@multica/ui/components/ui/checkbox";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { Spinner } from "@multica/ui/components/ui/spinner";
+import { ActorAvatar } from "../common/actor-avatar";
+import { StatusIcon } from "../issues/components/status-icon";
+import { useStatusLabel } from "../issues/utils/status-label";
+import { useT } from "../i18n";
+import { BriefBlock } from "./handoff-form";
+
+const FROM = "⁣from⁣";
+const TO = "⁣to⁣";
+
+/** Replaces the FROM/TO markers of an interpolated sentence with nodes. */
+function withChips(text: string, chips: { from?: ReactNode; to: ReactNode }): ReactNode[] {
+ return text.split(/(⁣from⁣|⁣to⁣)/).map((part, i) => {
+ if (part === FROM) return <Fragment key={i}>{chips.from}</Fragment>;
+ if (part === TO) return <Fragment key={i}>{chips.to}</Fragment>;
+ return <Fragment key={i}>{part}</Fragment>;
+ });
+}
+
+function useDuration() {
+ const { t } = useT("issues");
+ return (since: string | null) => {
+ if (!since) return t(($) => $.workflows.confirm.under_minute);
+ const minutes = Math.floor((Date.now() - new Date(since).getTime()) / 60_000);
+ if (minutes < 1) return t(($) => $.workflows.confirm.under_minute);
+ if (minutes < 60) return t(($) => $.workflows.confirm.minutes, { count: minutes });
+ return t(($) => $.workflows.confirm.hours, { count: Math.floor(minutes / 60) });
+ };
+}
+
+/**
+ * Confirms a status change that hands the issue off (MUL-7420): who it goes
+ * from and to, whether the previous agent is still running (with a default-on
+ * option to stop it), and the brief the new handler receives. The facts come
+ * from the server preview, so they match what the write will do.
+ *
+ * With `toProject` it confirms moving the issue into that project instead:
+ * the issue enters the column it lands on there.
+ *
+ * When the preview finds no handoff after all (the handler cannot be resolved,
+ * or the workflow changed), the move applies without asking.
+ */
+export function WorkflowHandoffConfirmDialog({
+ issue,
+ toStatus,
+ toProject,
+ onCancel,
+ onConfirm,
+}: {
+ /** The issue being moved; null keeps the dialog closed. */
+ issue: { id: string; identifier: string } | null;
+ /** The status being moved to; ignored with `toProject`. */
+ toStatus: string;
+ toProject?: { id: string; title: string } | null;
+ onCancel: () => void;
+ onConfirm: (options: { stopPreviousRuns: boolean }) => void;
+}) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const catalog = useIssueStatuses(wsId);
+ const labelOf = useStatusLabel(wsId);
+ const { getActorName } = useActorName();
+ const duration = useDuration();
+ const [stop, setStop] = useState(true);
+ const [briefOpen, setBriefOpen] = useState(false);
+ const open = issue !== null;
+ const { data: preview, isPending, isError } = useQuery({
+ ...workflowHandoffPreviewOptions(wsId, issue?.id ?? "", toProject ? "" : toStatus, toProject?.id),
+ enabled: open,
+ });
+ const target = toProject ? (preview?.to_status ?? "") : toStatus;
+
+ useEffect(() => {
+ if (open) {
+ setStop(true);
+ setBriefOpen(false);
+ }
+ }, [open, issue?.id, toStatus, toProject?.id]);
+
+ // Nothing to confirm: apply as an ordinary status change.
+ useEffect(() => {
+ if (open && preview && !preview.handoff) onConfirm({ stopPreviousRuns: false });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open, preview]);
+
+ const status = (key: string) => (
+ <span className="inline-flex items-center gap-1">
+ <StatusIcon
+ status={key}
+ category={catalog.categoryOf(key)}
+ color={catalog.colorOf(key)}
+ icon={catalog.iconOf(key)}
+ className="h-3 w-3"
+ />
+ {labelOf(key)}
+ </span>
+ );
+ const chip = (type: string, id: string) => (
+ <span className="mx-0.5 inline-flex items-center gap-1.5 align-middle font-medium">
+ <ActorAvatar actorType={type} actorId={id} size="xs" profileLink={false} />
+ {getActorName(type, id)}
+ </span>
+ );
+
+ const handlerType = preview?.handler_type ?? null;
+ const handlerId = preview?.handler_id ?? null;
+ const handlerName = handlerType && handlerId ? getActorName(handlerType, handlerId) : "";
+ const prevType = preview?.previous_assignee_type ?? null;
+ const prevId = preview?.previous_assignee_id ?? null;
+ const sameHandler = !!prevId && prevId === handlerId && prevType === handlerType;
+ const runs = preview?.previous_runs ?? [];
+ // A queued run has not started yet: stopping it cancels rather than
+ // interrupts, and there is no elapsed time to show.
+ const started = runs.some((run) => run.status === "running" || run.status === "dispatched");
+ const oldestRun = runs.reduce<string | null>(
+ (oldest, run) => (!oldest || (run.started_at && run.started_at < oldest) ? run.started_at : oldest),
+ null,
+ );
+ const prevName = prevType && prevId ? getActorName(prevType, prevId) : "";
+
+ let sentence: ReactNode = null;
+ if (preview?.handoff && handlerType && handlerId) {
+ if (sameHandler) {
+ sentence = withChips(t(($) => $.workflows.confirm.same_handler_run, { to: TO }), { to: chip(handlerType, handlerId) });
+ } else {
+ const text =
+ handlerType === "member"
+ ? t(($) => $.workflows.confirm.reassign, { from: FROM, to: TO })
+ : t(($) => $.workflows.confirm.reassign_run, { from: FROM, to: TO });
+ sentence = withChips(text, {
+ from: prevType && prevId ? chip(prevType, prevId) : <span className="font-medium">{t(($) => $.workflows.confirm.unassigned)}</span>,
+ to: chip(handlerType, handlerId),
+ });
+ }
+ }
+
+ return (
+ <Dialog open={open && !(preview && !preview.handoff)} onOpenChange={(v) => !v && onCancel()}>
+ <DialogContent className="sm:max-w-xl">
+ <DialogHeader>
+ <DialogTitle>
+ {toProject
+ ? t(($) => $.workflows.confirm.project_title, { issue: issue?.identifier ?? "", project: toProject.title })
+ : t(($) => $.workflows.confirm.title, { issue: issue?.identifier ?? "", status: labelOf(toStatus) })}
+ </DialogTitle>
+ <DialogDescription className="flex flex-wrap items-center gap-1.5">
+ {preview && preview.from_status !== target && status(preview.from_status)}
+ {preview && preview.from_status !== target && <ArrowRight aria-hidden className="size-3" />}
+ {target && status(target)}
+ {preview?.workflow_name && (
+ <>
+ <span aria-hidden className="text-muted-foreground">·</span>
+ <span>{preview.workflow_name}</span>
+ </>
+ )}
+ </DialogDescription>
+ </DialogHeader>
+
+ {isPending ? (
+ <div className="flex justify-center py-6">
+ <Spinner className="size-4" />
+ </div>
+ ) : isError ? (
+ <p className="text-body text-destructive">{t(($) => $.workflows.confirm.error)}</p>
+ ) : (
+ <div className="space-y-4">
+ {sentence && <div className="text-body leading-7">{sentence}</div>}
+ {runs.length > 0 && !sameHandler && (
+ <div className="rounded-lg border border-warning/30 bg-warning/10 px-3.5 py-3">
+ <p className="flex items-center gap-2 text-body font-medium">
+ <TriangleAlert aria-hidden className="size-3.5 shrink-0" />
+ {started
+ ? t(($) => $.workflows.confirm.running_title, { name: prevName, duration: duration(oldestRun) })
+ : t(($) => $.workflows.confirm.queued_title, { name: prevName })}
+ </p>
+ <label className="mt-2 flex cursor-pointer items-center gap-2 text-body">
+ <Checkbox checked={stop} onCheckedChange={(v) => setStop(v === true)} />
+ {started
+ ? t(($) => $.workflows.confirm.stop_label, { name: prevName })
+ : t(($) => $.workflows.confirm.cancel_queued_label, { name: prevName })}
+ </label>
+ <p className="ml-6 mt-1 text-caption leading-5 text-muted-foreground">
+ {started
+ ? t(($) => $.workflows.confirm.stop_hint)
+ : t(($) => $.workflows.confirm.queued_hint, { name: prevName })}
+ </p>
+ </div>
+ )}
+ {preview?.brief && (
+ <div>
+ <button
+ type="button"
+ onClick={() => setBriefOpen((v) => !v)}
+ aria-expanded={briefOpen}
+ className="flex items-center gap-1 text-caption font-medium text-brand hover:underline"
+ >
+ {briefOpen ? <ChevronDown aria-hidden className="size-3.5" /> : <ChevronRight aria-hidden className="size-3.5" />}
+ {t(($) => $.workflows.confirm.brief_toggle, { name: handlerName })}
+ </button>
+ {briefOpen && (
+ <div className="mt-2">
+ <BriefBlock brief={preview.brief} />
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+
+ <DialogFooter>
+ <Button variant="outline" onClick={onCancel}>
+ {t(($) => $.workflows.confirm.cancel)}
+ </Button>
+ <Button
+ disabled={isPending || isError}
+ onClick={() => onConfirm({ stopPreviousRuns: stop && runs.length > 0 && !sameHandler })}
+ >
+ {toProject
+ ? t(($) => $.workflows.confirm.project_confirm, { project: toProject.title })
+ : t(($) => $.workflows.confirm.confirm, { status: labelOf(toStatus) })}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/views/workflows/handoff-form.test.tsx b/packages/views/workflows/handoff-form.test.tsx
new file mode 100644
index 0000000000..375ae0b3e1
--- /dev/null
+++ b/packages/views/workflows/handoff-form.test.tsx
@@ -0,0 +1,159 @@
+// @vitest-environment jsdom
+
+import { cleanup, fireEvent, screen } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { buildIssueStatusCatalog } from "@multica/core/issue-statuses";
+import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";
+import { projectListOptions } from "@multica/core/projects/queries";
+import type { IssueWorkflow, IssueWorkflowStep } from "@multica/core/types";
+import { renderWithI18n } from "../test/i18n";
+import { HandoffFields, WorkflowHandoffForm } from "./handoff-form";
+
+const { mutateAsync } = vi.hoisted(() => ({ mutateAsync: vi.fn() }));
+
+vi.mock("@multica/core/api", () => ({ api: {}, clientErrorMessage: () => null }));
+vi.mock("@multica/core/issue-workflows", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/issue-workflows")>()),
+ useSetWorkflowHandoff: () => ({ mutateAsync, isPending: false }),
+}));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+vi.mock("@multica/core/issue-statuses/hooks", () => ({ useIssueStatuses: () => buildIssueStatusCatalog([]) }));
+vi.mock("../common/actor-avatar", () => ({
+ ActorAvatar: ({ actorId }: { actorId: string }) => <span data-testid={`avatar-${actorId}`} />,
+}));
+
+const WORKFLOW = {
+ steps: ["todo", "in_progress", "in_review", "done"].map((status_key) => ({
+ status_key,
+ handler: { type: "none" as const },
+ instructions: "",
+ })),
+};
+
+function renderFields(step: IssueWorkflowStep, onPatch = vi.fn()) {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ qc.setQueryData(agentListOptions("ws-1").queryKey, [{ id: "agent-1", name: "Builder", archived_at: null }] as never);
+ qc.setQueryData(memberListOptions("ws-1").queryKey, [{ user_id: "user-1", name: "Ada" }] as never);
+ renderWithI18n(
+ <QueryClientProvider client={qc}>
+ <HandoffFields step={step} workflow={WORKFLOW} canEdit onPatch={onPatch} />
+ </QueryClientProvider>,
+ );
+ return onPatch;
+}
+
+afterEach(cleanup);
+
+describe("HandoffFields", () => {
+ it("offers no handoff, an agent or a member — never a squad", () => {
+ const onPatch = renderFields({ status_key: "in_progress", handler: { type: "none" }, instructions: "" });
+
+ const radios = screen.getAllByRole("radio");
+ expect(radios.map((r) => r.textContent)).toEqual([
+ expect.stringContaining("No handoff"),
+ expect.stringContaining("Hand to an agent"),
+ expect.stringContaining("Hand to a member"),
+ ]);
+ expect(screen.queryByText(/squad/i)).toBeNull();
+ fireEvent.click(screen.getByRole("radio", { name: /Hand to an agent/ }));
+
+ expect(onPatch).toHaveBeenCalledWith({ handler: { type: "agent" } });
+ });
+
+ it("lists only agents for an agent handoff", async () => {
+ const onPatch = renderFields({ status_key: "in_progress", handler: { type: "agent" }, instructions: "" });
+
+ fireEvent.click(screen.getByRole("button", { name: "Choose an agent" }));
+ fireEvent.click(await screen.findByText("Builder"));
+ expect(screen.queryByText("Ada")).toBeNull();
+ expect(screen.queryByText("Project lead")).toBeNull();
+
+ expect(onPatch).toHaveBeenCalledWith({ handler: { type: "agent", id: "agent-1" } });
+ });
+
+ it("lists the project lead and members for a member handoff, without instructions", async () => {
+ const onPatch = renderFields({ status_key: "in_review", handler: { type: "member" }, instructions: "" });
+
+ expect(screen.queryByRole("textbox")).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "Choose a member" }));
+ expect(await screen.findByText("Project lead")).toBeTruthy();
+ expect(screen.queryByText("Builder")).toBeNull();
+ fireEvent.click(screen.getByText("Ada"));
+
+ expect(onPatch).toHaveBeenCalledWith({ handler: { type: "member", id: "user-1" } });
+ });
+
+ it("shows next and back for an agent, next defaulting to the next column", () => {
+ renderFields({ status_key: "in_progress", handler: { type: "agent", id: "agent-1" }, instructions: "" });
+
+ expect(screen.getAllByRole("combobox").length).toBe(2);
+ expect(screen.getByText(/In Review/)).toBeTruthy();
+ });
+});
+
+describe("WorkflowHandoffForm", () => {
+ const PROJECTS = [
+ { id: "p-pay", title: "Payments" },
+ { id: "p-orders", title: "Orders" },
+ ];
+ const workflow = (projectIds: string[]): IssueWorkflow =>
+ ({
+ id: "wf-1",
+ workspace_id: "ws-1",
+ name: "Delivery",
+ description: "",
+ is_default: false,
+ steps: WORKFLOW.steps,
+ project_ids: projectIds,
+ created_at: "",
+ updated_at: "",
+ }) as IssueWorkflow;
+
+ function renderForm(wf: IssueWorkflow) {
+ mutateAsync.mockReset().mockResolvedValue({ ...wf, name: "Delivery (Payments)" });
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ qc.setQueryData(agentListOptions("ws-1").queryKey, [{ id: "agent-1", name: "Builder", archived_at: null }] as never);
+ qc.setQueryData(memberListOptions("ws-1").queryKey, [] as never);
+ qc.setQueryData(projectListOptions("ws-1").queryKey, { projects: PROJECTS } as never);
+ renderWithI18n(
+ <QueryClientProvider client={qc}>
+ <WorkflowHandoffForm workflow={wf} statusKey="in_progress" canEdit project={PROJECTS[0]} />
+ </QueryClientProvider>,
+ );
+ }
+
+ async function handToBuilder() {
+ fireEvent.click(screen.getByRole("radio", { name: /Hand to an agent/ }));
+ fireEvent.click(screen.getByRole("button", { name: "Choose an agent" }));
+ fireEvent.click(await screen.findByText("Builder"));
+ }
+
+ it("asks where a change to a shared workflow applies, and can keep it to this project", async () => {
+ renderForm(workflow(["p-pay", "p-orders"]));
+ expect(screen.queryByText("Where should this change apply?")).toBeNull();
+
+ await handToBuilder();
+ expect(screen.getByRole("radio", { name: /All 2 projects using Delivery/ })).toBeTruthy();
+ fireEvent.click(screen.getByRole("radio", { name: /Only Payments/ }));
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ await vi.waitFor(() => expect(mutateAsync).toHaveBeenCalled());
+ expect(mutateAsync.mock.calls[0]![0]).toMatchObject({
+ workflowId: "wf-1",
+ handler: { type: "agent", id: "agent-1" },
+ copyForProjectId: "p-pay",
+ });
+ });
+
+ it("saves to the workflow directly when only this project uses it", async () => {
+ renderForm(workflow(["p-pay"]));
+
+ await handToBuilder();
+ expect(screen.queryByText("Where should this change apply?")).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ await vi.waitFor(() => expect(mutateAsync).toHaveBeenCalled());
+ expect(mutateAsync.mock.calls[0]![0].copyForProjectId).toBeUndefined();
+ });
+});
diff --git a/packages/views/workflows/handoff-form.tsx b/packages/views/workflows/handoff-form.tsx
new file mode 100644
index 0000000000..f9815dd5ed
--- /dev/null
+++ b/packages/views/workflows/handoff-form.tsx
@@ -0,0 +1,642 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { api, clientErrorMessage } from "@multica/core/api";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { useSetWorkflowHandoff, workflowNextStatus } from "@multica/core/issue-workflows";
+import { projectListOptions } from "@multica/core/projects/queries";
+import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";
+import type { IssueWorkflow, IssueWorkflowStep, Project } from "@multica/core/types";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+} from "@multica/ui/components/ui/select";
+import { Spinner } from "@multica/ui/components/ui/spinner";
+import { Textarea } from "@multica/ui/components/ui/textarea";
+import { cn } from "@multica/ui/lib/utils";
+import { ChevronDown } from "lucide-react";
+import { ActorAvatar } from "../common/actor-avatar";
+import { PickerEmpty, PickerItem, PickerSection, PropertyPicker } from "../issues/components/pickers/property-picker";
+import { StatusIcon } from "../issues/components/status-icon";
+import { useStatusLabel } from "../issues/utils/status-label";
+import { useT } from "../i18n";
+
+const NOT_SET = "__not_set__";
+
+type HandoffMode = "none" | "agent" | "member";
+
+function modeOf(handler: IssueWorkflowStep["handler"]): HandoffMode {
+ if (handler.type === "agent") return "agent";
+ if (handler.type === "member" || handler.type === "project_lead") return "member";
+ return "none";
+}
+
+/**
+ * The parts of a handoff that are saved. Instructions and next/back statuses
+ * only reach an agent's brief, so they are kept for agent handoffs alone.
+ */
+export function savedHandoff<T extends Pick<IssueWorkflowStep, "handler" | "instructions" | "next_status_key" | "back_status_key">>(
+ step: T,
+): T {
+ if (step.handler.type === "agent") return step;
+ return { ...step, instructions: "", next_status_key: undefined, back_status_key: undefined };
+}
+
+function sameStep(a: IssueWorkflowStep, b: IssueWorkflowStep): boolean {
+ return (
+ a.handler.type === b.handler.type &&
+ (a.handler.id ?? "") === (b.handler.id ?? "") &&
+ a.instructions === b.instructions &&
+ (a.next_status_key ?? "") === (b.next_status_key ?? "") &&
+ (a.back_status_key ?? "") === (b.back_status_key ?? "")
+ );
+}
+
+/**
+ * The other projects using `workflow` besides `projectId`, and a short label
+ * naming them ("A、B" or "A、B、C and 2 more").
+ */
+export function useWorkflowSharing(workflow: IssueWorkflow, projectId: string | undefined) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const { data: projects = [] } = useQuery(projectListOptions(wsId));
+ return useMemo(() => {
+ const others = workflow.project_ids
+ .filter((id) => id !== projectId)
+ .map((id) => projects.find((p) => p.id === id))
+ .filter((p): p is Project => !!p);
+ const separator = t(($) => $.workflows.list_separator);
+ const names = others.slice(0, 3).map((p) => p.title).join(separator);
+ const label =
+ others.length > 3 ? t(($) => $.workflows.handoff.scope_more, { names, count: others.length }) : names;
+ return { others, label };
+ }, [workflow.project_ids, projectId, projects, t]);
+}
+
+type SaveScope = "all" | "project";
+
+/**
+ * One column's handoff (MUL-7420): who entering the column hands the issue
+ * to, what they are told, and where it goes next. It belongs to the workflow,
+ * so saving applies to every project using it — unless, opened from one of
+ * several projects sharing a named workflow, the admin chooses to keep the
+ * change to that project: it then lands on a copy of the workflow only that
+ * project uses. The board's column popover and the full-flow panel both
+ * render this form.
+ */
+export function WorkflowHandoffForm({
+ workflow,
+ statusKey,
+ canEdit,
+ project,
+ onSaved,
+}: {
+ workflow: IssueWorkflow;
+ statusKey: string;
+ canEdit: boolean;
+ /** The project the form is opened from: the brief preview is for it. */
+ project?: Pick<Project, "id" | "title">;
+ onSaved?: () => void;
+}) {
+ const { t } = useT("issues");
+ const sharing = useWorkflowSharing(workflow, project?.id);
+ const [scope, setScope] = useState<SaveScope>("all");
+ const saved = useMemo<IssueWorkflowStep>(
+ () =>
+ workflow.steps.find((s) => s.status_key === statusKey) ?? {
+ status_key: statusKey,
+ handler: { type: "none" },
+ instructions: "",
+ },
+ [statusKey, workflow.steps],
+ );
+ const [draft, setDraft] = useState<IssueWorkflowStep>(saved);
+ const [previewOpen, setPreviewOpen] = useState(false);
+ const setHandoff = useSetWorkflowHandoff();
+ useEffect(() => setDraft(saved), [saved]);
+
+ const handler = draft.handler;
+ const needsTarget = (handler.type === "agent" || handler.type === "member") && !handler.id;
+ const dirty = !sameStep(savedHandoff(draft), savedHandoff(saved));
+ const askScope = canEdit && dirty && !!project && !workflow.is_default && sharing.others.length > 0;
+ useEffect(() => {
+ if (!dirty) setScope("all");
+ }, [dirty]);
+
+ const save = async () => {
+ const out = savedHandoff(draft);
+ const copyFor = askScope && scope === "project" ? project : undefined;
+ try {
+ const result = await setHandoff.mutateAsync({
+ workflowId: workflow.id,
+ statusKey,
+ handler: out.handler,
+ instructions: out.instructions,
+ next_status_key: out.next_status_key,
+ back_status_key: out.back_status_key,
+ copyForProjectId: copyFor?.id,
+ });
+ toast.success(
+ copyFor
+ ? t(($) => $.workflows.handoff.saved_copy, { workflow: result.name, project: copyFor.title })
+ : t(($) => $.workflows.handoff.saved),
+ );
+ onSaved?.();
+ } catch (err) {
+ toast.error(clientErrorMessage(err) ?? t(($) => $.workflows.handoff.error));
+ }
+ };
+
+ return (
+ <div className="space-y-4">
+ <HandoffFields
+ step={draft}
+ workflow={workflow}
+ canEdit={canEdit}
+ onPatch={(patch) => setDraft((d) => ({ ...d, ...patch }))}
+ onPreview={() => setPreviewOpen(true)}
+ />
+ {askScope && project && (
+ <div className="rounded-lg border border-surface-border bg-muted/40 p-2">
+ <p className="px-1.5 pb-1.5 pt-0.5 text-caption font-medium text-muted-foreground">
+ {t(($) => $.workflows.handoff.scope_question)}
+ </p>
+ <div role="radiogroup" aria-label={t(($) => $.workflows.handoff.scope_question)} className="space-y-1">
+ <ScopeOption
+ selected={scope === "all"}
+ onSelect={() => setScope("all")}
+ title={t(($) => $.workflows.handoff.scope_all, {
+ workflow: workflow.name,
+ count: sharing.others.length + 1,
+ })}
+ hint={t(($) => $.workflows.handoff.scope_all_hint, {
+ projects: [project.title, sharing.label].join(t(($) => $.workflows.list_separator)),
+ })}
+ />
+ <ScopeOption
+ selected={scope === "project"}
+ onSelect={() => setScope("project")}
+ title={t(($) => $.workflows.handoff.scope_project, { project: project.title })}
+ hint={t(($) => $.workflows.handoff.scope_project_hint, {
+ copy: `${workflow.name} (${project.title})`,
+ project: project.title,
+ })}
+ />
+ </div>
+ </div>
+ )}
+ {canEdit ? (
+ <div className="flex items-center justify-end gap-2">
+ {dirty && (
+ <Button variant="ghost" size="sm" onClick={() => setDraft(saved)}>
+ {t(($) => $.workflows.editor.cancel)}
+ </Button>
+ )}
+ <Button size="sm" onClick={() => void save()} disabled={!dirty || needsTarget || setHandoff.isPending}>
+ {setHandoff.isPending && <Spinner className="size-3.5" />}
+ {t(($) => $.workflows.editor.save)}
+ </Button>
+ </div>
+ ) : (
+ <p className="text-caption text-muted-foreground">{t(($) => $.workflows.handoff.read_only)}</p>
+ )}
+ <BriefPreviewDialog
+ open={previewOpen}
+ onOpenChange={setPreviewOpen}
+ workflowId={workflow.id}
+ projectId={project?.id}
+ step={draft}
+ />
+ </div>
+ );
+}
+
+function RadioDot({ selected }: { selected: boolean }) {
+ return (
+ <span
+ aria-hidden
+ className={cn(
+ "mt-0.5 flex size-4 shrink-0 items-center justify-center rounded-full border",
+ selected ? "border-brand" : "border-input",
+ )}
+ >
+ {selected && <span className="size-2 rounded-full bg-brand" />}
+ </span>
+ );
+}
+
+function ScopeOption({
+ selected,
+ onSelect,
+ title,
+ hint,
+}: {
+ selected: boolean;
+ onSelect: () => void;
+ title: string;
+ hint: string;
+}) {
+ return (
+ <button
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ onClick={onSelect}
+ className={cn(
+ "flex w-full items-start gap-2.5 rounded-md px-2 py-1.5 text-left transition-colors",
+ selected ? "bg-background shadow-xs ring-1 ring-surface-border" : "hover:bg-accent/60",
+ )}
+ >
+ <RadioDot selected={selected} />
+ <span className="min-w-0">
+ <span className="block text-body font-medium">{title}</span>
+ <span className="block text-caption leading-5 text-muted-foreground">{hint}</span>
+ </span>
+ </button>
+ );
+}
+
+/** The handoff fields of one column; the caller owns saving. */
+export function HandoffFields({
+ step,
+ workflow,
+ canEdit,
+ onPatch,
+ onPreview,
+}: {
+ step: IssueWorkflowStep;
+ workflow: Pick<IssueWorkflow, "steps">;
+ canEdit: boolean;
+ onPatch: (patch: Partial<IssueWorkflowStep>) => void;
+ onPreview?: () => void;
+}) {
+ const { t } = useT("issues");
+ const mode = modeOf(step.handler);
+ const nextDefault = workflowNextStatus({ steps: workflow.steps.map((s) => ({ ...s, next_status_key: undefined })) }, step.status_key);
+ const choose = (m: HandoffMode) => {
+ if (m === mode) return;
+ onPatch({ handler: m === "none" ? { type: "none" } : { type: m } });
+ };
+ const options: { mode: HandoffMode; title: string; hint: string }[] = [
+ { mode: "none", title: t(($) => $.workflows.handoff.mode_none), hint: t(($) => $.workflows.handoff.mode_none_hint) },
+ { mode: "agent", title: t(($) => $.workflows.handoff.mode_agent), hint: t(($) => $.workflows.handoff.mode_agent_hint) },
+ { mode: "member", title: t(($) => $.workflows.handoff.mode_member), hint: t(($) => $.workflows.handoff.mode_member_hint) },
+ ];
+
+ return (
+ <div className="space-y-4">
+ <div role="radiogroup" aria-label={t(($) => $.workflows.handoff.to)} className="space-y-1.5">
+ {options.map((option) => {
+ const selected = option.mode === mode;
+ return (
+ <div
+ key={option.mode}
+ className={cn(
+ "rounded-lg border transition-colors",
+ selected ? "border-brand/50 bg-brand/5" : "border-surface-border",
+ )}
+ >
+ <button
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ disabled={!canEdit}
+ onClick={() => choose(option.mode)}
+ className="flex w-full items-start gap-2.5 px-3 py-2.5 text-left disabled:cursor-default"
+ >
+ <RadioDot selected={selected} />
+ <span className="min-w-0">
+ <span className="block text-body font-medium">{option.title}</span>
+ <span className="block text-caption text-muted-foreground">{option.hint}</span>
+ </span>
+ </button>
+ {selected && option.mode !== "none" && (
+ <div className="px-3 pb-3 pl-9">
+ <HandlerPicker
+ kind={option.mode}
+ value={step.handler}
+ disabled={!canEdit}
+ onChange={(handler) => onPatch({ handler })}
+ />
+ {step.handler.type === "project_lead" && (
+ <p className="mt-1.5 text-caption leading-5 text-muted-foreground">
+ {t(($) => $.workflows.handoff.project_lead_hint)}
+ </p>
+ )}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+
+ {mode === "agent" && (
+ <>
+ <Field
+ label={t(($) => $.workflows.handoff.instructions)}
+ hint={t(($) => $.workflows.editor.instructions_hint)}
+ htmlFor={`workflow-handoff-instructions-${step.status_key}`}
+ >
+ <Textarea
+ id={`workflow-handoff-instructions-${step.status_key}`}
+ rows={4}
+ maxLength={8000}
+ readOnly={!canEdit}
+ value={step.instructions}
+ placeholder={t(($) => $.workflows.editor.instructions_placeholder)}
+ onChange={(e) => onPatch({ instructions: e.target.value })}
+ />
+ </Field>
+ <NextBackFields
+ step={step}
+ workflow={workflow}
+ canEdit={canEdit}
+ nextDefault={nextDefault}
+ onPatch={onPatch}
+ onPreview={onPreview}
+ />
+ </>
+ )}
+ </div>
+ );
+}
+
+/**
+ * The agent, or the member (project lead included), a column hands the issue
+ * to. Squads are left out on purpose — they route work themselves. (MUL-7420)
+ */
+function HandlerPicker({
+ kind,
+ value,
+ disabled,
+ onChange,
+}: {
+ kind: "agent" | "member";
+ value: IssueWorkflowStep["handler"];
+ disabled: boolean;
+ onChange: (handler: IssueWorkflowStep["handler"]) => void;
+}) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const { data: agents = [] } = useQuery(agentListOptions(wsId));
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const q = query.trim().toLowerCase();
+ const matches = (name: string) => !q || name.toLowerCase().includes(q);
+ const agentRows = kind === "agent" ? agents.filter((a) => !a.archived_at && matches(a.name)) : [];
+ const memberRows = kind === "member" ? members.filter((m) => matches(m.name)) : [];
+ const leadLabel = t(($) => $.workflows.handler.project_lead);
+ const pick = (handler: IssueWorkflowStep["handler"]) => {
+ onChange(handler);
+ setOpen(false);
+ };
+ const is = (type: string, id?: string) => value.type === type && (id === undefined || value.id === id);
+ const current =
+ value.type === "project_lead"
+ ? leadLabel
+ : value.id
+ ? (value.type === "agent" ? agents.find((a) => a.id === value.id)?.name : members.find((m) => m.user_id === value.id)?.name) ?? ""
+ : "";
+ const placeholder = kind === "agent" ? t(($) => $.workflows.handoff.pick_agent) : t(($) => $.workflows.handoff.pick_member);
+
+ return (
+ <PropertyPicker
+ open={open && !disabled}
+ onOpenChange={setOpen}
+ align="start"
+ width="w-72"
+ searchable
+ searchPlaceholder={kind === "agent" ? t(($) => $.workflows.handoff.search_agents) : t(($) => $.workflows.handoff.search_members)}
+ onSearchChange={setQuery}
+ triggerRender={
+ <button
+ type="button"
+ disabled={disabled}
+ aria-label={placeholder}
+ className="flex h-8 w-full items-center gap-2 rounded-md border border-input bg-background px-2.5 text-left text-body disabled:cursor-default"
+ />
+ }
+ trigger={
+ <>
+ {(value.type === "agent" || value.type === "member") && value.id && (
+ <ActorAvatar actorType={value.type} actorId={value.id} size="xs" profileLink={false} />
+ )}
+ <span className={cn("min-w-0 flex-1 truncate", !current && "text-muted-foreground")}>{current || placeholder}</span>
+ <ChevronDown aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
+ </>
+ }
+ >
+ {kind === "member" && !q && (
+ <PickerItem selected={is("project_lead")} onClick={() => pick({ type: "project_lead" })}>
+ <span className="truncate">{leadLabel}</span>
+ </PickerItem>
+ )}
+ {agentRows.map((agent) => (
+ <PickerItem key={agent.id} selected={is("agent", agent.id)} onClick={() => pick({ type: "agent", id: agent.id })}>
+ <ActorAvatar actorType="agent" actorId={agent.id} size="xs" profileLink={false} />
+ <span className="truncate">{agent.name}</span>
+ </PickerItem>
+ ))}
+ {memberRows.length > 0 && (
+ <PickerSection label={t(($) => $.workflows.handoff.members)}>
+ {memberRows.map((member) => (
+ <PickerItem
+ key={member.user_id}
+ selected={is("member", member.user_id)}
+ onClick={() => pick({ type: "member", id: member.user_id })}
+ >
+ <ActorAvatar actorType="member" actorId={member.user_id} size="xs" profileLink={false} />
+ <span className="truncate">{member.name}</span>
+ </PickerItem>
+ ))}
+ </PickerSection>
+ )}
+ {agentRows.length === 0 && memberRows.length === 0 && (q || kind === "agent") && <PickerEmpty />}
+ </PropertyPicker>
+ );
+}
+
+function NextBackFields({
+ step,
+ workflow,
+ canEdit,
+ nextDefault,
+ onPatch,
+ onPreview,
+}: {
+ step: IssueWorkflowStep;
+ workflow: Pick<IssueWorkflow, "steps">;
+ canEdit: boolean;
+ nextDefault: string | null;
+ onPatch: (patch: Partial<IssueWorkflowStep>) => void;
+ onPreview?: () => void;
+}) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const catalog = useIssueStatuses(wsId);
+ const labelOf = useStatusLabel(wsId);
+ const others = workflow.steps.filter((s) => s.status_key !== step.status_key).map((s) => s.status_key);
+ const statusIcon = (key: string) => (
+ <StatusIcon
+ status={key}
+ category={catalog.categoryOf(key)}
+ color={catalog.colorOf(key)}
+ icon={catalog.iconOf(key)}
+ className="h-3.5 w-3.5 shrink-0"
+ />
+ );
+
+ return (
+ <div className="space-y-2">
+ <div className="grid gap-3 sm:grid-cols-2">
+ {(["next", "back"] as const).map((kind) => {
+ const field = kind === "next" ? "next_status_key" : "back_status_key";
+ const value = step[field];
+ const unsetLabel =
+ kind === "next" && nextDefault
+ ? t(($) => $.workflows.handoff.next_default, { status: labelOf(nextDefault) })
+ : t(($) => $.workflows.editor.none_option);
+ const options = [{ value: NOT_SET, label: unsetLabel }, ...others.map((key) => ({ value: key, label: labelOf(key) }))];
+ return (
+ <div key={kind} className="min-w-0 space-y-1.5">
+ <span className="block text-caption font-medium">{t(($) => $.workflows.editor[kind])}</span>
+ <Select
+ items={options}
+ value={value ?? NOT_SET}
+ disabled={!canEdit}
+ onValueChange={(v) => onPatch({ [field]: !v || v === NOT_SET ? undefined : v })}
+ >
+ <SelectTrigger aria-label={t(($) => $.workflows.editor[kind])} className="w-full">
+ {value ? (
+ <span className="flex min-w-0 items-center gap-2">
+ {statusIcon(value)}
+ <span className="truncate">{labelOf(value)}</span>
+ </span>
+ ) : (
+ <span className="truncate text-muted-foreground">{unsetLabel}</span>
+ )}
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ <span className="flex items-center gap-2">
+ {option.value !== NOT_SET && statusIcon(option.value)}
+ <span>{option.label}</span>
+ </span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ );
+ })}
+ </div>
+ <p className="text-caption leading-5 text-muted-foreground">
+ {t(($) => $.workflows.editor.next_hint)}
+ {onPreview && (
+ <>
+ {" "}
+ <button type="button" onClick={onPreview} className="text-brand hover:underline">
+ {t(($) => $.workflows.editor.preview_brief)}
+ </button>
+ </>
+ )}
+ </p>
+ </div>
+ );
+}
+
+function Field({
+ label,
+ hint,
+ htmlFor,
+ children,
+}: {
+ label: string;
+ hint?: string;
+ htmlFor?: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="space-y-1.5">
+ <label htmlFor={htmlFor} className="block text-caption font-medium">
+ {label}
+ </label>
+ {children}
+ {hint && <p className="text-caption leading-5 text-muted-foreground">{hint}</p>}
+ </div>
+ );
+}
+
+/**
+ * The brief a column's handler receives, rendered by the server from the
+ * unsaved handoff on the saved workflow.
+ */
+export function BriefPreviewDialog({
+ open,
+ onOpenChange,
+ workflowId,
+ projectId,
+ step,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ workflowId: string;
+ projectId?: string;
+ step: IssueWorkflowStep;
+}) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const labelOf = useStatusLabel(wsId);
+ const { data: brief, isPending } = useQuery({
+ queryKey: ["issue-workflows", wsId, "brief-preview", workflowId, projectId ?? "", JSON.stringify(step)],
+ queryFn: () =>
+ api.previewWorkflowBrief(workflowId, {
+ status_key: step.status_key,
+ ...(projectId ? { project_id: projectId } : {}),
+ handler: step.handler,
+ instructions: step.instructions,
+ next_status_key: step.next_status_key,
+ back_status_key: step.back_status_key,
+ }),
+ enabled: open,
+ });
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>{t(($) => $.workflows.editor.preview_title, { status: labelOf(step.status_key) })}</DialogTitle>
+ <DialogDescription>{t(($) => $.workflows.editor.preview_description)}</DialogDescription>
+ </DialogHeader>
+ <BriefBlock brief={brief} loading={isPending} />
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+/** A handoff brief, shown as the agent reads it. */
+export function BriefBlock({ brief, loading }: { brief: string | undefined; loading?: boolean }) {
+ return (
+ <div className="max-h-[50dvh] overflow-auto rounded-lg border border-surface-border bg-muted/40 p-4">
+ {loading ? (
+ <Spinner className="size-4" />
+ ) : (
+ <pre className="whitespace-pre-wrap break-words font-mono text-caption leading-5 text-foreground">{brief}</pre>
+ )}
+ </div>
+ );
+}
diff --git a/packages/views/workflows/index.ts b/packages/views/workflows/index.ts
new file mode 100644
index 0000000000..8159d73cd2
--- /dev/null
+++ b/packages/views/workflows/index.ts
@@ -0,0 +1,5 @@
+export { WorkflowsTab } from "./workflows-tab";
+export { WorkflowEditorPage } from "./workflow-editor-page";
+export { WorkflowMappingDialog } from "./workflow-mapping-dialog";
+export { ProjectWorkflowControl } from "./project-workflow-row";
+export { stepHandlerActor, useStepHandlerLabel } from "./step-handler";
diff --git a/packages/views/workflows/issue-flow-card.tsx b/packages/views/workflows/issue-flow-card.tsx
new file mode 100644
index 0000000000..f1e509d0f1
--- /dev/null
+++ b/packages/views/workflows/issue-flow-card.tsx
@@ -0,0 +1,82 @@
+"use client";
+
+import { Workflow } from "lucide-react";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { useProjectWithWorkflow } from "@multica/core/issue-workflows";
+import { Popover, PopoverContent, PopoverTrigger } from "@multica/ui/components/ui/popover";
+import { cn } from "@multica/ui/lib/utils";
+import { ActorAvatar } from "../common/actor-avatar";
+import { StatusIcon } from "../issues/components/status-icon";
+import { useStatusLabel } from "../issues/utils/status-label";
+import { useT } from "../i18n";
+import { stepHandlerActor, useStepHandlerLabel } from "./step-handler";
+
+/**
+ * The workflow an issue follows through its project (MUL-7420), opening a
+ * read-only card of its columns and who each hands to. It changes on the
+ * project, so nothing here edits it.
+ */
+export function IssueFlowCard({ projectId, currentStatus }: { projectId: string | null; currentStatus: string }) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const catalog = useIssueStatuses(wsId);
+ const labelOf = useStatusLabel(wsId);
+ const { project, workflow } = useProjectWithWorkflow(wsId, projectId);
+ const handlerLabel = useStepHandlerLabel(project);
+ if (!workflow || !project) return null;
+
+ return (
+ <Popover>
+ <PopoverTrigger
+ render={
+ <button
+ type="button"
+ className="-ml-1 inline-flex min-w-0 items-center gap-1.5 rounded-md px-1 py-0.5 text-caption transition-colors hover:bg-accent data-popup-open:bg-accent"
+ >
+ <Workflow aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate text-foreground">{workflow.name}</span>
+ <span className="shrink-0 text-muted-foreground">{t(($) => $.workflows.detail.follows_project)}</span>
+ </button>
+ }
+ />
+ <PopoverContent align="start" className="w-72 p-3">
+ <p className="mb-2 text-caption text-muted-foreground">
+ {t(($) => $.workflows.detail.card_title, { workflow: workflow.name, project: project.title })}
+ </p>
+ <ol className="space-y-0.5">
+ {workflow.steps.map((step) => {
+ const label = handlerLabel(step);
+ const actor = stepHandlerActor(step, project);
+ const current = step.status_key === currentStatus;
+ return (
+ <li
+ key={step.status_key}
+ className={cn("flex items-center gap-2 rounded-md px-2 py-1.5", current && "bg-accent")}
+ aria-current={current ? "step" : undefined}
+ >
+ <StatusIcon
+ status={step.status_key}
+ category={catalog.categoryOf(step.status_key)}
+ color={catalog.colorOf(step.status_key)}
+ icon={catalog.iconOf(step.status_key)}
+ className="h-3.5 w-3.5 shrink-0"
+ />
+ <span className={cn("min-w-0 flex-1 truncate text-body", current && "font-medium")}>
+ {labelOf(step.status_key)}
+ </span>
+ {label && (
+ <span className="flex min-w-0 items-center gap-1 text-caption text-muted-foreground">
+ {actor && <ActorAvatar actorType={actor.type} actorId={actor.id} size="xs" profileLink={false} />}
+ <span className="truncate">{label}</span>
+ </span>
+ )}
+ </li>
+ );
+ })}
+ </ol>
+ <p className="mt-2 text-caption text-muted-foreground">{t(($) => $.workflows.detail.card_hint)}</p>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/packages/views/workflows/permissions.ts b/packages/views/workflows/permissions.ts
new file mode 100644
index 0000000000..9cc4b34c06
--- /dev/null
+++ b/packages/views/workflows/permissions.ts
@@ -0,0 +1,25 @@
+"use client";
+
+import { useQuery } from "@tanstack/react-query";
+import { useAuthStore } from "@multica/core/auth";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { memberListOptions } from "@multica/core/workspace/queries";
+import type { Project } from "@multica/core/types";
+
+/**
+ * Who may change what in project workflows (MUL-7420), mirroring the server:
+ * only admins edit workflows and their handoffs; admins and a project's member
+ * lead switch the workflow the project uses.
+ */
+export function useWorkflowPermissions(project?: Pick<Project, "lead_type" | "lead_id"> | null): {
+ isAdmin: boolean;
+ canManageProject: boolean;
+} {
+ const wsId = useWorkspaceId();
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const userId = useAuthStore((s) => s.user?.id);
+ const role = members.find((m) => m.user_id === userId)?.role;
+ const isAdmin = role === "owner" || role === "admin";
+ const isLead = !!userId && project?.lead_type === "member" && project.lead_id === userId;
+ return { isAdmin, canManageProject: isAdmin || isLead };
+}
diff --git a/packages/views/workflows/project-workflow-menu.tsx b/packages/views/workflows/project-workflow-menu.tsx
new file mode 100644
index 0000000000..0dde4399ca
--- /dev/null
+++ b/packages/views/workflows/project-workflow-menu.tsx
@@ -0,0 +1,231 @@
+"use client";
+
+import { useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { ChevronDown, ChevronRight, ListTree, Settings, Workflow } from "lucide-react";
+import { useFeatureEnabled } from "@multica/core/config";
+import { PROJECT_WORKFLOWS_V1_FLAG } from "@multica/core/feature-flags";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import {
+ resolveProjectWorkflow,
+ statusAcceptsHandoff,
+ useIssueWorkflows,
+} from "@multica/core/issue-workflows";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { projectListOptions } from "@multica/core/projects/queries";
+import type { IssueWorkflow, Project } from "@multica/core/types";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@multica/ui/components/ui/sheet";
+import { cn } from "@multica/ui/lib/utils";
+import { ActorAvatar } from "../common/actor-avatar";
+import { StatusIcon } from "../issues/components/status-icon";
+import { useStatusLabel } from "../issues/utils/status-label";
+import { useNavigation } from "../navigation";
+import { useT } from "../i18n";
+import { WorkflowHandoffForm } from "./handoff-form";
+import { useWorkflowPermissions } from "./permissions";
+import { useProjectWorkflowSwitch, WorkflowChoiceItems } from "./project-workflow-row";
+import { stepHandlerActor, useStepHandlerLabel } from "./step-handler";
+
+/**
+ * The project board's "Workflow" menu (MUL-7420): open the full flow or switch
+ * workflows; workflows themselves are made in settings. Shown while workflows
+ * are on, or when the project already names one.
+ */
+export function ProjectWorkflowMenu({ project }: { project: Project }) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const navigation = useNavigation();
+ const paths = useWorkspacePaths();
+ const enabled = useFeatureEnabled(PROJECT_WORKFLOWS_V1_FLAG, false);
+ const { workflows } = useIssueWorkflows(wsId);
+ const { canManageProject, isAdmin } = useWorkflowPermissions(project);
+ const { choose, busy, dialog } = useProjectWorkflowSwitch(project);
+ const [flowOpen, setFlowOpen] = useState(false);
+ const workflow = resolveProjectWorkflow(workflows, project);
+
+ if (!workflow || (!enabled && !project.workflow_id)) return null;
+
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ disabled={busy}
+ render={
+ <Button variant="ghost" size="sm" className="gap-1.5 text-muted-foreground">
+ <Workflow className="size-3.5" />
+ <span className="max-w-40 truncate">{workflow.name}</span>
+ <ChevronDown className="size-3" />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end" className="w-64">
+ <DropdownMenuItem onClick={() => setFlowOpen(true)}>
+ <ListTree className="size-3.5" />
+ {t(($) => $.workflows.menu.view_flow)}
+ </DropdownMenuItem>
+ {canManageProject && (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <Workflow className="size-3.5" />
+ {t(($) => $.workflows.menu.switch)}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-80">
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{t(($) => $.workflows.project.picker_title)}</DropdownMenuLabel>
+ <WorkflowChoiceItems project={project} onChoose={(w) => void choose(w)} />
+ </DropdownMenuGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )}
+ {isAdmin && enabled && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={() => navigation.push(`${paths.settings()}?tab=workflows`)}>
+ <Settings className="size-3.5" />
+ {t(($) => $.workflows.project.manage)}
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {dialog}
+ <WorkflowFlowSheet open={flowOpen} onOpenChange={setFlowOpen} project={project} workflow={workflow} />
+ </>
+ );
+}
+
+/**
+ * The project's whole flow in one panel (MUL-7420): every column, who it
+ * hands to, and the same handoff form the column header opens. Handoffs
+ * belong to the workflow, so only admins edit them here.
+ */
+export function WorkflowFlowSheet({
+ open,
+ onOpenChange,
+ project,
+ workflow,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ project: Project;
+ workflow: IssueWorkflow;
+}) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const { data: projects = [] } = useQuery(projectListOptions(wsId));
+ const { isAdmin } = useWorkflowPermissions(project);
+ const [expanded, setExpanded] = useState<string | null>(null);
+ const usedBy = workflow.is_default
+ ? projects.filter((p) => !p.workflow_id).length
+ : workflow.project_ids.length;
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent side="right" className="w-[440px] overflow-y-auto p-5 sm:max-w-[440px]">
+ <SheetHeader className="p-0">
+ <SheetTitle>{t(($) => $.workflows.flow.title, { workflow: workflow.name })}</SheetTitle>
+ <SheetDescription>
+ {usedBy > 1
+ ? t(($) => $.workflows.flow.scope_shared, { count: usedBy })
+ : t(($) => $.workflows.flow.scope_own)}
+ </SheetDescription>
+ </SheetHeader>
+ <ol className="space-y-1.5">
+ {workflow.steps.map((step) => (
+ <FlowRow
+ key={step.status_key}
+ project={project}
+ workflow={workflow}
+ statusKey={step.status_key}
+ canEdit={isAdmin}
+ expanded={expanded === step.status_key}
+ onToggle={() => setExpanded((current) => (current === step.status_key ? null : step.status_key))}
+ />
+ ))}
+ </ol>
+ </SheetContent>
+ </Sheet>
+ );
+}
+
+function FlowRow({
+ project,
+ workflow,
+ statusKey,
+ canEdit,
+ expanded,
+ onToggle,
+}: {
+ project: Project;
+ workflow: IssueWorkflow;
+ statusKey: string;
+ canEdit: boolean;
+ expanded: boolean;
+ onToggle: () => void;
+}) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const catalog = useIssueStatuses(wsId);
+ const labelOf = useStatusLabel(wsId);
+ const handlerLabel = useStepHandlerLabel(project);
+ const step = workflow.steps.find((s) => s.status_key === statusKey);
+ const label = handlerLabel(step);
+ const actor = stepHandlerActor(step, project);
+ const accepts = statusAcceptsHandoff(statusKey);
+
+ return (
+ <li className={cn("rounded-lg border border-surface-border", expanded && "bg-card")}>
+ <button
+ type="button"
+ disabled={!accepts}
+ onClick={onToggle}
+ aria-expanded={expanded}
+ className="flex w-full items-center gap-2 px-3 py-2 text-left disabled:cursor-default"
+ >
+ <StatusIcon
+ status={statusKey}
+ category={catalog.categoryOf(statusKey)}
+ color={catalog.colorOf(statusKey)}
+ icon={catalog.iconOf(statusKey)}
+ className="h-3.5 w-3.5 shrink-0"
+ />
+ <span className="min-w-0 flex-1 truncate text-body font-medium">{labelOf(statusKey)}</span>
+ {label ? (
+ <span className="flex min-w-0 items-center gap-1 text-caption text-muted-foreground">
+ {actor && <ActorAvatar actorType={actor.type} actorId={actor.id} size="xs" profileLink={false} />}
+ <span className="truncate">{label}</span>
+ </span>
+ ) : (
+ <span className="text-caption text-muted-foreground">
+ {accepts ? t(($) => $.workflows.handler.none) : t(($) => $.workflows.flow.no_handoff_here)}
+ </span>
+ )}
+ {accepts && (
+ <ChevronRight
+ aria-hidden
+ className={cn("size-3.5 shrink-0 text-muted-foreground transition-transform", expanded && "rotate-90")}
+ />
+ )}
+ </button>
+ {expanded && accepts && (
+ <div className="border-t border-surface-border px-3 py-3">
+ <WorkflowHandoffForm workflow={workflow} statusKey={statusKey} canEdit={canEdit} project={project} />
+ </div>
+ )}
+ </li>
+ );
+}
diff --git a/packages/views/workflows/project-workflow-row.tsx b/packages/views/workflows/project-workflow-row.tsx
new file mode 100644
index 0000000000..02ffa4d07e
--- /dev/null
+++ b/packages/views/workflows/project-workflow-row.tsx
@@ -0,0 +1,226 @@
+"use client";
+
+import { useState, type ReactNode } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Check, ChevronDown, Settings, Workflow } from "lucide-react";
+import { toast } from "sonner";
+import { api, clientErrorMessage } from "@multica/core/api";
+import { useFeatureEnabled } from "@multica/core/config";
+import { PROJECT_WORKFLOWS_V1_FLAG } from "@multica/core/feature-flags";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { handoffStepCount, resolveProjectWorkflow, useIssueWorkflows, useSetProjectWorkflow } from "@multica/core/issue-workflows";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { projectListOptions } from "@multica/core/projects/queries";
+import type { IssueWorkflow, IssueWorkflowMappingPlan, Project } from "@multica/core/types";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { useNavigation } from "../navigation";
+import { useT } from "../i18n";
+import { WorkflowMappingDialog } from "./workflow-mapping-dialog";
+import { useWorkflowPermissions } from "./permissions";
+
+interface PendingSwitch {
+ workflowId: string | null;
+ name: string;
+ plan: IssueWorkflowMappingPlan;
+ targetKeys: string[];
+}
+
+/**
+ * Switching a project's workflow (MUL-7420). Choosing one always confirms
+ * first: the dialog maps only the statuses the new workflow lacks and lists
+ * the ones that stay. Render `dialog` once wherever `choose` is offered.
+ */
+export function useProjectWorkflowSwitch(project: Project): {
+ choose: (workflow: IssueWorkflow) => Promise<void>;
+ busy: boolean;
+ dialog: ReactNode;
+} {
+ const { t } = useT("issues");
+ const setWorkflow = useSetProjectWorkflow();
+ const [pending, setPending] = useState<PendingSwitch | null>(null);
+ const [checking, setChecking] = useState(false);
+
+ const choose = async (workflow: IssueWorkflow) => {
+ const workflowId = workflow.is_default ? null : workflow.id;
+ if (workflowId === (project.workflow_id ?? null)) return;
+ setChecking(true);
+ try {
+ const { plan } = await api.dryRunProjectWorkflow(project.id, workflowId);
+ setPending({
+ workflowId,
+ name: workflow.name,
+ plan,
+ targetKeys: workflow.steps.map((s) => s.status_key),
+ });
+ } catch (err) {
+ toast.error(clientErrorMessage(err) ?? t(($) => $.workflows.project.error));
+ } finally {
+ setChecking(false);
+ }
+ };
+
+ const apply = async (mapping: Record<string, string>) => {
+ if (!pending) return;
+ try {
+ const moved = pending.plan.required.reduce((sum, r) => sum + r.issue_count, 0);
+ await setWorkflow.mutateAsync({
+ projectId: project.id,
+ workflow_id: pending.workflowId,
+ status_mapping: pending.plan.required.length > 0 ? mapping : undefined,
+ });
+ toast.success(
+ t(($) => $.workflows.mapping.switched, { project: project.title, workflow: pending.name, count: moved }),
+ );
+ setPending(null);
+ } catch (err) {
+ toast.error(clientErrorMessage(err) ?? t(($) => $.workflows.project.error));
+ }
+ };
+
+ return {
+ choose,
+ busy: checking || setWorkflow.isPending,
+ dialog: (
+ <WorkflowMappingDialog
+ open={pending !== null}
+ onOpenChange={(open) => !open && setPending(null)}
+ variant={{ kind: "switch", projectName: project.title, workflowName: pending?.name ?? "" }}
+ plan={pending?.plan ?? null}
+ targetKeys={pending?.targetKeys ?? []}
+ pending={setWorkflow.isPending}
+ onConfirm={(mapping) => void apply(mapping)}
+ />
+ ),
+ };
+}
+
+/** The workflows a project may switch to, each with what it has and who uses it. */
+export function WorkflowChoiceItems({
+ project,
+ onChoose,
+}: {
+ project: Project;
+ onChoose: (workflow: IssueWorkflow) => void;
+}) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const enabled = useFeatureEnabled(PROJECT_WORKFLOWS_V1_FLAG, false);
+ const { workflows } = useIssueWorkflows(wsId);
+ const { data: projects = [] } = useQuery(projectListOptions(wsId));
+ const current = resolveProjectWorkflow(workflows, project);
+ const separator = t(($) => $.workflows.list_separator);
+ const options = enabled ? workflows : workflows.filter((w) => w.is_default || w.id === current?.id);
+
+ return (
+ <>
+ {options.map((workflow) => {
+ const usedBy = projects
+ .filter((p) => (workflow.is_default ? !p.workflow_id : workflow.project_ids.includes(p.id)))
+ .map((p) => p.title)
+ .join(separator);
+ return (
+ <DropdownMenuItem key={workflow.id} className="items-start gap-2 py-2" onClick={() => onChoose(workflow)}>
+ <Workflow aria-hidden className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1">
+ <span className="flex items-center gap-2">
+ <span className="truncate font-medium">{workflow.name}</span>
+ {workflow.is_default && (
+ <span className="shrink-0 rounded-xs bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">
+ {t(($) => $.workflows.project.default_badge)}
+ </span>
+ )}
+ </span>
+ <span className="mt-0.5 block text-caption text-muted-foreground">
+ {t(($) => $.workflows.settings.statuses, { count: workflow.steps.length })}
+ </span>
+ <span className="block truncate text-caption text-muted-foreground">
+ {usedBy
+ ? t(($) => $.workflows.project.used_by_short, { names: usedBy })
+ : t(($) => $.workflows.project.used_by_nobody)}
+ </span>
+ </span>
+ {workflow.id === current?.id && <Check aria-hidden className="mt-0.5 size-3.5 shrink-0" />}
+ </DropdownMenuItem>
+ );
+ })}
+ </>
+ );
+}
+
+/**
+ * The project's Workflow property (MUL-7420). Admins and the project lead
+ * switch it; everyone else sees which one it uses.
+ */
+export function ProjectWorkflowControl({ project }: { project: Project }) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const navigation = useNavigation();
+ const paths = useWorkspacePaths();
+ const enabled = useFeatureEnabled(PROJECT_WORKFLOWS_V1_FLAG, false);
+ const { workflows } = useIssueWorkflows(wsId);
+ const { canManageProject } = useWorkflowPermissions(project);
+ const { choose, busy, dialog } = useProjectWorkflowSwitch(project);
+ const current = resolveProjectWorkflow(workflows, project);
+
+ if (!enabled && !project.workflow_id) return null;
+ const name = current?.name ?? t(($) => $.workflows.default_name);
+ const handoffs = current ? handoffStepCount(current) : 0;
+
+ if (!canManageProject) {
+ return (
+ <span className="-ml-1 inline-flex min-w-0 items-center gap-1.5 px-1 py-0.5 text-caption">
+ <Workflow aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate font-medium">{name}</span>
+ </span>
+ );
+ }
+
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ disabled={busy}
+ render={
+ <button
+ type="button"
+ className="-ml-1 inline-flex min-w-0 items-center gap-1.5 rounded-md px-1 py-0.5 text-caption transition-colors hover:bg-accent data-popup-open:bg-accent"
+ >
+ <Workflow aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate font-medium">{name}</span>
+ {handoffs > 0 && (
+ <span className="shrink-0 text-muted-foreground">
+ · {t(($) => $.workflows.settings.handoffs, { count: handoffs })}
+ </span>
+ )}
+ <ChevronDown aria-hidden className="size-3 shrink-0 text-muted-foreground" />
+ </button>
+ }
+ />
+ <DropdownMenuContent align="start" className="w-80">
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{t(($) => $.workflows.project.picker_title)}</DropdownMenuLabel>
+ <WorkflowChoiceItems project={project} onChoose={(w) => void choose(w)} />
+ </DropdownMenuGroup>
+ {enabled && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={() => navigation.push(`${paths.settings()}?tab=workflows`)}>
+ <Settings aria-hidden className="size-3.5" />
+ {t(($) => $.workflows.project.manage)}
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {dialog}
+ </>
+ );
+}
diff --git a/packages/views/workflows/step-handler.ts b/packages/views/workflows/step-handler.ts
new file mode 100644
index 0000000000..9df1f6ce06
--- /dev/null
+++ b/packages/views/workflows/step-handler.ts
@@ -0,0 +1,55 @@
+"use client";
+
+import { useCallback } from "react";
+import { useActorName } from "@multica/core/workspace/hooks";
+import type { IssueWorkflowStep, Project } from "@multica/core/types";
+import { useT } from "../i18n";
+
+/** The concrete actor a step hands off to, when one can be named up front. */
+export function stepHandlerActor(
+ step: IssueWorkflowStep | undefined,
+ project: Pick<Project, "lead_type" | "lead_id"> | null | undefined,
+): { type: "agent" | "squad" | "member"; id: string } | null {
+ if (!step) return null;
+ const { type, id } = step.handler;
+ if ((type === "agent" || type === "squad" || type === "member") && id) return { type, id };
+ if (type === "project_lead" && project?.lead_type && project.lead_id) {
+ return { type: project.lead_type, id: project.lead_id };
+ }
+ return null;
+}
+
+/**
+ * Names who a workflow step hands an issue to (MUL-7420): the agent, squad or
+ * member it names, the project lead, or the issue creator. Returns null for a
+ * step that keeps the assignee.
+ */
+export function useStepHandlerLabel(
+ project: Pick<Project, "lead_type" | "lead_id"> | null | undefined,
+) {
+ const { getActorName } = useActorName();
+ const { t } = useT("issues");
+ return useCallback(
+ (step: IssueWorkflowStep | undefined): string | null => {
+ if (!step) return null;
+ const { type, id } = step.handler;
+ switch (type) {
+ case "agent":
+ case "squad":
+ case "member":
+ return id ? getActorName(type, id) : t(($) => $.workflows.handler[type]);
+ case "project_lead":
+ return project?.lead_type && project.lead_id
+ ? t(($) => $.workflows.handler.project_lead_named, {
+ name: getActorName(project.lead_type, project.lead_id),
+ })
+ : t(($) => $.workflows.handler.project_lead);
+ case "creator":
+ return t(($) => $.workflows.handler.creator);
+ default:
+ return null;
+ }
+ },
+ [getActorName, project?.lead_id, project?.lead_type, t],
+ );
+}
diff --git a/packages/views/workflows/templates.ts b/packages/views/workflows/templates.ts
new file mode 100644
index 0000000000..eebdd22c78
--- /dev/null
+++ b/packages/views/workflows/templates.ts
@@ -0,0 +1,31 @@
+export type WorkflowTemplateId = "delivery" | "content" | "community";
+
+/**
+ * Starting points for a new workflow (MUL-7420). Each lists only its middle
+ * columns; `status` names a status in the library, `name` creates one (or
+ * reuses a status of that name) when the workflow is saved. Names are i18n
+ * keys under `workflows.templates.<id>.statuses`.
+ */
+export const WORKFLOW_TEMPLATES: {
+ id: WorkflowTemplateId;
+ columns: ({ status: string } | { name: string; category: "unstarted" | "started" })[];
+}[] = [
+ { id: "delivery", columns: [{ status: "in_progress" }, { status: "in_review" }, { name: "qa", category: "started" }] },
+ {
+ id: "content",
+ columns: [
+ { name: "drafting", category: "started" },
+ { name: "editing", category: "started" },
+ { name: "scheduled", category: "started" },
+ ],
+ },
+ {
+ id: "community",
+ columns: [
+ { name: "triage", category: "unstarted" },
+ { name: "replying", category: "started" },
+ { name: "waiting", category: "started" },
+ ],
+ },
+];
+
diff --git a/packages/views/workflows/timeline-handoff.tsx b/packages/views/workflows/timeline-handoff.tsx
new file mode 100644
index 0000000000..e4d6be5ecf
--- /dev/null
+++ b/packages/views/workflows/timeline-handoff.tsx
@@ -0,0 +1,62 @@
+"use client";
+
+import { useState } from "react";
+import { CornerDownRight } from "lucide-react";
+import { useActorName } from "@multica/core/workspace/hooks";
+import { ActorAvatar } from "../common/actor-avatar";
+import { useT } from "../i18n";
+import { BriefBlock } from "./handoff-form";
+
+/**
+ * The handoff half of a status-change timeline entry (MUL-7420): who the
+ * workflow step handed the issue to, whether their run started, and the brief
+ * that run received. Renders nothing for an ordinary status change.
+ */
+export function TimelineHandoff({ details }: { details: Record<string, string> }) {
+ const { t } = useT("issues");
+ const { getActorName } = useActorName();
+ const [open, setOpen] = useState(false);
+ const type = details.handoff_to_type;
+ const id = details.handoff_to_id;
+ if (!type || !id) return null;
+ const note = details.handoff_note ?? "";
+ const ran = details.handoff_run === "true";
+ const name = getActorName(type, id);
+ return (
+ <div className="mt-1 space-y-2">
+ <div className="flex flex-wrap items-center gap-1.5 text-caption text-muted-foreground">
+ <CornerDownRight aria-hidden className="size-3 shrink-0" />
+ <span>{t(($) => $.workflows.timeline.handed_to)}</span>
+ <ActorAvatar actorType={type} actorId={id} size="xs" profileLink={false} />
+ <span className="font-medium text-foreground">{name}</span>
+ {type === "member" ? (
+ <span>{t(($) => $.workflows.timeline.member_no_run)}</span>
+ ) : ran ? (
+ <>
+ <span>{t(($) => $.workflows.timeline.run_started)}</span>
+ {note && (
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ aria-expanded={open}
+ className="text-brand hover:underline"
+ >
+ {open ? t(($) => $.workflows.timeline.hide_brief) : t(($) => $.workflows.timeline.show_brief)}
+ </button>
+ )}
+ </>
+ ) : null}
+ </div>
+ {open && note && (
+ <div className="space-y-1.5">
+ <div className="flex items-center gap-1.5 text-caption text-muted-foreground">
+ <ActorAvatar actorType={type} actorId={id} size="xs" profileLink={false} />
+ <span className="font-medium text-foreground">{name}</span>
+ {t(($) => $.workflows.timeline.brief_header)}
+ </div>
+ <BriefBlock brief={note} />
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/packages/views/workflows/workflow-editor-page.tsx b/packages/views/workflows/workflow-editor-page.tsx
new file mode 100644
index 0000000000..e252b26457
--- /dev/null
+++ b/packages/views/workflows/workflow-editor-page.tsx
@@ -0,0 +1,883 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import {
+ DndContext,
+ KeyboardSensor,
+ PointerSensor,
+ closestCenter,
+ useSensor,
+ useSensors,
+ type DragEndEvent,
+} from "@dnd-kit/core";
+import {
+ SortableContext,
+ arrayMove,
+ sortableKeyboardCoordinates,
+ useSortable,
+ verticalListSortingStrategy,
+} from "@dnd-kit/sortable";
+import { CSS } from "@dnd-kit/utilities";
+import {
+ ChevronDown,
+ ChevronRight,
+ Copy,
+ CornerDownRight,
+ FolderKanban,
+ GripVertical,
+ MoreHorizontal,
+ Plus,
+ Trash2,
+ UserRound,
+} from "lucide-react";
+import { toast } from "sonner";
+import { ApiError, clientErrorMessage } from "@multica/core/api";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useCurrentWorkspace } from "@multica/core/paths";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { statusColumnKeys } from "@multica/core/issues";
+import {
+ isFixedWorkflowStatus,
+ statusAcceptsHandoff,
+ useCreateIssueWorkflow,
+ useDeleteIssueWorkflow,
+ useIssueWorkflows,
+ useUpdateIssueWorkflow,
+ workflowMiddleKeys,
+ workflowNextStatus,
+} from "@multica/core/issue-workflows";
+import { useActorName } from "@multica/core/workspace/hooks";
+import { projectListOptions } from "@multica/core/projects/queries";
+import type {
+ IssueWorkflow,
+ IssueWorkflowMappingPlan,
+ IssueWorkflowStep,
+ IssueWorkflowStepInput,
+} from "@multica/core/types";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { Input } from "@multica/ui/components/ui/input";
+import { Spinner } from "@multica/ui/components/ui/spinner";
+import { Switch } from "@multica/ui/components/ui/switch";
+import { cn } from "@multica/ui/lib/utils";
+import { StatusIcon } from "../issues/components/status-icon";
+import { useStatusLabel } from "../issues/utils/status-label";
+import { ActorAvatar } from "../common/actor-avatar";
+import { useT } from "../i18n";
+import { BriefPreviewDialog, HandoffFields, savedHandoff } from "./handoff-form";
+import { stepHandlerActor, useStepHandlerLabel } from "./step-handler";
+import { WORKFLOW_TEMPLATES, type WorkflowTemplateId } from "./templates";
+import { WorkflowMappingDialog } from "./workflow-mapping-dialog";
+
+/**
+ * The name and description edit in place. A hover or focus background tells
+ * them apart from the read-only note under them.
+ */
+const INLINE_FIELD =
+ "-mx-1.5 block w-[calc(100%+0.75rem)] rounded-md bg-transparent px-1.5 outline-none transition-colors placeholder:text-muted-foreground read-only:cursor-default hover:[&:not(:read-only)]:bg-accent/60 focus-visible:[&:not(:read-only)]:bg-accent/60 focus-visible:[&:not(:read-only)]:ring-1 focus-visible:[&:not(:read-only)]:ring-ring/40";
+
+/** A new workflow starts from the common delivery loop instead of nothing. */
+const NEW_WORKFLOW_MIDDLE = ["in_progress", "in_review"];
+
+/** A middle column of the draft: a library status, or one to create on save. */
+type DraftColumn = { id: string; status_key: string } | { id: string; new_name: string; category?: "unstarted" | "started" };
+
+/** What entering a column does, keyed in the draft by column id. */
+type Handoff = Pick<IssueWorkflowStep, "handler" | "instructions" | "next_status_key" | "back_status_key">;
+
+const NO_HANDOFF: Handoff = { handler: { type: "none" }, instructions: "" };
+
+interface Draft {
+ name: string;
+ description: string;
+ backlog: boolean;
+ blocked: boolean;
+ middle: DraftColumn[];
+ handoffs: Record<string, Handoff>;
+}
+
+function hasHandoff(h: Handoff | undefined): h is Handoff {
+ return !!h && (h.handler.type !== "none" || !!h.next_status_key || !!h.back_status_key);
+}
+
+function draftFrom(workflow: Pick<IssueWorkflow, "name" | "description" | "steps">): Draft {
+ const keys = workflow.steps.map((s) => s.status_key);
+ const handoffs: Record<string, Handoff> = {};
+ for (const s of workflow.steps) {
+ const h = { handler: s.handler, instructions: s.instructions, next_status_key: s.next_status_key, back_status_key: s.back_status_key };
+ if (hasHandoff(h)) handoffs[s.status_key] = h;
+ }
+ return {
+ name: workflow.name,
+ description: workflow.description,
+ backlog: keys.includes("backlog"),
+ blocked: keys.includes("blocked"),
+ middle: workflowMiddleKeys(workflow).map((key) => ({ id: key, status_key: key })),
+ handoffs,
+ };
+}
+
+/** Every column of the draft in board order. */
+function draftColumns(draft: Draft): DraftColumn[] {
+ const fixed = (key: string): DraftColumn => ({ id: key, status_key: key });
+ return [
+ ...(draft.backlog ? [fixed("backlog")] : []),
+ fixed("todo"),
+ ...draft.middle,
+ ...(draft.blocked ? [fixed("blocked")] : []),
+ fixed("done"),
+ fixed("cancelled"),
+ ];
+}
+
+function sameDraft(a: Draft, b: Draft): boolean {
+ return JSON.stringify(a) === JSON.stringify(b);
+}
+
+function mappingPlanFrom(err: unknown): IssueWorkflowMappingPlan | null {
+ if (!(err instanceof ApiError) || err.status !== 409 || !err.body || typeof err.body !== "object") return null;
+ const body = err.body as { code?: unknown; plan?: IssueWorkflowMappingPlan };
+ if (body.code !== "workflow_status_mapping_required" || !body.plan) return null;
+ return { ...body.plan, unchanged: body.plan.unchanged ?? [] };
+}
+
+/**
+ * The workflow editor (MUL-7420): a workflow is a whole pipeline — its
+ * columns and who each one hands an issue to. Todo, done and cancelled are
+ * always there; backlog and blocked can be switched off; the editor arranges
+ * what sits between. Selecting a column edits its handoff.
+ *
+ * `workflowId` is null for a new workflow; `seed` pre-fills one (duplicate).
+ */
+export function WorkflowEditorPage({
+ workflowId,
+ seed,
+ template,
+ canEdit,
+ onBack,
+ onOpen,
+}: {
+ workflowId: string | null;
+ seed: IssueWorkflow | null;
+ /** Pre-fills a new workflow from a template. */
+ template?: WorkflowTemplateId | null;
+ canEdit: boolean;
+ onBack: () => void;
+ /** Navigates to another workflow's editor (after create, or to a duplicate). */
+ onOpen: (target: { id: string } | { duplicateOf: string }) => void;
+}) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const catalog = useIssueStatuses(wsId);
+ const labelOf = useStatusLabel(wsId);
+ const { workflows, isLoaded } = useIssueWorkflows(wsId);
+ const { data: projects = [] } = useQuery(projectListOptions(wsId));
+ const createWorkflow = useCreateIssueWorkflow();
+ const updateWorkflow = useUpdateIssueWorkflow();
+ const deleteWorkflow = useDeleteIssueWorkflow();
+
+ const saved = workflowId ? workflows.find((w) => w.id === workflowId) ?? null : null;
+ const isDefault = !!saved?.is_default;
+ const baseline = useMemo<Draft>(() => {
+ if (saved) return draftFrom(saved);
+ if (seed) return { ...draftFrom(seed), name: t(($) => $.workflows.editor.copy_name, { name: seed.name }) };
+ const tpl = template ? WORKFLOW_TEMPLATES.find((x) => x.id === template) : undefined;
+ if (tpl) {
+ const statusName = (name: string) =>
+ t(($) => ($.workflows.templates[tpl.id].statuses as Record<string, string>)[name] ?? name);
+ return {
+ name: t(($) => $.workflows.templates[tpl.id].name),
+ description: t(($) => $.workflows.templates[tpl.id].summary),
+ backlog: true,
+ blocked: true,
+ handoffs: {},
+ middle: tpl.columns.map((column): DraftColumn => {
+ if ("status" in column) return { id: column.status, status_key: column.status };
+ const name = statusName(column.name);
+ const existing = catalog.activeStatuses.find((e) => e.name.toLowerCase() === name.toLowerCase());
+ return existing
+ ? { id: existing.key, status_key: existing.key }
+ : { id: `new:${name}`, new_name: name, category: column.category };
+ }),
+ };
+ }
+ return {
+ name: "",
+ description: "",
+ backlog: true,
+ blocked: true,
+ middle: NEW_WORKFLOW_MIDDLE.map((key) => ({ id: key, status_key: key })),
+ handoffs: {},
+ };
+ // Re-seed only when the target changes or the saved row is refreshed.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [saved?.updated_at, workflowId, seed?.id, template, catalog.activeStatuses.length]);
+
+ const [draft, setDraft] = useState<Draft>(baseline);
+ const [mappingPlan, setMappingPlan] = useState<IssueWorkflowMappingPlan | null>(null);
+ const [newName, setNewName] = useState<string | null>(null);
+ const [selected, setSelected] = useState<string | null>(null);
+ const [previewOpen, setPreviewOpen] = useState(false);
+ useEffect(() => setDraft(baseline), [baseline]);
+
+ const dirty = !workflowId || !sameDraft(draft, baseline);
+ const pending = createWorkflow.isPending || updateWorkflow.isPending;
+ const canSave = canEdit && dirty && draft.name.trim().length > 0 && !pending;
+ const usedBy = saved
+ ? projects.filter((p) => (saved.is_default ? !p.workflow_id : saved.project_ids.includes(p.id)))
+ : [];
+ const columns = draftColumns(draft);
+ const middleKeys = draft.middle.flatMap((c) => ("status_key" in c ? [c.status_key] : []));
+ const addable = statusColumnKeys(catalog).filter((key) => !isFixedWorkflowStatus(key) && !middleKeys.includes(key));
+ const ids = draft.middle.map((c) => c.id);
+ const targetKeys = columns.flatMap((c) => ("status_key" in c ? [c.status_key] : []));
+ // Next and back can only name statuses that exist before the save.
+ const flow = { steps: targetKeys.map((status_key) => ({ status_key, ...NO_HANDOFF })) };
+ const selectedId = selected ?? "todo";
+ const selectedColumn = columns.find((c) => c.id === selectedId && "status_key" in c && statusAcceptsHandoff(c.status_key));
+ const selectedStep: IssueWorkflowStep | null =
+ selectedColumn && "status_key" in selectedColumn
+ ? { status_key: selectedColumn.status_key, ...(draft.handoffs[selectedColumn.id] ?? NO_HANDOFF) }
+ : null;
+ const patchHandoff = (id: string, patch: Partial<Handoff>) =>
+ setDraft((d) => ({ ...d, handoffs: { ...d.handoffs, [id]: { ...(d.handoffs[id] ?? NO_HANDOFF), ...patch } } }));
+
+ const sensors = useSensors(
+ useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
+ );
+ const onDragEnd = ({ active, over }: DragEndEvent) => {
+ if (!over || active.id === over.id) return;
+ setDraft((d) => ({ ...d, middle: arrayMove(d.middle, ids.indexOf(String(active.id)), ids.indexOf(String(over.id))) }));
+ };
+
+ const addNew = () => {
+ const name = newName?.trim();
+ if (!name) return;
+ setDraft((d) => ({ ...d, middle: [...d.middle, { id: `new:${name}:${Date.now()}`, new_name: name }] }));
+ setNewName(null);
+ };
+
+ const save = async (mapping?: Record<string, string>) => {
+ const listed = new Set(targetKeys);
+ const steps: IssueWorkflowStepInput[] = columns.map((c) => {
+ const raw = draft.handoffs[c.id];
+ const h = raw && savedHandoff(raw);
+ const handoff = hasHandoff(h)
+ ? {
+ ...(h.handler.type !== "none" ? { handler: h.handler, instructions: h.instructions } : {}),
+ ...(h.next_status_key && listed.has(h.next_status_key) ? { next_status_key: h.next_status_key } : {}),
+ ...(h.back_status_key && listed.has(h.back_status_key) ? { back_status_key: h.back_status_key } : {}),
+ }
+ : {};
+ return "status_key" in c
+ ? { status_key: c.status_key, ...handoff }
+ : { new_status: { name: c.new_name, ...(c.category ? { category: c.category } : {}) }, ...handoff };
+ });
+ const body = {
+ ...(isDefault ? {} : { name: draft.name.trim() }),
+ description: draft.description.trim(),
+ steps,
+ ...(mapping ? { status_mapping: mapping } : {}),
+ };
+ try {
+ if (workflowId) {
+ await updateWorkflow.mutateAsync({ id: workflowId, ...body });
+ toast.success(t(($) => $.workflows.editor.saved));
+ } else {
+ const created = await createWorkflow.mutateAsync({ ...body, name: draft.name.trim() });
+ toast.success(t(($) => $.workflows.editor.created));
+ onOpen({ id: created.id });
+ }
+ setMappingPlan(null);
+ } catch (err) {
+ const plan = mappingPlanFrom(err);
+ if (plan) {
+ setMappingPlan(plan);
+ return;
+ }
+ toast.error(clientErrorMessage(err) ?? t(($) => $.workflows.editor.error));
+ }
+ };
+
+ const remove = async () => {
+ if (!workflowId) return;
+ try {
+ await deleteWorkflow.mutateAsync(workflowId);
+ toast.success(t(($) => $.workflows.settings.deleted));
+ onBack();
+ } catch (err) {
+ toast.error(clientErrorMessage(err) ?? t(($) => $.workflows.settings.delete_error));
+ }
+ };
+
+ if (workflowId && isLoaded && !saved) {
+ return (
+ <div className="space-y-4">
+ <Breadcrumb onBack={onBack} current="" />
+ <p className="text-body text-muted-foreground">{t(($) => $.workflows.editor.not_found)}</p>
+ </div>
+ );
+ }
+
+ const title = draft.name.trim() || t(($) => $.workflows.editor.create_title);
+ const middleIds = new Set(ids);
+ const isOff = (column: DraftColumn) =>
+ "status_key" in column &&
+ ((column.status_key === "backlog" && !draft.backlog) || (column.status_key === "blocked" && !draft.blocked));
+ const listed: DraftColumn[] = [
+ { id: "backlog", status_key: "backlog" },
+ { id: "todo", status_key: "todo" },
+ ...draft.middle,
+ { id: "blocked", status_key: "blocked" },
+ { id: "done", status_key: "done" },
+ { id: "cancelled", status_key: "cancelled" },
+ ];
+ const current = listed.find((c) => c.id === selectedId) ?? listed[1]!;
+ const nextOf = (key: string, h: Handoff | undefined) => h?.next_status_key ?? workflowNextStatus(flow, key);
+ const card = (column: DraftColumn) => {
+ const key = "status_key" in column ? column.status_key : null;
+ const optional = key === "backlog" || key === "blocked";
+ const off = isOff(column);
+ const props = {
+ column,
+ off,
+ start: key === "todo",
+ handoff: off ? undefined : draft.handoffs[column.id],
+ next: key && !off ? nextOf(key, draft.handoffs[column.id]) : undefined,
+ selected: current.id === column.id,
+ onSelect: () => setSelected(column.id),
+ toggle: optional
+ ? { checked: !off, disabled: !canEdit, onChange: (on: boolean) => setDraft((d) => ({ ...d, [key]: on })) }
+ : undefined,
+ };
+ return (
+ <li key={column.id}>
+ {middleIds.has(column.id) ? <SortableStepCard {...props} draggable={canEdit} /> : <StepCard {...props} />}
+ </li>
+ );
+ };
+ const replaceStatus = (column: DraftColumn, key: string) => {
+ setDraft((d) => {
+ const { [column.id]: moved, ...rest } = d.handoffs;
+ return {
+ ...d,
+ middle: d.middle.map((c) => (c.id === column.id ? { id: key, status_key: key } : c)),
+ handoffs: moved ? { ...rest, [key]: moved } : rest,
+ };
+ });
+ setSelected(key);
+ };
+ const removeColumn = (column: DraftColumn) => {
+ setDraft((d) => ({ ...d, middle: d.middle.filter((c) => c.id !== column.id) }));
+ setSelected("todo");
+ };
+
+ return (
+ <div className="space-y-6">
+ <div className="space-y-3">
+ <Breadcrumb onBack={onBack} current={title} />
+ <div className="flex items-start gap-3">
+ <div className="min-w-0 flex-1">
+ <input
+ aria-label={t(($) => $.workflows.editor.name)}
+ value={draft.name}
+ maxLength={64}
+ readOnly={!canEdit || isDefault}
+ placeholder={t(($) => $.workflows.editor.name_placeholder)}
+ onChange={(e) => setDraft((d) => ({ ...d, name: e.target.value }))}
+ className={cn(INLINE_FIELD, "h-9 text-title-lg font-semibold tracking-tight")}
+ />
+ <input
+ aria-label={t(($) => $.workflows.editor.description)}
+ value={draft.description}
+ maxLength={256}
+ readOnly={!canEdit}
+ placeholder={canEdit ? t(($) => $.workflows.editor.description_placeholder) : ""}
+ onChange={(e) => setDraft((d) => ({ ...d, description: e.target.value }))}
+ className={cn(INLINE_FIELD, "mt-0.5 h-7 text-body")}
+ />
+ <p className="mt-2 flex items-start gap-1.5 text-caption leading-5 text-muted-foreground">
+ <FolderKanban aria-hidden className="mt-0.5 size-3.5 shrink-0" />
+ <span>
+ {isDefault
+ ? t(($) => $.workflows.editor.default_note)
+ : usedBy.length > 0
+ ? t(($) => $.workflows.editor.used_by_note, {
+ count: usedBy.length,
+ names: usedBy.map((p) => p.title).join(t(($) => $.workflows.list_separator)),
+ })
+ : t(($) => $.workflows.editor.unused_note)}
+ </span>
+ </p>
+ </div>
+ {canEdit && (
+ <div className="flex shrink-0 items-center gap-2">
+ {dirty && workflowId && (
+ <span className="text-caption text-muted-foreground">{t(($) => $.workflows.editor.unsaved)}</span>
+ )}
+ {workflowId && (
+ <Button variant="outline" className="gap-1.5" onClick={() => onOpen({ duplicateOf: workflowId })}>
+ <Copy className="size-3.5" />
+ {t(($) => $.workflows.editor.duplicate)}
+ </Button>
+ )}
+ <Button onClick={() => void save()} disabled={!canSave} aria-busy={pending}>
+ {pending && <Spinner className="size-3.5" />}
+ {workflowId ? t(($) => $.workflows.editor.save) : t(($) => $.workflows.editor.create)}
+ </Button>
+ {workflowId && !isDefault && (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button variant="ghost" size="icon" aria-label={t(($) => $.workflows.editor.more)}>
+ <MoreHorizontal className="size-4" />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end" className="w-56">
+ <DropdownMenuItem
+ variant="destructive"
+ disabled={usedBy.length > 0 || deleteWorkflow.isPending}
+ onClick={() => void remove()}
+ >
+ <Trash2 className="size-3.5" />
+ {t(($) => $.workflows.settings.delete)}
+ </DropdownMenuItem>
+ {usedBy.length > 0 && (
+ <p className="px-2 pb-1.5 text-caption text-muted-foreground">
+ {t(($) => $.workflows.settings.delete_in_use)}
+ </p>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+
+ <div className="grid items-start gap-5 lg:grid-cols-[minmax(0,20rem)_minmax(0,1fr)]">
+ <div className="min-w-0">
+ <ol className="space-y-2">
+ {card(listed[0]!)}
+ {card(listed[1]!)}
+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>
+ <SortableContext items={ids} strategy={verticalListSortingStrategy}>
+ {draft.middle.map(card)}
+ </SortableContext>
+ </DndContext>
+ {listed.slice(-3).map(card)}
+ </ol>
+ {canEdit && (
+ <div className="mt-3 flex flex-wrap items-center gap-2">
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button variant="outline" size="sm" className="gap-1.5">
+ <Plus className="size-3.5" />
+ {t(($) => $.workflows.editor.add_step)}
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="start" className="max-h-80 w-56 overflow-y-auto">
+ {addable.map((key) => (
+ <DropdownMenuItem
+ key={key}
+ onClick={() => {
+ setDraft((d) => ({ ...d, middle: [...d.middle, { id: key, status_key: key }] }));
+ setSelected(key);
+ }}
+ >
+ <StatusIcon
+ status={key}
+ category={catalog.categoryOf(key)}
+ color={catalog.colorOf(key)}
+ icon={catalog.iconOf(key)}
+ className="h-3.5 w-3.5"
+ />
+ <span className="truncate">{labelOf(key)}</span>
+ </DropdownMenuItem>
+ ))}
+ {addable.length > 0 && <DropdownMenuSeparator />}
+ <DropdownMenuItem onClick={() => setNewName("")}>
+ <Plus className="size-3.5" />
+ {t(($) => $.workflows.columns.new_status)}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {newName !== null && (
+ <div className="flex items-center gap-1.5">
+ <Input
+ autoFocus
+ maxLength={64}
+ value={newName}
+ className="h-8 w-44"
+ placeholder={t(($) => $.workflows.columns.name_placeholder)}
+ onChange={(e) => setNewName(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") addNew();
+ if (e.key === "Escape") setNewName(null);
+ }}
+ />
+ <Button size="sm" variant="ghost" onClick={addNew} disabled={!newName.trim()}>
+ {t(($) => $.workflows.columns.add)}
+ </Button>
+ </div>
+ )}
+ </div>
+ )}
+ <p className="mt-2.5 text-caption leading-5 text-muted-foreground">{t(($) => $.workflows.editor.steps_hint)}</p>
+ </div>
+
+ <StepDetail
+ key={current.id}
+ column={current}
+ off={isOff(current)}
+ handoff={draft.handoffs[current.id]}
+ flow={flow}
+ canEdit={canEdit}
+ statusOptions={middleIds.has(current.id) && "status_key" in current ? addable : null}
+ onReplaceStatus={(key) => replaceStatus(current, key)}
+ onRemove={canEdit && middleIds.has(current.id) ? () => removeColumn(current) : undefined}
+ onPatch={(patch) => patchHandoff(current.id, patch)}
+ onPreview={
+ saved && "status_key" in current && saved.steps.some((s) => s.status_key === current.status_key)
+ ? () => setPreviewOpen(true)
+ : undefined
+ }
+ />
+ {saved && selectedStep && (
+ <BriefPreviewDialog open={previewOpen} onOpenChange={setPreviewOpen} workflowId={saved.id} step={selectedStep} />
+ )}
+ </div>
+
+ <WorkflowMappingDialog
+ open={mappingPlan !== null}
+ onOpenChange={(open) => !open && setMappingPlan(null)}
+ variant={{ kind: "edit", workflowName: draft.name.trim() }}
+ plan={mappingPlan}
+ targetKeys={targetKeys}
+ pending={pending}
+ onConfirm={(mapping) => void save(mapping)}
+ />
+ </div>
+ );
+}
+
+function Breadcrumb({ onBack, current }: { onBack: () => void; current: string }) {
+ const { t } = useT("issues");
+ const workspace = useCurrentWorkspace();
+ return (
+ <nav className="flex items-center gap-1.5 text-caption text-muted-foreground">
+ {workspace?.name && (
+ <>
+ <span className="truncate">{workspace.name}</span>
+ <ChevronRight aria-hidden className="size-3" />
+ </>
+ )}
+ <button type="button" onClick={onBack} className="hover:text-foreground transition-colors">
+ {t(($) => $.workflows.settings.title)}
+ </button>
+ {current && (
+ <>
+ <ChevronRight aria-hidden className="size-3" />
+ <span className="truncate text-foreground">{current}</span>
+ </>
+ )}
+ </nav>
+ );
+}
+
+interface StepCardProps {
+ column: DraftColumn;
+ /** Backlog or blocked switched off: the workflow leaves the status out. */
+ off: boolean;
+ /** The step new issues start on. */
+ start: boolean;
+ handoff: Handoff | undefined;
+ /** Where the handler is told to move the issue next. */
+ next: string | undefined;
+ selected: boolean;
+ onSelect: () => void;
+ toggle?: { checked: boolean; disabled: boolean; onChange: (on: boolean) => void };
+}
+
+function SortableStepCard({ draggable, ...props }: StepCardProps & { draggable: boolean }) {
+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
+ id: props.column.id,
+ disabled: !draggable,
+ });
+ return (
+ <StepCard
+ {...props}
+ sortable={{
+ ref: setNodeRef,
+ style: { transform: CSS.Transform.toString(transform), transition },
+ dragging: isDragging,
+ handle: draggable ? { ...attributes, ...listeners } : undefined,
+ }}
+ />
+ );
+}
+
+/**
+ * One step of the editor's list: its status and what entering it does.
+ * Middle steps drag; backlog and blocked switch on and off.
+ */
+function StepCard({
+ column,
+ off,
+ start,
+ handoff,
+ next,
+ selected,
+ onSelect,
+ toggle,
+ sortable,
+}: StepCardProps & {
+ sortable?: {
+ ref: (node: HTMLElement | null) => void;
+ style: React.CSSProperties;
+ dragging: boolean;
+ handle?: React.HTMLAttributes<HTMLButtonElement>;
+ };
+}) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const catalog = useIssueStatuses(wsId);
+ const labelOf = useStatusLabel(wsId);
+ const handlerLabel = useStepHandlerLabel(null);
+ const { getActorName } = useActorName();
+ const label = "status_key" in column ? labelOf(column.status_key) : column.new_name;
+ const step = handoff && "status_key" in column ? { status_key: column.status_key, ...handoff } : undefined;
+ const who = handlerLabel(step);
+ const actor = stepHandlerActor(step, null);
+
+ return (
+ <div
+ ref={sortable?.ref}
+ style={sortable?.style}
+ className={cn(
+ "flex items-start gap-1 rounded-lg border px-2 py-2.5 transition-colors",
+ selected ? "border-foreground/20 bg-accent" : "border-surface-border bg-card hover:bg-accent/50",
+ off && !selected && "border-dashed bg-transparent",
+ sortable?.dragging && "z-10 shadow-[var(--surface-shadow)]",
+ )}
+ >
+ {sortable?.handle ? (
+ <button
+ type="button"
+ aria-label={t(($) => $.workflows.editor.reorder, { name: label })}
+ className="flex h-5 w-4 shrink-0 touch-none items-center justify-center rounded-xs cursor-grab text-muted-foreground active:cursor-grabbing"
+ {...sortable.handle}
+ >
+ <GripVertical className="size-3.5" />
+ </button>
+ ) : (
+ <span className="h-5 w-4 shrink-0" />
+ )}
+ <button
+ type="button"
+ onClick={onSelect}
+ aria-pressed={selected}
+ className={cn("min-w-0 flex-1 text-left", off && "opacity-60")}
+ >
+ <span className="flex h-5 items-center gap-2">
+ {"status_key" in column ? (
+ <StatusIcon
+ status={column.status_key}
+ category={catalog.categoryOf(column.status_key)}
+ color={catalog.colorOf(column.status_key)}
+ icon={catalog.iconOf(column.status_key)}
+ className="h-3.5 w-3.5 shrink-0"
+ />
+ ) : (
+ <Plus aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
+ )}
+ <span className="min-w-0 truncate text-body font-medium">{label}</span>
+ {start && <Badge>{t(($) => $.workflows.editor.start)}</Badge>}
+ {!("status_key" in column) && <Badge>{t(($) => $.workflows.editor.new_badge)}</Badge>}
+ </span>
+ <span className="mt-1 flex min-w-0 items-center gap-1 text-caption text-muted-foreground">
+ {off ? (
+ <span className="truncate">{t(($) => $.workflows.editor.step_off_short)}</span>
+ ) : who ? (
+ <>
+ <CornerDownRight aria-hidden className="size-3 shrink-0" />
+ <span className="shrink-0">{t(($) => $.workflows.editor.card_hand_to)}</span>
+ {actor && <ActorAvatar actorType={actor.type} actorId={actor.id} size="xs" profileLink={false} />}
+ <span className="min-w-0 truncate text-foreground">{actor ? getActorName(actor.type, actor.id) : who}</span>
+ {handoff?.handler.type === "agent" && next && (
+ <span className="shrink-0 truncate">· {t(($) => $.workflows.editor.card_then, { status: labelOf(next) })}</span>
+ )}
+ </>
+ ) : (
+ <>
+ <UserRound aria-hidden className="size-3 shrink-0" />
+ <span className="truncate">{t(($) => $.workflows.handler.none)}</span>
+ </>
+ )}
+ </span>
+ </button>
+ {toggle && (
+ <Switch
+ size="sm"
+ className="mt-0.5"
+ checked={toggle.checked}
+ disabled={toggle.disabled}
+ onCheckedChange={toggle.onChange}
+ aria-label={t(($) => $.workflows.editor.include_status, { status: label })}
+ />
+ )}
+ </div>
+ );
+}
+
+function Badge({ children }: { children: React.ReactNode }) {
+ return (
+ <span className="shrink-0 rounded-xs bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">{children}</span>
+ );
+}
+
+/** The selected step: its status and its handoff. */
+function StepDetail({
+ column,
+ off,
+ handoff,
+ flow,
+ canEdit,
+ statusOptions,
+ onReplaceStatus,
+ onRemove,
+ onPatch,
+ onPreview,
+}: {
+ column: DraftColumn;
+ off: boolean;
+ handoff: Handoff | undefined;
+ flow: Pick<IssueWorkflow, "steps">;
+ canEdit: boolean;
+ /** Statuses a middle step can switch to; null for fixed steps. */
+ statusOptions: string[] | null;
+ onReplaceStatus: (key: string) => void;
+ onRemove?: () => void;
+ onPatch: (patch: Partial<Handoff>) => void;
+ onPreview?: () => void;
+}) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const catalog = useIssueStatuses(wsId);
+ const labelOf = useStatusLabel(wsId);
+ const key = "status_key" in column ? column.status_key : null;
+ const label = key ? labelOf(key) : "new_name" in column ? column.new_name : "";
+ const icon = (statusKey: string, className = "h-3.5 w-3.5 shrink-0") => (
+ <StatusIcon
+ status={statusKey}
+ category={catalog.categoryOf(statusKey)}
+ color={catalog.colorOf(statusKey)}
+ icon={catalog.iconOf(statusKey)}
+ className={className}
+ />
+ );
+ const statusField = (
+ <span className="flex min-w-0 items-center gap-2">
+ {key ? icon(key) : <Plus aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />}
+ <span className="truncate">{label}</span>
+ </span>
+ );
+
+ return (
+ <section className="min-w-0 rounded-xl border border-surface-border bg-card lg:sticky lg:top-4">
+ <header className="flex items-center gap-2 border-b border-surface-border px-5 py-3.5">
+ {key ? icon(key, "h-4 w-4 shrink-0") : <Plus aria-hidden className="size-4 shrink-0 text-muted-foreground" />}
+ <h3 className="min-w-0 truncate text-body font-semibold">{label}</h3>
+ {key ? (
+ <code className="truncate font-mono text-caption text-muted-foreground">{key}</code>
+ ) : (
+ <Badge>{t(($) => $.workflows.editor.new_badge)}</Badge>
+ )}
+ {onRemove && (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="ml-auto text-muted-foreground"
+ aria-label={t(($) => $.workflows.editor.remove)}
+ onClick={onRemove}
+ >
+ <Trash2 className="size-3.5" />
+ </Button>
+ )}
+ </header>
+ <div className="space-y-6 p-5">
+ <DetailField label={t(($) => $.workflows.editor.status)} hint={key ? t(($) => $.workflows.editor.status_hint) : t(($) => $.workflows.editor.status_new_hint)}>
+ {statusOptions && canEdit ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <button
+ type="button"
+ className="flex h-8 w-full max-w-sm items-center justify-between gap-2 rounded-md border border-input bg-background px-2.5 text-body transition-colors hover:bg-accent/50"
+ />
+ }
+ >
+ {statusField}
+ <ChevronDown aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="max-h-80 w-(--anchor-width) overflow-y-auto">
+ {statusOptions.length === 0 ? (
+ <p className="px-2 py-1.5 text-caption text-muted-foreground">{t(($) => $.workflows.editor.no_other_status)}</p>
+ ) : (
+ statusOptions.map((option) => (
+ <DropdownMenuItem key={option} onClick={() => onReplaceStatus(option)}>
+ {icon(option)}
+ <span className="truncate">{labelOf(option)}</span>
+ </DropdownMenuItem>
+ ))
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : (
+ <div className="flex h-8 w-full max-w-sm items-center rounded-md border border-input bg-muted/40 px-2.5 text-body">
+ {statusField}
+ </div>
+ )}
+ </DetailField>
+ <DetailField label={t(($) => $.workflows.editor.on_enter)}>
+ {off ? (
+ <p className="text-caption leading-5 text-muted-foreground">{t(($) => $.workflows.editor.step_off)}</p>
+ ) : key && statusAcceptsHandoff(key) ? (
+ <HandoffFields
+ step={{ status_key: key, ...(handoff ?? NO_HANDOFF) }}
+ workflow={flow}
+ canEdit={canEdit}
+ onPatch={onPatch}
+ onPreview={onPreview}
+ />
+ ) : (
+ <p className="text-caption leading-5 text-muted-foreground">
+ {key ? t(($) => $.workflows.editor.no_handoff_step) : t(($) => $.workflows.editor.new_step_handoff)}
+ </p>
+ )}
+ </DetailField>
+ </div>
+ </section>
+ );
+}
+
+function DetailField({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
+ return (
+ <div className="space-y-2">
+ <p className="text-caption font-medium">{label}</p>
+ {children}
+ {hint && <p className="text-caption leading-5 text-muted-foreground">{hint}</p>}
+ </div>
+ );
+}
diff --git a/packages/views/workflows/workflow-mapping-dialog.tsx b/packages/views/workflows/workflow-mapping-dialog.tsx
new file mode 100644
index 0000000000..ba6f2eae21
--- /dev/null
+++ b/packages/views/workflows/workflow-mapping-dialog.tsx
@@ -0,0 +1,187 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { ArrowRight, Check } from "lucide-react";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+} from "@multica/ui/components/ui/select";
+import { Spinner } from "@multica/ui/components/ui/spinner";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import type { IssueWorkflowMappingPlan } from "@multica/core/types";
+import { StatusIcon } from "../issues/components/status-icon";
+import { useStatusLabel } from "../issues/utils/status-label";
+import { useT } from "../i18n";
+
+export type WorkflowMappingVariant =
+ | { kind: "switch"; projectName: string; workflowName: string }
+ | { kind: "edit"; workflowName: string };
+
+/**
+ * Confirms a workflow change that can move issues (MUL-7420): switching a
+ * project's workflow, or saving a workflow edit that removed statuses in use.
+ * Only statuses the target lacks get a destination; the rest are listed as
+ * unchanged, and the move never hands anything off.
+ */
+export function WorkflowMappingDialog({
+ open,
+ onOpenChange,
+ variant,
+ plan,
+ targetKeys,
+ pending,
+ onConfirm,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ variant: WorkflowMappingVariant;
+ plan: IssueWorkflowMappingPlan | null;
+ /** Statuses the issues may move to, in the target workflow's order. */
+ targetKeys: string[];
+ pending: boolean;
+ onConfirm: (mapping: Record<string, string>) => void;
+}) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const { categoryOf, colorOf, iconOf } = useIssueStatuses(wsId);
+ const labelOf = useStatusLabel(wsId);
+ const [mapping, setMapping] = useState<Record<string, string>>({});
+
+ useEffect(() => {
+ if (!plan) return;
+ setMapping(
+ Object.fromEntries(
+ plan.required.map((r) => [
+ r.status_key,
+ targetKeys.includes(r.suggested_status_key) ? r.suggested_status_key : targetKeys[0] ?? "",
+ ]),
+ ),
+ );
+ }, [plan, targetKeys]);
+
+ const icon = (key: string) => (
+ <StatusIcon status={key} category={categoryOf(key)} color={colorOf(key)} icon={iconOf(key)} className="h-3.5 w-3.5 shrink-0" />
+ );
+ const required = plan?.required ?? [];
+ const unchanged = plan?.unchanged ?? [];
+ const moving = required.reduce((sum, r) => sum + r.issue_count, 0);
+ const staying = unchanged.reduce((sum, r) => sum + r.issue_count, 0);
+ const complete = !!plan && required.every((r) => !!mapping[r.status_key]);
+ const separator = t(($) => $.workflows.list_separator);
+
+ const title =
+ variant.kind === "switch"
+ ? t(($) => $.workflows.mapping.switch_title, { project: variant.projectName, workflow: variant.workflowName })
+ : t(($) => $.workflows.mapping.edit_title, { workflow: variant.workflowName });
+ const description =
+ variant.kind === "switch"
+ ? t(($) => $.workflows.mapping.switch_description, {
+ project: variant.projectName,
+ workflow: variant.workflowName,
+ count: plan?.total_issues ?? 0,
+ })
+ : t(($) => $.workflows.mapping.edit_description);
+ const confirmLabel =
+ variant.kind === "switch"
+ ? moving > 0
+ ? t(($) => $.workflows.mapping.confirm_count, { count: moving })
+ : t(($) => $.workflows.mapping.confirm_plain)
+ : t(($) => $.workflows.mapping.confirm_save_count, { count: moving });
+
+ return (
+ <Dialog open={open} onOpenChange={(v) => !pending && onOpenChange(v)}>
+ <DialogContent className="sm:max-w-xl">
+ <DialogHeader>
+ <DialogTitle>{title}</DialogTitle>
+ <DialogDescription>{description}</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-3 py-1">
+ {required.length > 0 && (
+ <div>
+ <p className="text-caption font-medium text-muted-foreground">
+ {t(($) => $.workflows.mapping.needs_mapping, { count: moving })}
+ </p>
+ {required.map((req) => (
+ <div key={req.status_key} className="flex items-center gap-3 py-2">
+ <div className="flex w-44 min-w-0 shrink-0 items-center gap-2">
+ {icon(req.status_key)}
+ <span className="truncate text-body">{labelOf(req.status_key)}</span>
+ <span className="shrink-0 text-caption tabular-nums text-muted-foreground">
+ {t(($) => $.workflows.mapping.issues, { count: req.issue_count })}
+ </span>
+ </div>
+ <ArrowRight aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
+ <Select
+ items={targetKeys.map((key) => ({ value: key, label: labelOf(key) }))}
+ value={mapping[req.status_key] ?? ""}
+ onValueChange={(value) =>
+ value && setMapping((current) => ({ ...current, [req.status_key]: value }))
+ }
+ >
+ <SelectTrigger aria-label={labelOf(req.status_key)} className="min-w-0 flex-1">
+ {mapping[req.status_key] ? (
+ <span className="flex min-w-0 items-center gap-2">
+ {icon(mapping[req.status_key]!)}
+ <span className="truncate">{labelOf(mapping[req.status_key]!)}</span>
+ </span>
+ ) : null}
+ </SelectTrigger>
+ <SelectContent>
+ {targetKeys.map((key) => (
+ <SelectItem key={key} value={key}>
+ <span className="flex items-center gap-2">
+ {icon(key)}
+ <span>{labelOf(key)}</span>
+ </span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ ))}
+ </div>
+ )}
+ {(staying > 0 || required.length === 0) && (
+ <div className="flex items-start gap-2 rounded-lg bg-muted/60 px-3 py-2.5 text-body">
+ <Check aria-hidden className="mt-0.5 size-3.5 shrink-0" />
+ <span>
+ {staying > 0
+ ? t(($) => $.workflows.mapping.unchanged, {
+ count: staying,
+ statuses: unchanged.map((u) => labelOf(u.status_key)).join(separator),
+ })
+ : t(($) => $.workflows.mapping.nothing_moves)}
+ </span>
+ </div>
+ )}
+ <p className="text-caption leading-5 text-muted-foreground">
+ {variant.kind === "switch"
+ ? t(($) => $.workflows.mapping.switch_note)
+ : t(($) => $.workflows.mapping.no_handoff)}
+ </p>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => onOpenChange(false)} disabled={pending}>
+ {t(($) => $.workflows.mapping.cancel)}
+ </Button>
+ <Button onClick={() => onConfirm(mapping)} disabled={!complete || pending} aria-busy={pending}>
+ {pending && <Spinner className="size-3.5" />}
+ {confirmLabel}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/views/workflows/workflow-pill.test.tsx b/packages/views/workflows/workflow-pill.test.tsx
new file mode 100644
index 0000000000..4d9587dfe3
--- /dev/null
+++ b/packages/views/workflows/workflow-pill.test.tsx
@@ -0,0 +1,53 @@
+import { cleanup, fireEvent, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { IssueWorkflow } from "@multica/core/types";
+import { renderWithI18n } from "../test/i18n";
+import { WorkflowPill } from "./workflow-pill";
+
+function workflow(id: string, name: string, isDefault: boolean): IssueWorkflow {
+ return {
+ id,
+ workspace_id: "workspace-1",
+ name,
+ description: "",
+ is_default: isDefault,
+ steps: [],
+ project_ids: [],
+ created_at: "",
+ updated_at: "",
+ };
+}
+
+vi.mock("@multica/core/config", () => ({ useFeatureEnabled: () => true }));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));
+const workflows = vi.hoisted(() => ({ list: [] as IssueWorkflow[] }));
+vi.mock("@multica/core/issue-workflows", () => ({
+ useIssueWorkflows: () => ({ workflows: workflows.list }),
+}));
+
+beforeEach(() => {
+ workflows.list = [workflow("wf-default", "Default", true), workflow("wf-delivery", "Delivery", false)];
+});
+afterEach(cleanup);
+
+describe("WorkflowPill", () => {
+ it("opens the workflow list and reports the choice", async () => {
+ const onChange = vi.fn();
+ renderWithI18n(<WorkflowPill value={null} onChange={onChange} />);
+
+ fireEvent.click(screen.getByRole("button", { name: /Default/ }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: /Delivery/ }));
+
+ expect(onChange).toHaveBeenCalledWith("wf-delivery");
+ });
+
+ it("shows Default and where to create more when it is the only workflow", async () => {
+ workflows.list = [workflow("wf-default", "Default", true)];
+ renderWithI18n(<WorkflowPill value={null} onChange={vi.fn()} />);
+
+ fireEvent.click(screen.getByRole("button", { name: /Default/ }));
+
+ expect(await screen.findByRole("menuitem", { name: /Default/ })).toBeTruthy();
+ expect(screen.getByText(/Settings → Workflows/)).toBeTruthy();
+ });
+});
diff --git a/packages/views/workflows/workflow-pill.tsx b/packages/views/workflows/workflow-pill.tsx
new file mode 100644
index 0000000000..c0b3d04708
--- /dev/null
+++ b/packages/views/workflows/workflow-pill.tsx
@@ -0,0 +1,74 @@
+"use client";
+
+import { Check, Workflow } from "lucide-react";
+import { useFeatureEnabled } from "@multica/core/config";
+import { PROJECT_WORKFLOWS_V1_FLAG } from "@multica/core/feature-flags";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useIssueWorkflows } from "@multica/core/issue-workflows";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { PillButton } from "../common/pill-button";
+import { useT } from "../i18n";
+
+/**
+ * The workflow a new project starts on (MUL-7420); null is Default. Shown
+ * while workflows are on, so the choice is visible even before the workspace
+ * has more than Default.
+ */
+export function WorkflowPill({
+ value,
+ onChange,
+}: {
+ value: string | null;
+ onChange: (workflowId: string | null) => void;
+}) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const enabled = useFeatureEnabled(PROJECT_WORKFLOWS_V1_FLAG, false);
+ const { workflows } = useIssueWorkflows(wsId);
+ const named = workflows.filter((w) => !w.is_default);
+ if (!enabled) return null;
+ const defaultName = workflows.find((w) => w.is_default)?.name ?? t(($) => $.workflows.default_name);
+ const current = named.find((w) => w.id === value);
+ const options = [{ id: null as string | null, name: defaultName, columns: workflows.find((w) => w.is_default)?.steps.length }, ...named.map((w) => ({ id: w.id as string | null, name: w.name, columns: w.steps.length }))];
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <PillButton>
+ <Workflow className="size-3" />
+ <span className="max-w-[10rem] truncate">{current?.name ?? defaultName}</span>
+ </PillButton>
+ }
+ />
+ <DropdownMenuContent align="start" className="w-60">
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{t(($) => $.workflows.project.picker_title)}</DropdownMenuLabel>
+ {options.map((option) => (
+ <DropdownMenuItem key={option.id ?? "default"} onClick={() => onChange(option.id)}>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate">{option.name}</span>
+ {option.columns !== undefined && (
+ <span className="block text-caption text-muted-foreground">
+ {t(($) => $.workflows.settings.statuses, { count: option.columns })}
+ </span>
+ )}
+ </span>
+ {option.id === (current?.id ?? null) && <Check className="size-3.5 shrink-0" />}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuGroup>
+ <p className="border-t border-surface-border px-2 pb-1 pt-2 text-caption leading-5 text-muted-foreground">
+ {t(($) => $.workflows.project.picker_more)}
+ </p>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/packages/views/workflows/workflows-tab.tsx b/packages/views/workflows/workflows-tab.tsx
new file mode 100644
index 0000000000..f591e1584e
--- /dev/null
+++ b/packages/views/workflows/workflows-tab.tsx
@@ -0,0 +1,290 @@
+"use client";
+
+import { Fragment, useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { ChevronDown, ChevronRight, LayoutTemplate, Plus } from "lucide-react";
+import { useAuthStore } from "@multica/core/auth";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { statusColumnKeys } from "@multica/core/issues";
+import { useIssueWorkflows } from "@multica/core/issue-workflows";
+import { projectListOptions } from "@multica/core/projects/queries";
+import { memberListOptions } from "@multica/core/workspace/queries";
+import type { IssueWorkflow, IssueWorkflowStep, Project } from "@multica/core/types";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { ActorAvatar } from "../common/actor-avatar";
+import { StatusIcon } from "../issues/components/status-icon";
+import { useStatusLabel } from "../issues/utils/status-label";
+import { useNavigation } from "../navigation";
+import { IssueStatusesTab } from "../settings/components/issue-statuses-tab";
+import { SettingsTab } from "../settings/components/settings-layout";
+import { useT } from "../i18n";
+import { WORKFLOW_TEMPLATES, type WorkflowTemplateId } from "./templates";
+import { WorkflowEditorPage } from "./workflow-editor-page";
+
+const WORKFLOW_PARAM = "workflow";
+const DUPLICATE_PARAM = "from";
+const TEMPLATE_PARAM = "template";
+const NEW_WORKFLOW = "new";
+
+/**
+ * Settings → Workflows (MUL-7420): the workflows, then the status library
+ * they all draw from. `?workflow=<id>` (or `new`) opens the editor in place,
+ * so a workflow is a linkable page rather than a dialog.
+ */
+export function WorkflowsTab() {
+ const { t } = useT("issues");
+ const navigation = useNavigation();
+ const wsId = useWorkspaceId();
+ const { workflows, isLoaded } = useIssueWorkflows(wsId);
+ const { data: projects = [] } = useQuery(projectListOptions(wsId));
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const currentUser = useAuthStore((s) => s.user);
+ const role = members.find((m) => m.user_id === currentUser?.id)?.role;
+ const isAdmin = role === "owner" || role === "admin";
+
+ const open = navigation.searchParams.get(WORKFLOW_PARAM);
+ const duplicateOf = navigation.searchParams.get(DUPLICATE_PARAM);
+ const templateParam = navigation.searchParams.get(TEMPLATE_PARAM);
+ const template = WORKFLOW_TEMPLATES.find((tpl) => tpl.id === templateParam)?.id ?? null;
+ const hrefWith = (params: Record<string, string | null>) => {
+ const next = new URLSearchParams(navigation.searchParams);
+ for (const [key, value] of Object.entries(params)) {
+ if (value === null) next.delete(key);
+ else next.set(key, value);
+ }
+ return `${navigation.pathname}?${next.toString()}`;
+ };
+ const openEditor = (id: string, from: WorkflowTemplateId | null = null) =>
+ navigation.push(hrefWith({ [WORKFLOW_PARAM]: id, [DUPLICATE_PARAM]: null, [TEMPLATE_PARAM]: from }));
+ const backToList = () =>
+ navigation.push(hrefWith({ [WORKFLOW_PARAM]: null, [DUPLICATE_PARAM]: null, [TEMPLATE_PARAM]: null }));
+
+ const usage = useMemo(() => {
+ const counts = new Map<string, number>();
+ for (const workflow of workflows) {
+ if (workflow.is_default) continue;
+ for (const step of workflow.steps) counts.set(step.status_key, (counts.get(step.status_key) ?? 0) + 1);
+ }
+ return (key: string) => counts.get(key) ?? 0;
+ }, [workflows]);
+
+ if (open) {
+ const seed = open === NEW_WORKFLOW && duplicateOf ? workflows.find((w) => w.id === duplicateOf) ?? null : null;
+ return (
+ <WorkflowEditorPage
+ key={`${open}:${duplicateOf ?? ""}:${template ?? ""}`}
+ workflowId={open === NEW_WORKFLOW ? null : open}
+ seed={seed}
+ template={open === NEW_WORKFLOW && !duplicateOf ? template : null}
+ canEdit={isAdmin}
+ onBack={backToList}
+ onOpen={(target) =>
+ "id" in target
+ ? navigation.replace(hrefWith({ [WORKFLOW_PARAM]: target.id, [DUPLICATE_PARAM]: null, [TEMPLATE_PARAM]: null }))
+ : navigation.push(
+ hrefWith({ [WORKFLOW_PARAM]: NEW_WORKFLOW, [DUPLICATE_PARAM]: target.duplicateOf, [TEMPLATE_PARAM]: null }),
+ )
+ }
+ />
+ );
+ }
+
+ const defaultProjects = projects.filter((p) => !p.workflow_id);
+ const defaultRow = workflows.find((w) => w.is_default);
+
+ return (
+ <SettingsTab
+ title={t(($) => $.workflows.settings.title)}
+ actions={
+ isAdmin && (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button variant="outline" className="gap-1.5">
+ <Plus className="size-3.5" />
+ {t(($) => $.workflows.settings.new)}
+ <ChevronDown className="size-3" />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end" className="w-72">
+ <DropdownMenuItem onClick={() => openEditor(NEW_WORKFLOW)}>
+ <Plus className="size-3.5" />
+ {t(($) => $.workflows.settings.new_blank)}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{t(($) => $.workflows.settings.from_template)}</DropdownMenuLabel>
+ {WORKFLOW_TEMPLATES.map((tpl) => (
+ <DropdownMenuItem key={tpl.id} className="items-start py-2" onClick={() => openEditor(NEW_WORKFLOW, tpl.id)}>
+ <LayoutTemplate className="mt-0.5 size-3.5" />
+ <span className="min-w-0">
+ <span className="block font-medium">{t(($) => $.workflows.templates[tpl.id].name)}</span>
+ <span className="block text-caption text-muted-foreground">
+ {t(($) => $.workflows.templates[tpl.id].summary)}
+ </span>
+ </span>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+ }
+ >
+ <div className="divide-y divide-surface-border overflow-hidden rounded-lg border border-surface-border bg-card">
+ {defaultRow ? (
+ <WorkflowRow workflow={defaultRow} projects={defaultProjects} onOpen={() => openEditor(defaultRow.id)} />
+ ) : (
+ <DefaultWorkflowRow projects={defaultProjects} />
+ )}
+ {isLoaded &&
+ workflows.filter((w) => !w.is_default).map((workflow) => (
+ <WorkflowRow
+ key={workflow.id}
+ workflow={workflow}
+ projects={projects.filter((p) => workflow.project_ids.includes(p.id))}
+ onOpen={() => openEditor(workflow.id)}
+ />
+ ))}
+ </div>
+
+ <IssueStatusesTab
+ embedded={{ title: t(($) => $.workflows.settings.statuses_title) }}
+ workflowUsage={usage}
+ />
+ </SettingsTab>
+ );
+}
+
+/** The implicit workflow of every project without one: the library itself. */
+function DefaultWorkflowRow({ projects }: { projects: Project[] }) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const catalog = useIssueStatuses(wsId);
+ const keys = statusColumnKeys(catalog);
+ const separator = t(($) => $.workflows.list_separator);
+ return (
+ <button
+ type="button"
+ className="flex w-full items-center gap-4 px-4 py-3.5 text-left transition-colors hover:bg-accent/40"
+ onClick={() => document.getElementById("status-library")?.scrollIntoView({ behavior: "smooth", block: "start" })}
+ >
+ <div className="min-w-0 flex-1 space-y-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-body font-semibold">{t(($) => $.workflows.default_name)}</span>
+ </div>
+ <StepChain steps={keys.map((key) => ({ status_key: key, handler: { type: "none" }, instructions: "" }))} />
+ <p className="text-caption text-muted-foreground">
+ {projects.length > 0
+ ? t(($) => $.workflows.settings.used_by_default, {
+ count: projects.length,
+ names: projects.map((p) => p.title).join(separator),
+ })
+ : t(($) => $.workflows.settings.used_by_default_none)}
+ </p>
+ </div>
+ <ChevronRight aria-hidden className="size-4 shrink-0 text-muted-foreground" />
+ </button>
+ );
+}
+
+function WorkflowRow({
+ workflow,
+ projects,
+ onOpen,
+}: {
+ workflow: IssueWorkflow;
+ projects: Project[];
+ onOpen: () => void;
+}) {
+ const { t } = useT("issues");
+ const separator = t(($) => $.workflows.list_separator);
+ return (
+ <button
+ type="button"
+ onClick={onOpen}
+ className="flex w-full items-center gap-4 px-4 py-3.5 text-left transition-colors hover:bg-accent/40"
+ >
+ <div className="min-w-0 flex-1 space-y-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-body font-semibold">{workflow.name}</span>
+ {workflow.description && (
+ <span className="truncate text-caption text-muted-foreground">{workflow.description}</span>
+ )}
+ </div>
+ <StepChain steps={workflow.steps} />
+ <p className="text-caption text-muted-foreground">
+ {workflow.is_default
+ ? projects.length > 0
+ ? t(($) => $.workflows.settings.used_by_default, {
+ count: projects.length,
+ names: projects.map((p) => p.title).join(separator),
+ })
+ : t(($) => $.workflows.settings.used_by_default_none)
+ : projects.length > 0
+ ? t(($) => $.workflows.settings.used_by, {
+ count: projects.length,
+ names: projects.map((p) => p.title).join(separator),
+ })
+ : t(($) => $.workflows.settings.no_projects)}
+ </p>
+ </div>
+ <ChevronRight aria-hidden className="size-4 shrink-0 text-muted-foreground" />
+ </button>
+ );
+}
+
+/**
+ * A workflow's steps as a chain of chips, each with its handler. Side states
+ * (the closed category and `blocked`) are left out so the chain reads as the
+ * path an issue takes.
+ */
+function StepChain({ steps }: { steps: IssueWorkflowStep[] }) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const catalog = useIssueStatuses(wsId);
+ const labelOf = useStatusLabel(wsId);
+ const path = steps.filter((s) => s.status_key !== "blocked" && catalog.categoryOf(s.status_key) !== "closed");
+ return (
+ <div className="flex flex-wrap items-center gap-x-1 gap-y-1.5">
+ {path.map((step, index) => {
+ const { type, id } = step.handler;
+ return (
+ <Fragment key={step.status_key}>
+ {index > 0 && <ChevronRight aria-hidden className="size-3 text-muted-foreground" />}
+ <span className="inline-flex items-center gap-1.5 rounded-full border border-surface-border px-2 py-0.5 text-caption">
+ <StatusIcon
+ status={step.status_key}
+ category={catalog.categoryOf(step.status_key)}
+ color={catalog.colorOf(step.status_key)}
+ icon={catalog.iconOf(step.status_key)}
+ className="h-3 w-3"
+ />
+ {labelOf(step.status_key)}
+ {(type === "agent" || type === "squad" || type === "member") && id && (
+ <ActorAvatar actorType={type} actorId={id} size="xs" profileLink={false} />
+ )}
+ {type === "project_lead" && (
+ <span className="text-muted-foreground">· {t(($) => $.workflows.handler.project_lead)}</span>
+ )}
+ {type === "creator" && (
+ <span className="text-muted-foreground">· {t(($) => $.workflows.handler.creator)}</span>
+ )}
+ </span>
+ </Fragment>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index b754ad06d2..cece0fdddb 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -150,6 +150,9 @@ var concurrentIndexCleanups = map[string]string{
"546_issue_pr_automation_workspace_index": "idx_issue_pr_automation_workspace",
"547_issue_pull_request_exclusion_workspace_index": "idx_issue_pull_request_exclusion_workspace",
"548_task_supplement_comment_task_index": "task_supplement_comment_task_uidx",
+ "574_issue_workflow_pkey_index": "issue_workflow_pkey_uidx",
+ "576_issue_workflow_workspace_name_index": "idx_issue_workflow_workspace_name",
+ "582_issue_workflow_default_index": "idx_issue_workflow_workspace_default",
"554_wakeup_expiry_index": "issue_wakeup_expiry_idx",
"556_wakeup_system_rule_index": "issue_wakeup_system_rule_idx",
"559_issue_child_event_id": "issue_child_event_id_idx",
diff --git a/server/cmd/server/activity_listeners.go b/server/cmd/server/activity_listeners.go
index 9ee19a2cea..ec97ab4804 100644
--- a/server/cmd/server/activity_listeners.go
+++ b/server/cmd/server/activity_listeners.go
@@ -76,12 +76,23 @@ func registerActivityListeners(bus *events.Bus, queries *db.Queries) {
assigneeChanged, _ := payload["assignee_changed"].(bool)
descriptionChanged, _ := payload["description_changed"].(bool)
+ // A workflow handoff (MUL-7420) rides on the status row: entering the
+ // step is what moved the issue to its handler, so the timeline shows
+ // one entry and the separate assignee row would only repeat it.
+ handoff, _ := payload["workflow_handoff"].(map[string]string)
+ if statusChanged && handoff != nil {
+ assigneeChanged = false
+ }
+
if statusChanged {
prevStatus, _ := payload["prev_status"].(string)
detailsMap := map[string]string{
"from": prevStatus,
"to": issue.Status,
}
+ for k, v := range handoff {
+ detailsMap["handoff_"+k] = v
+ }
// PR auto-complete (MUL-7429): say why the status moved, so the
// timeline explains the change without a hidden rule.
if source, _ := payload["source"].(string); source == "pr_automation" {
diff --git a/server/cmd/server/activity_listeners_test.go b/server/cmd/server/activity_listeners_test.go
index 1bcd3f4a3a..d6a8156306 100644
--- a/server/cmd/server/activity_listeners_test.go
+++ b/server/cmd/server/activity_listeners_test.go
@@ -244,6 +244,68 @@ func TestActivityIssueUpdated_AssigneeChanged(t *testing.T) {
}
}
+// TestActivityIssueUpdated_WorkflowHandoff pins the merged timeline entry for
+// a workflow handoff (MUL-7420): one status row carrying who the issue went
+// to and the brief, and no separate assignee row repeating it.
+func TestActivityIssueUpdated_WorkflowHandoff(t *testing.T) {
+ queries := db.New(testPool)
+ bus := events.New()
+ registerActivityListeners(bus, queries)
+
+ issueID := createTestIssue(t, testWorkspaceID, testUserID)
+ t.Cleanup(func() {
+ cleanupActivities(t, issueID)
+ cleanupTestIssue(t, issueID)
+ })
+
+ agentType := "agent"
+ agentID := "0f0e0d0c-0b0a-4909-8807-060504030201"
+ bus.Publish(events.Event{
+ Type: protocol.EventIssueUpdated,
+ WorkspaceID: testWorkspaceID,
+ ActorType: "member",
+ ActorID: testUserID,
+ Payload: map[string]any{
+ "issue": handler.IssueResponse{
+ ID: issueID,
+ WorkspaceID: testWorkspaceID,
+ Title: "activity test issue",
+ Status: "code_review",
+ Priority: "medium",
+ CreatorType: "member",
+ CreatorID: testUserID,
+ AssigneeType: &agentType,
+ AssigneeID: &agentID,
+ },
+ "status_changed": true,
+ "prev_status": "implement",
+ "assignee_changed": true,
+ "prev_assignee_type": (*string)(nil),
+ "prev_assignee_id": (*string)(nil),
+ "workflow_handoff": map[string]string{
+ "workflow": "Delivery", "to_type": "agent", "to_id": agentID, "run": "true", "note": "Review the PR.",
+ },
+ },
+ })
+
+ activities := listActivitiesForIssue(t, queries, issueID)
+ if len(activities) != 1 || activities[0].Action != "status_changed" {
+ t.Fatalf("expected one status_changed activity, got %+v", activities)
+ }
+ var details map[string]string
+ if err := json.Unmarshal(activities[0].Details, &details); err != nil {
+ t.Fatalf("failed to unmarshal details: %v", err)
+ }
+ for key, want := range map[string]string{
+ "from": "implement", "to": "code_review", "handoff_workflow": "Delivery",
+ "handoff_to_type": "agent", "handoff_to_id": agentID, "handoff_run": "true", "handoff_note": "Review the PR.",
+ } {
+ if details[key] != want {
+ t.Fatalf("details[%q] = %q, want %q (all: %v)", key, details[key], want, details)
+ }
+ }
+}
+
func TestActivityIssueUpdated_NoChangeFlags(t *testing.T) {
queries := db.New(testPool)
bus := events.New()
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 6bad7ffb5d..707351265d 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -2026,6 +2026,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/comments", h.CreateComment)
r.Get("/comments", h.ListComments)
r.Get("/timeline", h.ListTimeline)
+ r.Get("/workflow-handoff", h.PreviewWorkflowHandoff)
r.Get("/subscribers", h.ListIssueSubscribers)
r.Post("/subscribe", h.SubscribeToIssue)
r.Post("/unsubscribe", h.UnsubscribeFromIssue)
@@ -2120,6 +2121,21 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
})
})
+ // Project workflows (MUL-7420). Reads are open to any member; writes
+ // are gated inside the handlers to workspace owners/admins and, for
+ // switching a project's workflow, its lead.
+ r.Route("/api/issue-workflows", func(r chi.Router) {
+ r.Get("/", h.ListIssueWorkflows)
+ r.Post("/", h.CreateIssueWorkflow)
+ r.Route("/{id}", func(r chi.Router) {
+ r.Get("/", h.GetIssueWorkflow)
+ r.Patch("/", h.UpdateIssueWorkflow)
+ r.Delete("/", h.DeleteIssueWorkflow)
+ r.Put("/handoffs/{status}", h.SetIssueWorkflowHandoff)
+ r.Post("/brief", h.PreviewIssueWorkflowBrief)
+ })
+ })
+
// Projects
r.Route("/api/projects", func(r chi.Router) {
r.Get("/search", h.SearchProjects)
@@ -2129,6 +2145,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/", h.GetProject)
r.Put("/", h.UpdateProject)
r.Delete("/", h.DeleteProject)
+ r.Post("/workflow", h.SetProjectWorkflow)
r.Get("/resources", h.ListProjectResources)
r.Post("/resources", h.CreateProjectResource)
r.Put("/resources/{resourceId}", h.UpdateProjectResource)
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 39af184c71..7b2696f855 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -10011,6 +10011,20 @@ func convertIssueStatusesForEnv(statuses []IssueStatusData) []execenv.IssueStatu
return result
}
+func convertProjectWorkflowForEnv(w *ProjectWorkflowData) *execenv.ProjectWorkflowForEnv {
+ if w == nil || len(w.Steps) == 0 {
+ return nil
+ }
+ steps := make([]execenv.ProjectWorkflowStepForEnv, len(w.Steps))
+ for i, s := range w.Steps {
+ steps[i] = execenv.ProjectWorkflowStepForEnv{
+ Key: s.Key, Name: s.Name, Handler: s.Handler, Instructions: s.Instructions,
+ NextStatusKey: s.NextStatusKey, BackStatusKey: s.BackStatusKey,
+ }
+ }
+ return &execenv.ProjectWorkflowForEnv{Name: w.Name, CurrentStatusKey: w.CurrentStatusKey, Steps: steps}
+}
+
func convertReposForEnv(repos []RepoData) []execenv.RepoContextForEnv {
if len(repos) == 0 {
return nil
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index a6f908e362..e1405e28d7 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -248,6 +248,25 @@ type IssueStatusForEnv struct {
Description string
}
+// ProjectWorkflowForEnv is the workflow of the issue's project (MUL-7420),
+// present only when that project's workflow hands off. It is rendered into
+// the per-turn prompt by BuildProjectWorkflowBlock and never into the brief:
+// it varies by project and the current step by run.
+type ProjectWorkflowForEnv struct {
+ Name string
+ CurrentStatusKey string
+ Steps []ProjectWorkflowStepForEnv
+}
+
+type ProjectWorkflowStepForEnv struct {
+ Key string
+ Name string
+ Handler string
+ Instructions string
+ NextStatusKey string
+ BackStatusKey string
+}
+
type SkillContextForEnv struct {
Name string
Description string
diff --git a/server/internal/daemon/execenv/runtime_config_project_workflow_test.go b/server/internal/daemon/execenv/runtime_config_project_workflow_test.go
new file mode 100644
index 0000000000..ee0046119d
--- /dev/null
+++ b/server/internal/daemon/execenv/runtime_config_project_workflow_test.go
@@ -0,0 +1,68 @@
+package execenv
+
+import (
+ "strings"
+ "testing"
+)
+
+// Project workflow block of the per-turn prompt (MUL-7420). The brief has no
+// workflow input at all: TaskContextForEnv carries none, so neither the
+// project nor the current step can reach the cached prefix (MUL-5377).
+
+func TestProjectWorkflowBlockEmptyRendersNothing(t *testing.T) {
+ t.Parallel()
+ if got := BuildProjectWorkflowBlock(nil, "issue-1"); got != "" {
+ t.Fatalf("nil workflow rendered %q", got)
+ }
+ if got := BuildProjectWorkflowBlock(&ProjectWorkflowForEnv{Name: "Delivery"}, "issue-1"); got != "" {
+ t.Fatalf("a workflow without steps rendered %q", got)
+ }
+}
+
+func TestProjectWorkflowBlockRendersStepsAndExits(t *testing.T) {
+ t.Parallel()
+ out := BuildProjectWorkflowBlock(&ProjectWorkflowForEnv{
+ Name: "Delivery",
+ CurrentStatusKey: "implement",
+ Steps: []ProjectWorkflowStepForEnv{
+ {Key: "todo", Name: "Todo"},
+ {Key: "implement", Name: "Implement", Handler: "Forge", Instructions: "Open a PR.\nLink it here.", NextStatusKey: "code_review"},
+ {Key: "code_review", Name: "Code review", Handler: "Sentinel", NextStatusKey: "done", BackStatusKey: "implement"},
+ {Key: "done", Name: "Done"},
+ },
+ }, "issue-1")
+ for _, want := range []string{
+ "[Project workflow: Delivery]\n",
+ "finish your step by moving to the step's next status instead",
+ "- `todo` Todo\n",
+ "- `implement` Implement — hands off to Forge (current)\n",
+ "- `code_review` Code review — hands off to Sentinel\n",
+ "> Open a PR.\n> Link it here.\n",
+ "- Step done → `multica issue status issue-1 code_review`\n",
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("block is missing %q\n---\n%s", want, out)
+ }
+ }
+ if strings.Contains(out, "Needs changes →") {
+ t.Errorf("the current step has no back status, so no needs-changes exit may render")
+ }
+}
+
+func TestProjectWorkflowBlockSanitizesUserText(t *testing.T) {
+ t.Parallel()
+ out := BuildProjectWorkflowBlock(&ProjectWorkflowForEnv{
+ Name: "Flow\n## Injected",
+ CurrentStatusKey: "a",
+ Steps: []ProjectWorkflowStepForEnv{
+ {Key: "a", Name: "Step\n# Heading"},
+ {Key: "bad key`", Name: "Dropped"},
+ },
+ }, "issue-1")
+ if strings.Contains(out, "\n## Injected") || strings.Contains(out, "\n# Heading") {
+ t.Fatalf("user-authored names must not inject headings\n---\n%s", out)
+ }
+ if strings.Contains(out, "Dropped") {
+ t.Errorf("a step whose key is not a code token must be dropped")
+ }
+}
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index 92ebda662a..3e74d8326a 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -615,6 +615,74 @@ func writeWorkflowIssue(b *strings.Builder, ctx TaskContextForEnv) {
b.WriteString("- Your turn produced none of the issue's own deliverable — you answered a question or consulted on work owned elsewhere → write nothing, at any point; questions, discussion, and acknowledgements never touch status. This no-write default is what keeps concurrent runs from flapping the board.\n\n")
}
+// BuildProjectWorkflowBlock renders the issue's project workflow (MUL-7420)
+// for the per-turn prompt: its statuses in board order, who each step hands
+// the issue to, and the current step's instructions and exits. Moving the
+// issue into a step with a handler reassigns it to that handler, which is how
+// work passes along the workflow; nothing advances the status when a run ends.
+//
+// Names, handlers and instructions are user-authored and pass through the
+// same sanitizers as the status catalog; a step whose key fails the code-token
+// check is dropped.
+func BuildProjectWorkflowBlock(w *ProjectWorkflowForEnv, issueID string) string {
+ if w == nil || len(w.Steps) == 0 {
+ return ""
+ }
+ var sb strings.Builder
+ b := &sb
+ fmt.Fprintf(b, "[Project workflow: %s]\n", sanitizeNameForBriefMarkdown(w.Name))
+ b.WriteString("This issue's status can only be one of the keys below. Where a status rule names a key this workflow does not list — `in_review` on delivery, for example — finish your step by moving to the step's next status instead. Moving the issue into a step that hands off reassigns it to that step's handler and starts their run; the system never advances the status when a run ends. Each step's handler gets a run when the issue enters that step, so do not use `multica issue wakeup` to watch this issue's status, assignee or runs; use wakeups only to wait for a time or for something outside this issue.\n\n")
+ var current *ProjectWorkflowStepForEnv
+ for i := range w.Steps {
+ s := &w.Steps[i]
+ key := sanitizeBriefCodeToken(s.Key)
+ if key == "" {
+ continue
+ }
+ fmt.Fprintf(b, "- `%s`", key)
+ if name := sanitizeNameForBriefMarkdown(s.Name); name != "" {
+ fmt.Fprintf(b, " %s", name)
+ }
+ if handler := sanitizeNameForBriefMarkdown(s.Handler); handler != "" {
+ fmt.Fprintf(b, " — hands off to %s", handler)
+ }
+ if s.Key == w.CurrentStatusKey {
+ b.WriteString(" (current)")
+ current = s
+ }
+ b.WriteString("\n")
+ }
+ b.WriteString("\n")
+ if current == nil {
+ return sb.String()
+ }
+ if instructions := strings.TrimSpace(current.Instructions); instructions != "" {
+ b.WriteString("Current step instructions:\n")
+ for _, line := range strings.Split(instructions, "\n") {
+ b.WriteString("> ")
+ b.WriteString(line)
+ b.WriteString("\n")
+ }
+ b.WriteString("\n")
+ }
+ next := sanitizeBriefCodeToken(current.NextStatusKey)
+ back := sanitizeBriefCodeToken(current.BackStatusKey)
+ id := sanitizeBriefCodeToken(issueID)
+ if id == "" {
+ id = "<id>"
+ }
+ if next != "" {
+ fmt.Fprintf(b, "- Step done → `multica issue status %s %s`\n", id, next)
+ }
+ if back != "" {
+ fmt.Fprintf(b, "- Needs changes → `multica issue status %s %s`\n", id, back)
+ }
+ if next != "" || back != "" {
+ b.WriteString("\n")
+ }
+ return sb.String()
+}
+
// writeSubIssueCreation emits the Sub-issue Creation section.
//
// MUL-5442 demotes the full todo/backlog/stage playbook to the multica-platform
diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.go
index b8ce727c51..1cba6be69d 100644
--- a/server/internal/daemon/prompt.go
+++ b/server/internal/daemon/prompt.go
@@ -70,9 +70,21 @@ func perTurnContextBlocks(task Task, opts promptOpts) string {
b.WriteString(execenv.BuildOnBehalfOfBlock(task.InitiatorName, task.InitiatorEmail))
b.WriteString(execenv.BuildConnectedAppsBlock(task.ConnectedApps))
b.WriteString(buildJoinedWakeupsBlock(task.WakeupJoined))
+ b.WriteString(buildProjectWorkflowBlock(task))
return b.String()
}
+// buildProjectWorkflowBlock carries the issue's project workflow and current
+// step (MUL-7420). It varies by project and by step, so it lives here and not
+// in the cached brief (MUL-5377). A handoff run already got the same workflow
+// and step brief as its handoff note, so it is not repeated.
+func buildProjectWorkflowBlock(task Task) string {
+ if task.ProjectWorkflow == nil || (task.HandoffNote != "" && task.WakeupID == "") {
+ return ""
+ }
+ return execenv.BuildProjectWorkflowBlock(convertProjectWorkflowForEnv(task.ProjectWorkflow), task.IssueID)
+}
+
// buildJoinedWakeupsBlock carries wakeups that fired while this run was
// waiting to start. The server folded them into this run instead of queuing a
// second run of the same agent on the issue, so this run handles them too.
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index aae6a3722a..cdecd2de24 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -65,6 +65,24 @@ type IssueStatusData struct {
Description string `json:"description,omitempty"`
}
+// ProjectWorkflowData mirrors the claim payload's project workflow (MUL-7420):
+// the statuses the issue's project uses, in board order, and who each step
+// hands the issue to.
+type ProjectWorkflowData struct {
+ Name string `json:"name"`
+ CurrentStatusKey string `json:"current_status_key"`
+ Steps []ProjectWorkflowStepData `json:"steps"`
+}
+
+type ProjectWorkflowStepData struct {
+ Key string `json:"key"`
+ Name string `json:"name"`
+ Handler string `json:"handler,omitempty"`
+ Instructions string `json:"instructions,omitempty"`
+ NextStatusKey string `json:"next_status_key,omitempty"`
+ BackStatusKey string `json:"back_status_key,omitempty"`
+}
+
// Task represents a claimed task from the server.
// Agent data (name, skills) is populated by the claim endpoint.
type Task struct {
@@ -98,6 +116,7 @@ type Task struct {
// the built-in-only form. IssueStatusesOmitted is the cap overflow count.
IssueStatuses []IssueStatusData `json:"issue_statuses,omitempty"`
IssueStatusesOmitted int `json:"issue_statuses_omitted,omitempty"`
+ ProjectWorkflow *ProjectWorkflowData `json:"project_workflow,omitempty"`
ThreadName string `json:"thread_name,omitempty"` // semantic title for provider-native session/thread history
Agent *AgentData `json:"agent,omitempty"`
ConnectedApps []ConnectedAppData `json:"connected_apps,omitempty"` // per-run app capabilities mounted through runtime MCP overlays
diff --git a/server/internal/daemon/workflow_prompt_test.go b/server/internal/daemon/workflow_prompt_test.go
new file mode 100644
index 0000000000..dfbb3bedaa
--- /dev/null
+++ b/server/internal/daemon/workflow_prompt_test.go
@@ -0,0 +1,56 @@
+package daemon
+
+import (
+ "strings"
+ "testing"
+)
+
+func deliveryWorkflowAt(step string) *ProjectWorkflowData {
+ return &ProjectWorkflowData{
+ Name: "Delivery",
+ CurrentStatusKey: step,
+ Steps: []ProjectWorkflowStepData{
+ {Key: "todo"},
+ {Key: "in_progress", Handler: "Forge", Instructions: "Open a PR.", NextStatusKey: "in_review"},
+ {Key: "in_review", Handler: "Forge", Instructions: "Review your own PR.", NextStatusKey: "done", BackStatusKey: "in_progress"},
+ {Key: "done"},
+ },
+ }
+}
+
+// The workflow and its current step are per-turn context (MUL-7420): appended
+// after everything else, so the prompt ahead of it is the same whatever step
+// the issue is at (MUL-5377).
+func TestBuildPromptAppendsProjectWorkflowBlock(t *testing.T) {
+ base := Task{IssueID: "issue-1", TriggerCommentID: "c-1", TriggerCommentContent: "please continue"}
+ plain := BuildPrompt(base, "claude")
+
+ for _, step := range []string{"in_progress", "in_review"} {
+ task := base
+ task.ProjectWorkflow = deliveryWorkflowAt(step)
+ out := BuildPrompt(task, "claude")
+ if !strings.HasPrefix(out, plain) {
+ t.Fatalf("step %s: the workflow block must be appended, not change the prompt ahead of it", step)
+ }
+ block := out[len(plain):]
+ for _, want := range []string{"[Project workflow: Delivery]", "- `" + step + "`", "(current)", "multica issue status issue-1 "} {
+ if !strings.Contains(block, want) {
+ t.Errorf("step %s: block is missing %q\n---\n%s", step, want, block)
+ }
+ }
+ }
+}
+
+func TestBuildPromptSkipsWorkflowBlockForHandoffRun(t *testing.T) {
+ task := Task{IssueID: "issue-1", HandoffNote: "This project's workflow — Delivery\nYou are handling the step.", ProjectWorkflow: deliveryWorkflowAt("in_progress")}
+ if out := BuildPrompt(task, "claude"); strings.Contains(out, "[Project workflow:") {
+ t.Fatalf("a handoff run already has the workflow in its note:\n%s", out)
+ }
+}
+
+func TestBuildPromptKeepsWorkflowBlockForWakeup(t *testing.T) {
+ task := Task{IssueID: "issue-1", WakeupID: "w-1", HandoffNote: "check the PR", ProjectWorkflow: deliveryWorkflowAt("in_review")}
+ if out := BuildPrompt(task, "claude"); !strings.Contains(out, "[Project workflow: Delivery]") {
+ t.Fatalf("a wakeup's note is not the workflow brief, so the block must render:\n%s", out)
+ }
+}
diff --git a/server/internal/featureflags/keys.go b/server/internal/featureflags/keys.go
index ca8e9c5d8c..7a1fa60726 100644
--- a/server/internal/featureflags/keys.go
+++ b/server/internal/featureflags/keys.go
@@ -30,6 +30,12 @@ const (
// either way. Turning it off stops new intake and triage runs but leaves
// existing Triage issues workable.
TriageV1 = "triage_v1"
+ // ProjectWorkflowsV1 gates project workflows (MUL-7420): creating a
+ // workflow and pointing a project at one, plus the Settings → Workflows
+ // and project workflow UI. Turning it off stops new adoption but leaves
+ // workflows already in use working, and a project can always switch back
+ // to the Default workflow.
+ ProjectWorkflowsV1 = "project_workflows_v1"
// LocalSearchIndex gates the sync endpoints behind Web/Desktop local search
// (MUL-7754). On by default. Turning it off (FF_LOCAL_SEARCH_INDEX=off)
// makes those endpoints answer 404, so clients stop syncing and search
@@ -56,6 +62,7 @@ var frontendPublicFlags = []string{
BillingWorkspaceSubscriptions,
ComposioMCPApps,
PluginsV1,
+ ProjectWorkflowsV1,
}
func BillingWorkspaceSubscriptionsEnabled(ctx context.Context, flags *featureflag.Service) bool {
@@ -88,3 +95,7 @@ func EvaluateFrontendPublicFlags(ctx context.Context, flags *featureflag.Service
out[resourceLabelsCompat] = true
return out
}
+
+func ProjectWorkflowsV1Enabled(ctx context.Context, flags *featureflag.Service) bool {
+ return flags.IsEnabled(ctx, ProjectWorkflowsV1, false)
+}
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index d082d6ec70..c8185ba927 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -348,6 +348,29 @@ type TaskIssueStatusData struct {
Description string `json:"description,omitempty"`
}
+// TaskProjectWorkflowData is the workflow of the project a task's issue
+// belongs to (MUL-7420), sent only when that project uses a workflow other
+// than the workspace Default. The daemon renders it into the brief so the
+// agent moves the issue along this project's statuses instead of the
+// built-in ones its generic status rules name.
+type TaskProjectWorkflowData struct {
+ Name string `json:"name"`
+ CurrentStatusKey string `json:"current_status_key"`
+ Steps []TaskProjectWorkflowStep `json:"steps"`
+}
+
+// TaskProjectWorkflowStep is one step of TaskProjectWorkflowData. Handler is a
+// display description ("Sentinel", "Lin (project lead)"), empty when the step
+// does not hand off. Instructions are sent for the current step only.
+type TaskProjectWorkflowStep struct {
+ Key string `json:"key"`
+ Name string `json:"name"`
+ Handler string `json:"handler,omitempty"`
+ Instructions string `json:"instructions,omitempty"`
+ NextStatusKey string `json:"next_status_key,omitempty"`
+ BackStatusKey string `json:"back_status_key,omitempty"`
+}
+
// TaskCancellationActor is the point-in-time actor snapshot attached to a
// cancelled run. Type stays open for forward compatibility; current producers
// emit member, agent, or system.
@@ -397,31 +420,34 @@ type AgentTaskResponse struct {
// IssueStatusesOmitted is how many active custom statuses were dropped by
// the cap, so the brief can say the list is incomplete instead of
// presenting a truncated catalog as the whole one.
- IssueStatusesOmitted int `json:"issue_statuses_omitted,omitempty"`
- ThreadName string `json:"thread_name,omitempty"` // semantic title for provider-native session/thread history
- Status string `json:"status"`
- Priority int32 `json:"priority"`
- DispatchedAt *string `json:"dispatched_at"`
- StartedAt *string `json:"started_at"`
- CompletedAt *string `json:"completed_at"`
- Result any `json:"result"`
- Error *string `json:"error"`
- FailureReason string `json:"failure_reason,omitempty"` // see TaskService.MaybeRetryFailedTask
- Attempt int32 `json:"attempt"`
- MaxAttempts int32 `json:"max_attempts"`
- ParentTaskID *string `json:"parent_task_id,omitempty"`
- IsLeaderTask bool `json:"is_leader_task,omitempty"`
- LeaderRoleResolved bool `json:"leader_role_resolved,omitempty"` // claim-only capability, always true here: IsLeaderTask/SquadID authoritatively answer "is this a leader run", so the daemon must not infer the role from briefing text. Servers predating it make no such promise — before #4951 they sent no is_leader_task at all, after it they sent the flag without guaranteeing a briefing — so a daemon seeing no capability keeps the legacy inference. Never rendered into a prompt; see daemon.taskIsSquadLeader (MUL-5811). Mirror field: internal/daemon/types.go, same JSON name
- Agent *TaskAgentData `json:"agent,omitempty"`
- ConnectedApps []ConnectedAppData `json:"connected_apps,omitempty"` // daemon-claim only: per-run app capabilities mounted through runtime MCP overlays
- Repos []RepoData `json:"repos,omitempty"`
- ProjectID string `json:"project_id,omitempty"` // issue's project, when present
- ProjectTitle string `json:"project_title,omitempty"` // for surfacing in agent context
- ProjectDescription string `json:"project_description,omitempty"` // durable project-level context injected into the brief
- ProjectResources []ProjectResourceData `json:"project_resources,omitempty"` // resources attached to the project
- CreatedAt string `json:"created_at"`
- PriorSessionID string `json:"prior_session_id,omitempty"` // session ID from a previous task on same issue
- PriorWorkDir string `json:"prior_work_dir,omitempty"` // work_dir from a previous task on same issue
+ IssueStatusesOmitted int `json:"issue_statuses_omitted,omitempty"`
+ // ProjectWorkflow is the issue's project workflow, when it has one other
+ // than the Default (MUL-7420). Absent keeps the brief unchanged.
+ ProjectWorkflow *TaskProjectWorkflowData `json:"project_workflow,omitempty"`
+ ThreadName string `json:"thread_name,omitempty"` // semantic title for provider-native session/thread history
+ Status string `json:"status"`
+ Priority int32 `json:"priority"`
+ DispatchedAt *string `json:"dispatched_at"`
+ StartedAt *string `json:"started_at"`
+ CompletedAt *string `json:"completed_at"`
+ Result any `json:"result"`
+ Error *string `json:"error"`
+ FailureReason string `json:"failure_reason,omitempty"` // see TaskService.MaybeRetryFailedTask
+ Attempt int32 `json:"attempt"`
+ MaxAttempts int32 `json:"max_attempts"`
+ ParentTaskID *string `json:"parent_task_id,omitempty"`
+ IsLeaderTask bool `json:"is_leader_task,omitempty"`
+ LeaderRoleResolved bool `json:"leader_role_resolved,omitempty"` // claim-only capability, always true here: IsLeaderTask/SquadID authoritatively answer "is this a leader run", so the daemon must not infer the role from briefing text. Servers predating it make no such promise — before #4951 they sent no is_leader_task at all, after it they sent the flag without guaranteeing a briefing — so a daemon seeing no capability keeps the legacy inference. Never rendered into a prompt; see daemon.taskIsSquadLeader (MUL-5811). Mirror field: internal/daemon/types.go, same JSON name
+ Agent *TaskAgentData `json:"agent,omitempty"`
+ ConnectedApps []ConnectedAppData `json:"connected_apps,omitempty"` // daemon-claim only: per-run app capabilities mounted through runtime MCP overlays
+ Repos []RepoData `json:"repos,omitempty"`
+ ProjectID string `json:"project_id,omitempty"` // issue's project, when present
+ ProjectTitle string `json:"project_title,omitempty"` // for surfacing in agent context
+ ProjectDescription string `json:"project_description,omitempty"` // durable project-level context injected into the brief
+ ProjectResources []ProjectResourceData `json:"project_resources,omitempty"` // resources attached to the project
+ CreatedAt string `json:"created_at"`
+ PriorSessionID string `json:"prior_session_id,omitempty"` // session ID from a previous task on same issue
+ PriorWorkDir string `json:"prior_work_dir,omitempty"` // work_dir from a previous task on same issue
// PriorSessionResumeUnavailable is set when a more recent Codex session was
// withheld because its rollout was missing (MUL-5305); PriorSessionID (if
// any) is then an older fallback, and the daemon surfaces the continuity gap
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 0d16221df6..504c9a0299 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -2819,6 +2819,9 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
}
}
projectCtx.applyTo(&resp)
+ // Project workflow (MUL-7420): best-effort, like the status catalog
+ // below — a failure degrades to the workspace-wide status rules.
+ resp.ProjectWorkflow = h.claimProjectWorkflow(r.Context(), issue)
// Load every planned input as one chronological, de-duplicated set.
// The trigger is included here so the delivery receipt can only contain
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 75fc2c676d..a598b70f39 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -24,6 +24,7 @@ import (
"github.com/multica-ai/multica/server/internal/dispatch"
"github.com/multica-ai/multica/server/internal/issueguard"
"github.com/multica-ai/multica/server/internal/issuestatus"
+ "github.com/multica-ai/multica/server/internal/issueworkflow"
"github.com/multica-ai/multica/server/internal/logger"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
@@ -3276,6 +3277,47 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {
}
projectID = id
}
+
+ // Project workflow (MUL-7420). A new issue in a project on a named
+ // workflow must start on a status the workflow lists, and a column the
+ // project hands off gives the new issue to its handler unless the caller
+ // chose an assignee. A sub-issue without its own project inherits the
+ // parent's, as IssueService.Create does.
+ workflowProjectID := projectID
+ if !workflowProjectID.Valid && parentIssueID.Valid {
+ if parent, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{
+ ID: parentIssueID, WorkspaceID: wsUUID,
+ }); err == nil {
+ workflowProjectID = parent.ProjectID
+ }
+ }
+ createWorkflow, createWorkflowProject, err := issueworkflow.ForProject(r.Context(), h.Queries, wsUUID, workflowProjectID)
+ if err != nil {
+ slog.Error("create issue: resolve project workflow", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to resolve project workflow")
+ return
+ }
+ var createHandoff *workflowHandoff
+ if createWorkflow != nil {
+ if err := issueworkflow.CheckStatus(createWorkflow, status); err != nil {
+ writeIssueWorkflowError(w, err)
+ return
+ }
+ if req.AssigneeType == nil && req.AssigneeID == nil {
+ if step, ok := createWorkflow.Step(status); ok && step.HandsOff() {
+ handoffCreatorType, handoffCreatorID := h.resolveActor(r, creatorID, workspaceID)
+ if t, id, ok := issueworkflow.ResolveHandler(step, createWorkflowProject, handoffCreatorType, parseUUID(handoffCreatorID)); ok {
+ assigneeType = pgtype.Text{String: t, Valid: true}
+ assigneeID = id
+ if status, msg := h.validateAssigneePair(r.Context(), r, workspaceID, assigneeType, assigneeID); status != 0 {
+ writeError(w, status, msg)
+ return
+ }
+ createHandoff = &workflowHandoff{def: *createWorkflow, step: step, project: createWorkflowProject}
+ }
+ }
+ }
+ }
// Project existence and the final parent boundary check are enforced inside
// IssueService.Create atomically with the create. The handler preloads a
// supplied parent only because the assignee gate must bind any autopilot
@@ -3426,6 +3468,9 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {
ActorID: actualCreatorID,
AnalyticsAgentID: analyticsAgentID,
Platform: func() string { p, _, _ := middleware.ClientMetadataFromContext(r.Context()); return p }(),
+ HandoffNote: func(issue db.Issue) string {
+ return h.workflowHandoffNote(r.Context(), issue, createHandoff)
+ },
BroadcastPayload: func(issue db.Issue, atts []db.Attachment, labels []db.IssueLabel) map[string]any {
payload := issueToResponse(issue, prefix)
// The event other tabs receive must carry the category too — filling
@@ -3537,6 +3582,16 @@ type UpdateIssueRequest struct {
// predate the handoff UI removal. It is consumed only when this write starts
// a run and is never stored on the issue itself.
HandoffNote string `json:"handoff_note,omitempty"`
+ // StopPreviousAssigneeRuns, when a status change hands the issue off to a
+ // project workflow step's handler, cancels the active runs of the agent or
+ // squad it was taken from. Ignored when the write does not hand off.
+ // (MUL-7420)
+ StopPreviousAssigneeRuns bool `json:"stop_previous_assignee_runs,omitempty"`
+ // EnterWorkflowStep makes a project move enter the destination workflow's
+ // step the issue lands on, handing it off like a status change would. A
+ // project move without it is administrative. Batch updates ignore it.
+ // (MUL-7420)
+ EnterWorkflowStep bool `json:"enter_workflow_step,omitempty"`
// DuplicateOfIssueID marks this issue as a duplicate of another issue in
// the same workspace (MUL-7349). A duplicate is an ordinary cancelled issue
// that remembers its original, so this also sets status to cancelled.
@@ -3953,7 +4008,27 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
// the identical lineage was accepted on the create path.
_, touchedType := rawFields["assignee_type"]
_, touchedID := rawFields["assignee_id"]
- if touchedType || touchedID {
+
+ // Project workflow (MUL-7420): keep the status inside the project's
+ // workflow, and hand the issue off when it enters a step with a handler.
+ // A handoff assignee passes the same gate as a hand-picked one.
+ // An agent's run may only move the issue from the step it works on.
+ callerType, _ := h.resolveActor(r, userID, workspaceID)
+ callerRun := h.agentRunOnIssue(r, callerType, prevIssue)
+ handoff, err := h.applyIssueWorkflow(r.Context(), prevIssue, &params, req.Status != nil, touchedType || touchedID, req.EnterWorkflowStep, callerRun)
+ if err != nil {
+ if writeIssueWorkflowError(w, err) {
+ return
+ }
+ slog.Error("update issue: resolve project workflow", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to resolve project workflow")
+ return
+ }
+ if params.Status.Valid && params.Status.String != statusKeyForGuard {
+ // A project move remapped the status; guard the key actually written.
+ statusKeyForGuard = params.Status.String
+ }
+ if touchedType || touchedID || handoff != nil {
if status, msg := h.validateAssigneePair(r.Context(), r, workspaceID, params.AssigneeType, params.AssigneeID); status != 0 {
writeError(w, status, msg)
return
@@ -3965,18 +4040,21 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
return
}
+ // The agent this write hands the issue to gets the change as its own run,
+ // not also through its event wakeups.
+ writeCtx := withWakeupHandedTo(r.Context(), h.handedToAgent(r.Context(), prevIssue, params, handoff != nil))
var issue db.Issue
attachmentsChanged := false
if req.Description != nil || req.TitleBase != nil || req.DescriptionBase != nil || len(attachmentIDs) > 0 {
var lockedPrev db.Issue
issue, lockedPrev, attachmentsChanged, err = h.updateIssueAtomically(
- r.Context(), prevIssue.WorkspaceID, params, rawFields, req.TitleBase, req.DescriptionBase, attachmentIDs, statusKeyForGuard,
+ writeCtx, prevIssue.WorkspaceID, params, rawFields, req.TitleBase, req.DescriptionBase, attachmentIDs, statusKeyForGuard,
)
if lockedPrev.ID.Valid {
prevIssue = lockedPrev
}
} else {
- issue, err = h.updateIssueWithStatusGuard(r.Context(), prevIssue.WorkspaceID, statusKeyForGuard, params)
+ issue, err = h.updateIssueWithStatusGuard(writeCtx, prevIssue.WorkspaceID, statusKeyForGuard, params)
}
if err != nil {
if writeIssueStatusRaceError(w, err) {
@@ -4003,15 +4081,16 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
// Determine actor identity: agent (via X-Agent-ID header) or member.
actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ h.advanceRunStep(r.Context(), callerRun, prevIssue, issue)
prefix := h.getIssuePrefix(r.Context(), issue.WorkspaceID)
resp := issueToResponse(issue, prefix)
slog.Info("issue updated", append(logger.RequestAttrs(r), "issue_id", id, "workspace_id", workspaceID)...)
h.fillStatusCategory(r.Context(), issue.WorkspaceID, &resp)
- assigneeChanged := (req.AssigneeType != nil || req.AssigneeID != nil) &&
+ assigneeChanged := (req.AssigneeType != nil || req.AssigneeID != nil || handoff != nil) &&
(prevIssue.AssigneeType.String != issue.AssigneeType.String || uuidToString(prevIssue.AssigneeID) != uuidToString(issue.AssigneeID))
- statusChanged := req.Status != nil && prevIssue.Status != issue.Status
+ statusChanged := (req.Status != nil || params.Status.Valid) && prevIssue.Status != issue.Status
priorityChanged := req.Priority != nil && prevIssue.Priority != issue.Priority
// project_changed gates the client's per-project issue-list refetch the way
// status/assignee flags gate theirs. Without it the client must diff
@@ -4027,7 +4106,26 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
dueDateChanged := prevDueDate != resp.DueDate && (prevDueDate == nil) != (resp.DueDate == nil) ||
(prevDueDate != nil && resp.DueDate != nil && *prevDueDate != *resp.DueDate)
- h.publish(protocol.EventIssueUpdated, workspaceID, actorType, actorID, map[string]any{
+ // A workflow handoff (MUL-7420) is decided before the event goes out so
+ // the timeline can record it as one entry: the status change, who the
+ // issue went to, whether their run started, and the brief it received.
+ handoffNote := req.HandoffNote
+ if handoff != nil && handoffNote == "" {
+ handoffNote = h.workflowHandoffNote(r.Context(), issue, handoff)
+ }
+ trigger, willRun := h.IssueService.WillEnqueueRun(r.Context(),
+ service.IssueTriggerInput{
+ Issue: issue,
+ PrevStatus: prevIssue.Status,
+ AssigneeChanged: assigneeChanged || handoff != nil,
+ StatusChanged: statusChanged,
+ EnteredHandoffStep: handoff != nil,
+ },
+ h.issueTriggerWriteProbe(r, actorType, actorID, issue),
+ )
+ willRun = willRun && !req.SuppressRun
+
+ updatedPayload := map[string]any{
"issue": resp,
"assignee_changed": assigneeChanged,
"status_changed": statusChanged,
@@ -4051,7 +4149,11 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
// and clients refresh the two issues' relations from it.
"duplicate_of_issue_id": liveDuplicateMark(issue.Status, issue.DuplicateOfIssueID),
"prev_duplicate_of_issue_id": liveDuplicateMark(prevIssue.Status, prevIssue.DuplicateOfIssueID),
- })
+ }
+ if handoff != nil {
+ updatedPayload["workflow_handoff"] = workflowHandoffPayload(issue, handoff, handoffNote, willRun)
+ }
+ h.publish(protocol.EventIssueUpdated, workspaceID, actorType, actorID, updatedPayload)
if attachmentsChanged {
// The full owner snapshot must be admitted before an auxiliary event at
// the same revision. Otherwise clients advance only the revision here and
@@ -4079,16 +4181,15 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
// it stops in-flight agent runs, so that implicit coupling is gone
// (MUL-4465). Deleting an issue still cancels its tasks (see DeleteIssue),
// because the tasks' owning issue ceases to exist.
- if trigger, ok := h.IssueService.WillEnqueueRun(r.Context(),
- service.IssueTriggerInput{
- Issue: issue,
- PrevStatus: prevIssue.Status,
- AssigneeChanged: assigneeChanged,
- StatusChanged: statusChanged,
- },
- h.issueTriggerWriteProbe(r, actorType, actorID, issue),
- ); ok && !req.SuppressRun {
- h.dispatchIssueRun(r.Context(), issue, trigger, actorType, actorID, req.HandoffNote)
+ //
+ // A workflow handoff counts as a fresh assignment even when the step's
+ // handler already owns the issue: entering the step is the handler's cue
+ // to work on it, with the step's brief as the handoff note. (MUL-7420)
+ if handoff != nil && req.StopPreviousAssigneeRuns {
+ h.stopPreviousAssigneeRuns(r.Context(), prevIssue, issue, actorType, actorID)
+ }
+ if willRun {
+ h.dispatchIssueRun(r.Context(), issue, trigger, actorType, actorID, handoffNote)
}
// Sub-issue rules on the parent (the child_done system rule and sub-issue
@@ -4748,12 +4849,26 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
// resolveActor still classifies the caller as an agent (MUL-6691).
_, batchTouchedType := rawUpdates["assignee_type"]
_, batchTouchedID := rawUpdates["assignee_id"]
- if batchTouchedType || batchTouchedID {
+ // Project workflow (MUL-7420), per issue: an issue whose workflow does
+ // not list the batch status is skipped like the other per-item guards;
+ // entering a handoff step reassigns this issue to the step's handler.
+ callerType, _ := h.resolveActor(r, userID, workspaceID)
+ callerRun := h.agentRunOnIssue(r, callerType, prevIssue)
+ handoff, err := h.applyIssueWorkflow(r.Context(), prevIssue, &params, req.Updates.Status != nil, batchTouchedType || batchTouchedID, false, callerRun)
+ if err != nil {
+ continue
+ }
+ issueStatusGuard := batchStatusKey
+ if params.Status.Valid {
+ issueStatusGuard = params.Status.String
+ }
+ if batchTouchedType || batchTouchedID || handoff != nil {
if status, _ := h.validateAssigneePair(r.Context(), r, workspaceID, params.AssigneeType, params.AssigneeID); status != 0 {
continue
}
}
+ writeCtx := withWakeupHandedTo(r.Context(), h.handedToAgent(r.Context(), prevIssue, params, handoff != nil))
var issue db.Issue
if req.Updates.Description != nil {
// One batch-level base cannot describe multiple issue documents.
@@ -4761,13 +4876,13 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
// legacy single-update clients that omit description_base.
var lockedPrev db.Issue
issue, lockedPrev, _, err = h.updateIssueAtomically(
- r.Context(), prevIssue.WorkspaceID, params, rawUpdates, nil, nil, nil, batchStatusKey,
+ writeCtx, prevIssue.WorkspaceID, params, rawUpdates, nil, nil, nil, issueStatusGuard,
)
if err == nil {
prevIssue = lockedPrev
}
} else {
- issue, err = h.updateIssueWithStatusGuard(r.Context(), wsUUID, batchStatusKey, params)
+ issue, err = h.updateIssueWithStatusGuard(writeCtx, wsUUID, issueStatusGuard, params)
}
if err != nil {
// The archive race is a property of the batch's shared target
@@ -4783,23 +4898,44 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
prefix := h.getIssuePrefix(r.Context(), issue.WorkspaceID)
resp := issueToResponse(issue, prefix)
actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ h.advanceRunStep(r.Context(), callerRun, prevIssue, issue)
fillBatch(&resp)
- assigneeChanged := (req.Updates.AssigneeType != nil || req.Updates.AssigneeID != nil) &&
+ assigneeChanged := (req.Updates.AssigneeType != nil || req.Updates.AssigneeID != nil || handoff != nil) &&
(prevIssue.AssigneeType.String != issue.AssigneeType.String || uuidToString(prevIssue.AssigneeID) != uuidToString(issue.AssigneeID))
- statusChanged := req.Updates.Status != nil && prevIssue.Status != issue.Status
+ statusChanged := (req.Updates.Status != nil || params.Status.Valid) && prevIssue.Status != issue.Status
priorityChanged := req.Updates.Priority != nil && prevIssue.Priority != issue.Priority
projectChanged := req.Updates.ProjectID != nil && uuidToString(prevIssue.ProjectID) != uuidToString(issue.ProjectID)
- h.publish(protocol.EventIssueUpdated, workspaceID, actorType, actorID, map[string]any{
+ batchHandoffNote := req.Updates.HandoffNote
+ if handoff != nil && batchHandoffNote == "" {
+ batchHandoffNote = h.workflowHandoffNote(r.Context(), issue, handoff)
+ }
+ trigger, willRun := h.IssueService.WillEnqueueRun(r.Context(),
+ service.IssueTriggerInput{
+ Issue: issue,
+ PrevStatus: prevIssue.Status,
+ AssigneeChanged: assigneeChanged || handoff != nil,
+ StatusChanged: statusChanged,
+ EnteredHandoffStep: handoff != nil,
+ },
+ h.issueTriggerWriteProbe(r, actorType, actorID, issue),
+ )
+ willRun = willRun && !req.Updates.SuppressRun
+ batchPayload := map[string]any{
"issue": resp,
"assignee_changed": assigneeChanged,
"status_changed": statusChanged,
"priority_changed": priorityChanged,
"project_changed": projectChanged,
+ "prev_status": prevIssue.Status,
"duplicate_of_issue_id": liveDuplicateMark(issue.Status, issue.DuplicateOfIssueID),
"prev_duplicate_of_issue_id": liveDuplicateMark(prevIssue.Status, prevIssue.DuplicateOfIssueID),
- })
+ }
+ if handoff != nil {
+ batchPayload["workflow_handoff"] = workflowHandoffPayload(issue, handoff, batchHandoffNote, willRun)
+ }
+ h.publish(protocol.EventIssueUpdated, workspaceID, actorType, actorID, batchPayload)
// Reassignment does not cancel existing tasks (#4963 / MUL-4113) —
// mirrors UpdateIssue. See that handler for the rationale.
@@ -4807,16 +4943,11 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
// Same single predicate as UpdateIssue — batch must not grow its own
// copy of the enqueue rule (the historical source of four-entry-point
// drift, MUL-3375). suppress_run applies batch-wide.
- if trigger, ok := h.IssueService.WillEnqueueRun(r.Context(),
- service.IssueTriggerInput{
- Issue: issue,
- PrevStatus: prevIssue.Status,
- AssigneeChanged: assigneeChanged,
- StatusChanged: statusChanged,
- },
- h.issueTriggerWriteProbe(r, actorType, actorID, issue),
- ); ok && !req.Updates.SuppressRun {
- h.dispatchIssueRun(r.Context(), issue, trigger, actorType, actorID, req.Updates.HandoffNote)
+ if handoff != nil && req.Updates.StopPreviousAssigneeRuns {
+ h.stopPreviousAssigneeRuns(r.Context(), prevIssue, issue, actorType, actorID)
+ }
+ if willRun {
+ h.dispatchIssueRun(r.Context(), issue, trigger, actorType, actorID, batchHandoffNote)
}
// No status change — not even → cancelled — cancels active tasks here,
diff --git a/server/internal/handler/issue_move.go b/server/internal/handler/issue_move.go
index 7f47c3a146..89e8a56635 100644
--- a/server/internal/handler/issue_move.go
+++ b/server/internal/handler/issue_move.go
@@ -23,6 +23,9 @@ var issueMoveFields = map[string]struct{}{
"before_id": {},
"after_id": {},
"expected_revision": {},
+ // A drag onto a workflow handoff step can stop the previous agent's run,
+ // exactly as the same status change through UpdateIssue can. (MUL-7420)
+ "stop_previous_assignee_runs": {},
}
// MoveIssue accepts relative neighbors instead of a client-authored canonical
diff --git a/server/internal/handler/issue_status.go b/server/internal/handler/issue_status.go
index 7d1125005d..f174fbc573 100644
--- a/server/internal/handler/issue_status.go
+++ b/server/internal/handler/issue_status.go
@@ -247,7 +247,19 @@ func (h *Handler) createIssueStatusEntry(ctx context.Context, workspaceID pgtype
if err := qtx.LockIssueStatusCatalog(ctx, workspaceID); err != nil {
return db.IssueStatus{}, "", err
}
+ entry, badRequest, err := createIssueStatusEntryLocked(ctx, qtx, workspaceID, publicCategory, arg)
+ if badRequest != "" || err != nil {
+ return db.IssueStatus{}, badRequest, err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return db.IssueStatus{}, "", err
+ }
+ return entry, "", nil
+}
+// createIssueStatusEntryLocked is createIssueStatusEntry inside a transaction
+// that already holds the exclusive catalog lock.
+func createIssueStatusEntryLocked(ctx context.Context, qtx *db.Queries, workspaceID pgtype.UUID, publicCategory string, arg db.CreateIssueStatusEntryParams) (db.IssueStatus, string, error) {
if arg.Key == "" {
// IncludeArchived, because idx_issue_status_workspace_key is NOT a
// partial index: a retired status still owns its key, so reusing it
@@ -274,9 +286,6 @@ func (h *Handler) createIssueStatusEntry(ctx context.Context, workspaceID pgtype
if err != nil {
return db.IssueStatus{}, "", err
}
- if err := tx.Commit(ctx); err != nil {
- return db.IssueStatus{}, "", err
- }
return entry, "", nil
}
@@ -432,6 +441,27 @@ func (h *Handler) ArchiveIssueStatus(w http.ResponseWriter, r *http.Request) {
})
return
}
+ // A status a project workflow lists stays active, or that workflow's
+ // projects would lose a column. Workflow edits take the same exclusive
+ // lock, so none can add the status back between this check and the
+ // archive. (MUL-7420)
+ workflowNames, err := qtx.ListIssueWorkflowNamesUsingStatusKey(r.Context(), db.ListIssueWorkflowNamesUsingStatusKeyParams{
+ WorkspaceID: wsUUID,
+ StatusKey: entry.Key,
+ })
+ if err != nil {
+ slog.Warn("ArchiveIssueStatus workflow check failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to check workflows using status")
+ return
+ }
+ if len(workflowNames) > 0 {
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": fmt.Sprintf("cannot archive status: workflow %q still uses it; remove it from the workflow first", workflowNames[0]),
+ "code": "issue_status_in_workflow",
+ "workflows": workflowNames,
+ })
+ return
+ }
archived, err := qtx.ArchiveIssueStatusEntry(r.Context(), db.ArchiveIssueStatusEntryParams{
ID: entry.ID,
@@ -446,6 +476,14 @@ func (h *Handler) ArchiveIssueStatus(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to archive issue status")
return
}
+ if err := qtx.RemoveStatusFromDefaultIssueWorkflow(r.Context(), db.RemoveStatusFromDefaultIssueWorkflowParams{
+ WorkspaceID: wsUUID,
+ StatusKey: entry.Key,
+ }); err != nil {
+ slog.Warn("ArchiveIssueStatus default workflow update failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to archive issue status")
+ return
+ }
if err := tx.Commit(r.Context()); err != nil {
slog.Warn("ArchiveIssueStatus commit failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to archive issue status")
@@ -455,6 +493,7 @@ func (h *Handler) ArchiveIssueStatus(w http.ResponseWriter, r *http.Request) {
// transaction then rolled back would have every other tab re-read the
// catalog and cache the pre-archive row as the new truth.
h.publishIssueStatusChanged(uuidToString(wsUUID), member, "archived")
+ h.publishIssueWorkflowChanged(uuidToString(wsUUID), member, "updated")
writeJSON(w, http.StatusOK, issueStatusToResponse(archived))
}
diff --git a/server/internal/handler/issue_trigger.go b/server/internal/handler/issue_trigger.go
index 8ac03ad612..19bd3a119a 100644
--- a/server/internal/handler/issue_trigger.go
+++ b/server/internal/handler/issue_trigger.go
@@ -7,6 +7,7 @@ import (
"net/http"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/issueworkflow"
"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"
@@ -120,6 +121,9 @@ type IssueTriggerPreviewRequest struct {
AssigneeType *string `json:"assignee_type"`
AssigneeID *string `json:"assignee_id"`
Status *string `json:"status"`
+ // ProjectID places a create preview in a project, so its workflow's
+ // starting status and starting-step handoff apply. (MUL-7420)
+ ProjectID *string `json:"project_id,omitempty"`
}
// IssueTriggerPreviewItem is one issue that WILL start a run under the
@@ -211,6 +215,20 @@ func (h *Handler) PreviewIssueTrigger(w http.ResponseWriter, r *http.Request) {
AssigneeType: newAssigneeType,
AssigneeID: newAssigneeID,
}
+ // Mirror CreateIssue's workflow handling: the starting column's
+ // handoff when no assignee was picked. (MUL-7420)
+ if req.ProjectID != nil && *req.ProjectID != "" {
+ if projectUUID, err := util.ParseUUID(*req.ProjectID); err == nil {
+ if def, project, err := issueworkflow.ForProject(r.Context(), h.Queries, wsUUID, projectUUID); err == nil && def != nil {
+ if step, ok := def.Step(candidate.Status); ok && step.HandsOff() && !hasNewAssignee {
+ if t, id, ok := issueworkflow.ResolveHandler(step, project, actorType, parseUUID(actorID)); ok {
+ candidate.AssigneeType = pgtype.Text{String: t, Valid: true}
+ candidate.AssigneeID = id
+ }
+ }
+ }
+ }
+ }
appendTrigger(candidate, service.IssueTriggerInput{Issue: candidate, IsCreate: true})
resp.TotalCount = len(resp.Triggers)
writeJSON(w, http.StatusOK, resp)
@@ -241,6 +259,22 @@ func (h *Handler) PreviewIssueTrigger(w http.ResponseWriter, r *http.Request) {
if req.Status != nil && *req.Status != "" {
post.Status = *req.Status
in.StatusChanged = loaded.Status != *req.Status
+ // A status that enters a workflow handoff step reassigns the
+ // issue, exactly as UpdateIssue will. (MUL-7420)
+ if !hasNewAssignee {
+ params := db.UpdateIssueParams{
+ ProjectID: loaded.ProjectID,
+ Status: pgtype.Text{String: *req.Status, Valid: true},
+ AssigneeType: loaded.AssigneeType,
+ AssigneeID: loaded.AssigneeID,
+ }
+ if hand, err := h.applyIssueWorkflow(r.Context(), loaded, &params, true, false, false, nil); err == nil && hand != nil {
+ post.AssigneeType = params.AssigneeType
+ post.AssigneeID = params.AssigneeID
+ in.AssigneeChanged = true
+ in.EnteredHandoffStep = true
+ }
+ }
}
in.Issue = post
appendTrigger(post, in)
diff --git a/server/internal/handler/issue_workflow.go b/server/internal/handler/issue_workflow.go
new file mode 100644
index 0000000000..a6fde985b4
--- /dev/null
+++ b/server/internal/handler/issue_workflow.go
@@ -0,0 +1,1412 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "sort"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/featureflags"
+ "github.com/multica-ai/multica/server/internal/issuestatus"
+ "github.com/multica-ai/multica/server/internal/issueworkflow"
+ "github.com/multica-ai/multica/server/internal/logger"
+ "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"
+)
+
+// Project workflow API (MUL-7420).
+//
+// Reading workflows is open to any member: every client needs them to render
+// a project's board and to filter status choices. Creating, editing and
+// deleting workflows, handoffs included, is owner/admin only: a workflow's
+// handoffs apply to every project using it. Which workflow a project uses is
+// open to owners/admins and to the project's lead.
+
+// requireProjectWorkflowsV1 gates adopting workflows behind the
+// project_workflows_v1 flag. Reads, edits of existing workflows and switching
+// a project back to Default stay open, so turning the flag off never strands
+// a project on a workflow nobody can maintain.
+func (h *Handler) requireProjectWorkflowsV1(w http.ResponseWriter, r *http.Request) bool {
+ if featureflags.ProjectWorkflowsV1Enabled(r.Context(), h.FeatureFlags) {
+ return true
+ }
+ writeFeatureDisabled(w, "project_workflows_disabled", "Project workflows are not enabled")
+ return false
+}
+
+func isWorkspaceAdmin(member db.Member) bool {
+ return roleAllowed(member.Role, "owner", "admin")
+}
+
+// canManageProjectWorkflow reports whether member may change a project's own
+// workflow settings: owners and admins, and the member who leads the project.
+func canManageProjectWorkflow(member db.Member, project db.Project) bool {
+ if isWorkspaceAdmin(member) {
+ return true
+ }
+ return project.LeadType.Valid && project.LeadType.String == "member" && project.LeadID == member.UserID
+}
+
+type IssueWorkflowHandlerPayload struct {
+ Type string `json:"type"`
+ ID string `json:"id,omitempty"`
+}
+
+// IssueWorkflowStepPayload is one status of a workflow, in board order, with
+// what happens when an issue enters it.
+type IssueWorkflowStepPayload struct {
+ StatusKey string `json:"status_key"`
+ Handler IssueWorkflowHandlerPayload `json:"handler"`
+ Instructions string `json:"instructions"`
+ NextStatusKey string `json:"next_status_key,omitempty"`
+ BackStatusKey string `json:"back_status_key,omitempty"`
+}
+
+type IssueWorkflowResponse struct {
+ ID string `json:"id"`
+ WorkspaceID string `json:"workspace_id"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ IsDefault bool `json:"is_default"`
+ Steps []IssueWorkflowStepPayload `json:"steps"`
+ ProjectIDs []string `json:"project_ids"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+}
+
+// StatusMappingRequirement names a status some issues are on that the target
+// workflow does not list. SuggestedStatusKey is the server's default choice.
+type StatusMappingRequirement struct {
+ StatusKey string `json:"status_key"`
+ IssueCount int64 `json:"issue_count"`
+ SuggestedStatusKey string `json:"suggested_status_key"`
+}
+
+// StatusIssueCount is a status some issues are on that the target workflow
+// also lists, so they keep it.
+type StatusIssueCount struct {
+ StatusKey string `json:"status_key"`
+ IssueCount int64 `json:"issue_count"`
+}
+
+type workflowMappingPlan struct {
+ Required []StatusMappingRequirement `json:"required"`
+ Unchanged []StatusIssueCount `json:"unchanged"`
+ TotalIssues int64 `json:"total_issues"`
+ AffectedIssues int64 `json:"affected_issues"`
+}
+
+func stepToPayload(s issueworkflow.Step) IssueWorkflowStepPayload {
+ return IssueWorkflowStepPayload{
+ StatusKey: s.StatusKey,
+ Handler: IssueWorkflowHandlerPayload{Type: s.Handler.Type, ID: s.Handler.ID},
+ Instructions: s.Instructions,
+ NextStatusKey: s.NextStatusKey,
+ BackStatusKey: s.BackStatusKey,
+ }
+}
+
+func payloadToStep(statusKey string, in IssueWorkflowStepPayload) issueworkflow.Step {
+ return issueworkflow.Step{
+ StatusKey: statusKey,
+ Handler: issueworkflow.Handler{Type: in.Handler.Type, ID: in.Handler.ID},
+ Instructions: in.Instructions,
+ NextStatusKey: in.NextStatusKey,
+ BackStatusKey: in.BackStatusKey,
+ }
+}
+
+func issueWorkflowToResponse(row db.IssueWorkflow, def issueworkflow.Definition, projectIDs []string) IssueWorkflowResponse {
+ if projectIDs == nil {
+ projectIDs = []string{}
+ }
+ steps := make([]IssueWorkflowStepPayload, len(def.Steps))
+ for i, s := range def.Steps {
+ steps[i] = stepToPayload(s)
+ }
+ return IssueWorkflowResponse{
+ ID: uuidToString(row.ID),
+ WorkspaceID: uuidToString(row.WorkspaceID),
+ Name: row.Name,
+ Description: row.Description,
+ IsDefault: row.IsDefault,
+ Steps: steps,
+ ProjectIDs: projectIDs,
+ CreatedAt: timestampToString(row.CreatedAt),
+ UpdatedAt: timestampToString(row.UpdatedAt),
+ }
+}
+
+// projectIDsByWorkflow groups the workspace's projects by the workflow row
+// they use, so a list response can say where each workflow applies. Projects
+// without a workflow, or pointing at a deleted one, count for Default.
+func (h *Handler) projectIDsByWorkflow(ctx context.Context, wsUUID pgtype.UUID, rows []db.IssueWorkflow) (map[string][]string, error) {
+ projects, err := h.Queries.ListProjects(ctx, db.ListProjectsParams{WorkspaceID: wsUUID})
+ if err != nil {
+ return nil, err
+ }
+ known := map[string]bool{}
+ defaultID := ""
+ for _, row := range rows {
+ id := uuidToString(row.ID)
+ known[id] = true
+ if row.IsDefault {
+ defaultID = id
+ }
+ }
+ out := map[string][]string{}
+ for _, p := range projects {
+ key := uuidToString(p.WorkflowID)
+ if !p.WorkflowID.Valid || !known[key] {
+ key = defaultID
+ }
+ if key != "" {
+ out[key] = append(out[key], uuidToString(p.ID))
+ }
+ }
+ return out, nil
+}
+
+// workflowStatusCatalog loads the workspace catalog keyed by status key,
+// including archived rows so validation can say why a key is unusable.
+func (h *Handler) workflowStatusCatalog(ctx context.Context, q *db.Queries, wsUUID pgtype.UUID) (map[string]issueworkflow.CatalogEntry, error) {
+ if err := issuestatus.Ensure(ctx, q, wsUUID); err != nil {
+ return nil, err
+ }
+ rows, err := q.ListIssueStatusEntries(ctx, db.ListIssueStatusEntriesParams{WorkspaceID: wsUUID, IncludeArchived: true})
+ if err != nil {
+ return nil, err
+ }
+ out := make(map[string]issueworkflow.CatalogEntry, len(rows))
+ for _, row := range rows {
+ // The lifecycle category, not the legacy wire value: a switch maps
+ // in_progress onto in_review because both are "started".
+ category, _ := issuestatus.ParseCategory(row.Category)
+ out[row.Key] = issueworkflow.CatalogEntry{
+ Key: row.Key,
+ Name: row.Name,
+ Category: category,
+ Archived: row.ArchivedAt.Valid,
+ }
+ }
+ return out, nil
+}
+
+func (h *Handler) ListIssueWorkflows(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+ if _, ok := h.requireWorkspaceMember(w, r, workspaceID, "workspace not found"); !ok {
+ return
+ }
+ // Default is stored the first time workflows are read with the feature
+ // on, so every client sees the same Default from then on.
+ if featureflags.ProjectWorkflowsV1Enabled(r.Context(), h.FeatureFlags) {
+ if _, err := issueworkflow.EnsureDefault(r.Context(), h.Queries, wsUUID); err != nil {
+ slog.Warn("ListIssueWorkflows ensure default failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to list workflows")
+ return
+ }
+ }
+ rows, err := h.Queries.ListIssueWorkflows(r.Context(), wsUUID)
+ if err != nil {
+ slog.Warn("ListIssueWorkflows failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to list workflows")
+ return
+ }
+ byWorkflow, err := h.projectIDsByWorkflow(r.Context(), wsUUID, rows)
+ if err != nil {
+ slog.Warn("ListIssueWorkflows projects failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to list workflows")
+ return
+ }
+ resp := make([]IssueWorkflowResponse, 0, len(rows))
+ for _, row := range rows {
+ def, err := issueworkflow.Decode(row)
+ if err != nil {
+ slog.Warn("ListIssueWorkflows decode failed", append(logger.RequestAttrs(r), "workflow_id", uuidToString(row.ID), "error", err)...)
+ continue
+ }
+ resp = append(resp, issueWorkflowToResponse(row, def, byWorkflow[uuidToString(row.ID)]))
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"workflows": resp, "total": len(resp)})
+}
+
+func (h *Handler) GetIssueWorkflow(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+ if _, ok := h.requireWorkspaceMember(w, r, workspaceID, "workspace not found"); !ok {
+ return
+ }
+ idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workflow id")
+ if !ok {
+ return
+ }
+ row, err := h.Queries.GetIssueWorkflow(r.Context(), db.GetIssueWorkflowParams{ID: idUUID, WorkspaceID: wsUUID})
+ if err != nil {
+ writeError(w, http.StatusNotFound, "workflow not found")
+ return
+ }
+ h.writeIssueWorkflow(w, r, http.StatusOK, row)
+}
+
+func (h *Handler) writeIssueWorkflow(w http.ResponseWriter, r *http.Request, status int, row db.IssueWorkflow) {
+ writeJSON(w, status, h.issueWorkflowResponse(r.Context(), row))
+}
+
+func (h *Handler) issueWorkflowResponse(ctx context.Context, row db.IssueWorkflow) IssueWorkflowResponse {
+ def, err := issueworkflow.Decode(row)
+ if err != nil {
+ def = issueworkflow.Definition{}
+ }
+ rows, err := h.Queries.ListIssueWorkflows(ctx, row.WorkspaceID)
+ if err != nil {
+ rows = []db.IssueWorkflow{row}
+ }
+ byWorkflow, err := h.projectIDsByWorkflow(ctx, row.WorkspaceID, rows)
+ if err != nil {
+ byWorkflow = map[string][]string{}
+ }
+ return issueWorkflowToResponse(row, def, byWorkflow[uuidToString(row.ID)])
+}
+
+// NewWorkflowStatus creates a catalog status as part of a workflow write, so
+// a column can be added without the status settings page.
+type NewWorkflowStatus struct {
+ Name string `json:"name"`
+ Category string `json:"category"`
+ Color string `json:"color"`
+}
+
+// IssueWorkflowStepInput names a step by an existing status key or by a
+// status to create, with its handoff. Next and back statuses must name
+// existing statuses.
+type IssueWorkflowStepInput struct {
+ StatusKey string `json:"status_key,omitempty"`
+ NewStatus *NewWorkflowStatus `json:"new_status,omitempty"`
+ Handler *IssueWorkflowHandlerPayload `json:"handler,omitempty"`
+ Instructions string `json:"instructions,omitempty"`
+ NextStatusKey string `json:"next_status_key,omitempty"`
+ BackStatusKey string `json:"back_status_key,omitempty"`
+}
+
+type IssueWorkflowWriteRequest struct {
+ Name *string `json:"name"`
+ Description *string `json:"description"`
+ // Steps replace the workflow's steps and handoffs. Todo, done and
+ // cancelled are added when missing; backlog and blocked are listed only
+ // when included. Fixed statuses take their fixed places.
+ Steps *[]IssueWorkflowStepInput `json:"steps"`
+ // StatusMapping moves issues off statuses an edit removes, keyed by the
+ // removed status. Required for every removed status that issues of the
+ // workflow's projects still use.
+ StatusMapping map[string]string `json:"status_mapping,omitempty"`
+ // DryRun validates the edit and returns the mapping plan without writing.
+ DryRun bool `json:"dry_run,omitempty"`
+}
+
+var newStatusDefaultColor = map[string]string{
+ "unstarted": "#94a3b8",
+ "started": "#3b82f6",
+ "done": "#22c55e",
+ "closed": "#64748b",
+}
+
+// resolveStepInputs turns step inputs into steps, creating the new statuses
+// they name. The caller holds the exclusive catalog lock. A non-empty message
+// is a caller error.
+func resolveStepInputs(ctx context.Context, qtx *db.Queries, wsUUID pgtype.UUID, inputs []IssueWorkflowStepInput) ([]issueworkflow.Step, []db.IssueStatus, string, error) {
+ steps := make([]issueworkflow.Step, 0, len(inputs))
+ var created []db.IssueStatus
+ for _, in := range inputs {
+ step := issueworkflow.Step{
+ StatusKey: in.StatusKey,
+ Instructions: in.Instructions,
+ NextStatusKey: in.NextStatusKey,
+ BackStatusKey: in.BackStatusKey,
+ }
+ if in.Handler != nil {
+ step.Handler = issueworkflow.Handler{Type: in.Handler.Type, ID: in.Handler.ID}
+ }
+ if in.NewStatus != nil {
+ entry, msg, err := createWorkflowStatus(ctx, qtx, wsUUID, *in.NewStatus)
+ if msg != "" || err != nil {
+ return nil, nil, msg, err
+ }
+ created = append(created, entry)
+ step.StatusKey = entry.Key
+ }
+ steps = append(steps, step)
+ }
+ return steps, created, "", nil
+}
+
+func createWorkflowStatus(ctx context.Context, qtx *db.Queries, wsUUID pgtype.UUID, in NewWorkflowStatus) (db.IssueStatus, string, error) {
+ name := strings.TrimSpace(in.Name)
+ if name == "" || utf8.RuneCountInString(name) > 64 {
+ return db.IssueStatus{}, "status name must be 1-64 characters", nil
+ }
+ category, ok := issuestatus.ParseCategory(in.Category)
+ if !ok {
+ category = "started"
+ }
+ color := newStatusDefaultColor[category]
+ if strings.TrimSpace(in.Color) != "" {
+ c, err := normalizeColor(in.Color)
+ if err != nil {
+ return db.IssueStatus{}, err.Error(), nil
+ }
+ color = c
+ }
+ // A status with this name already exists: reuse it instead of failing,
+ // so the same template applied twice lands on the same statuses.
+ entries, err := qtx.ListIssueStatusEntries(ctx, db.ListIssueStatusEntriesParams{WorkspaceID: wsUUID, IncludeArchived: false})
+ if err != nil {
+ return db.IssueStatus{}, "", err
+ }
+ for _, e := range entries {
+ if strings.EqualFold(e.Name, name) {
+ return e, "", nil
+ }
+ }
+ entry, msg, err := createIssueStatusEntryLocked(ctx, qtx, wsUUID, category, db.CreateIssueStatusEntryParams{
+ WorkspaceID: wsUUID,
+ Name: name,
+ Category: category,
+ Color: color,
+ })
+ if err != nil && isUniqueViolation(err) {
+ return db.IssueStatus{}, fmt.Sprintf("a status named %q already exists", name), nil
+ }
+ return entry, msg, err
+}
+
+// validateHandoffHandlers checks that each concrete handler exists in the
+// workspace and that the caller may hand work to it — the same gate an
+// assignment passes. Only changed handlers are checked, so an edit never
+// fails on a handler someone else picked.
+func (h *Handler) validateHandoffHandlers(ctx context.Context, r *http.Request, workspaceID string, steps, previous []issueworkflow.Step) (int, string) {
+ before := map[issueworkflow.Handler]bool{}
+ for _, s := range previous {
+ before[s.Handler] = true
+ }
+ for _, s := range steps {
+ if before[s.Handler] {
+ continue
+ }
+ if status, msg := h.validateHandoffHandler(ctx, r, workspaceID, s); status != 0 {
+ return status, msg
+ }
+ }
+ return 0, ""
+}
+
+// validateHandoffHandler checks one step's handler like
+// validateHandoffHandlers.
+func (h *Handler) validateHandoffHandler(ctx context.Context, r *http.Request, workspaceID string, s issueworkflow.Step) (int, string) {
+ switch s.Handler.Type {
+ case issueworkflow.HandlerAgent, issueworkflow.HandlerSquad, issueworkflow.HandlerMember:
+ id, err := parseUUIDString(s.Handler.ID)
+ if err != nil {
+ return http.StatusBadRequest, "invalid handler id"
+ }
+ return h.validateAssigneePair(ctx, r, workspaceID, pgtype.Text{String: s.Handler.Type, Valid: true}, id)
+ }
+ return 0, ""
+}
+
+func parseUUIDString(s string) (pgtype.UUID, error) {
+ var id pgtype.UUID
+ if err := id.Scan(s); err != nil || !id.Valid {
+ return pgtype.UUID{}, errors.New("invalid uuid")
+ }
+ return id, nil
+}
+
+func (h *Handler) CreateIssueWorkflow(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+ member, ok := h.requireWorkspaceMember(w, r, workspaceID, "workspace not found")
+ if !ok {
+ return
+ }
+ if !h.requireProjectWorkflowsV1(w, r) {
+ return
+ }
+ var req IssueWorkflowWriteRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if !isWorkspaceAdmin(member) {
+ writeError(w, http.StatusForbidden, "insufficient permissions")
+ return
+ }
+ var name, description string
+ if req.Name != nil {
+ name = *req.Name
+ }
+ if req.Description != nil {
+ description = *req.Description
+ }
+ var inputs []IssueWorkflowStepInput
+ if req.Steps != nil {
+ inputs = *req.Steps
+ }
+
+ ctx := r.Context()
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save workflow")
+ return
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+ if err := qtx.LockIssueStatusCatalog(ctx, wsUUID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save workflow")
+ return
+ }
+ // Store Default before creating statuses for this workflow, so they
+ // never join Default's snapshot.
+ if _, err := issueworkflow.EnsureDefault(ctx, qtx, wsUUID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save workflow")
+ return
+ }
+ steps, createdStatuses, msg, err := resolveStepInputs(ctx, qtx, wsUUID, inputs)
+ if msg != "" {
+ writeErrorCode(w, http.StatusBadRequest, "invalid_workflow", msg)
+ return
+ }
+ if err != nil {
+ slog.Warn("CreateIssueWorkflow statuses failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to save workflow")
+ return
+ }
+ name, description, steps = issueworkflow.Normalize(name, description, steps)
+ catalog, err := h.workflowStatusCatalog(ctx, qtx, wsUUID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load issue statuses")
+ return
+ }
+ if err := issueworkflow.Validate(name, description, steps, false, catalog); err != nil {
+ writeErrorCode(w, http.StatusBadRequest, "invalid_workflow", err.Error())
+ return
+ }
+ if status, msg := h.validateHandoffHandlers(ctx, r, workspaceID, steps, nil); status != 0 {
+ writeErrorCode(w, status, "invalid_handoff", msg)
+ return
+ }
+ raw, err := issueworkflow.EncodeSteps(steps)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save workflow")
+ return
+ }
+ row, err := qtx.CreateIssueWorkflow(ctx, db.CreateIssueWorkflowParams{
+ WorkspaceID: wsUUID,
+ Name: name,
+ Description: description,
+ InitialStatusKey: issueworkflow.StartStatus,
+ Steps: raw,
+ })
+ if err != nil {
+ if isUniqueViolation(err) {
+ writeErrorCode(w, http.StatusConflict, "workflow_name_taken", "a workflow with this name already exists")
+ return
+ }
+ slog.Warn("CreateIssueWorkflow failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to save workflow")
+ return
+ }
+ if err := tx.Commit(ctx); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save workflow")
+ return
+ }
+ if len(createdStatuses) > 0 {
+ h.publishIssueStatusChanged(workspaceID, member, "created")
+ }
+ h.publishIssueWorkflowChanged(workspaceID, member, "created")
+ h.writeIssueWorkflow(w, r, http.StatusCreated, row)
+}
+
+// mappingPlan computes which statuses issues of projectIDs are on that
+// allowed() rejects, with a suggested target for each.
+func mappingPlan(counts []db.CountProjectIssuesByStatusRow, allowed func(string) bool, suggest func(string) string) workflowMappingPlan {
+ plan := workflowMappingPlan{Required: []StatusMappingRequirement{}, Unchanged: []StatusIssueCount{}}
+ for _, c := range counts {
+ plan.TotalIssues += c.IssueCount
+ if allowed(c.Status) {
+ plan.Unchanged = append(plan.Unchanged, StatusIssueCount{StatusKey: c.Status, IssueCount: c.IssueCount})
+ continue
+ }
+ plan.AffectedIssues += c.IssueCount
+ plan.Required = append(plan.Required, StatusMappingRequirement{
+ StatusKey: c.Status,
+ IssueCount: c.IssueCount,
+ SuggestedStatusKey: suggest(c.Status),
+ })
+ }
+ sort.Slice(plan.Required, func(i, j int) bool { return plan.Required[i].StatusKey < plan.Required[j].StatusKey })
+ return plan
+}
+
+// checkMapping verifies a mapping covers every required status with a target
+// the destination accepts. It returns the first problem as a message.
+func checkMapping(plan workflowMappingPlan, mapping map[string]string, targetAllowed func(string) bool) string {
+ for _, req := range plan.Required {
+ target, ok := mapping[req.StatusKey]
+ if !ok || target == "" {
+ return fmt.Sprintf("choose a destination status for the %d issue(s) on %q", req.IssueCount, req.StatusKey)
+ }
+ if !targetAllowed(target) {
+ return fmt.Sprintf("destination status %q for %q is not part of the target workflow", target, req.StatusKey)
+ }
+ }
+ return ""
+}
+
+func writeMappingRequired(w http.ResponseWriter, plan workflowMappingPlan, msg string) {
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": msg,
+ "code": "workflow_status_mapping_required",
+ "plan": plan,
+ })
+}
+
+// remapIssues applies a validated mapping inside the caller's transaction.
+// An issue it moves into a done or closed status ends its wakeups, as any
+// status write does; the returned runs are for the caller's post-commit
+// broadcast.
+func remapIssues(ctx context.Context, qtx *db.Queries, wsUUID pgtype.UUID, projectIDs []pgtype.UUID, plan workflowMappingPlan, mapping map[string]string) ([]db.Issue, []db.AgentTaskQueue, error) {
+ var changed []db.Issue
+ var cancelled []db.AgentTaskQueue
+ for _, req := range plan.Required {
+ rows, err := qtx.RemapProjectIssueStatus(ctx, db.RemapProjectIssueStatusParams{
+ WorkspaceID: wsUUID,
+ ProjectIds: projectIDs,
+ FromStatus: req.StatusKey,
+ ToStatus: mapping[req.StatusKey],
+ })
+ if err != nil {
+ return nil, nil, err
+ }
+ for _, issue := range rows {
+ stopped, err := service.StopClosedIssueWakeups(ctx, qtx, issue)
+ if err != nil {
+ return nil, nil, err
+ }
+ cancelled = append(cancelled, stopped...)
+ }
+ changed = append(changed, rows...)
+ }
+ return changed, cancelled, nil
+}
+
+func (h *Handler) UpdateIssueWorkflow(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+ member, ok := h.requireWorkspaceRole(w, r, workspaceID, "workspace not found", "owner", "admin")
+ if !ok {
+ return
+ }
+ idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workflow id")
+ if !ok {
+ return
+ }
+ var req IssueWorkflowWriteRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ ctx := r.Context()
+
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save workflow")
+ return
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+ // The exclusive catalog lock keeps a status archive from racing the step
+ // validation below, and serializes concurrent edits of one workspace's
+ // workflows.
+ if err := qtx.LockIssueStatusCatalog(ctx, wsUUID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save workflow")
+ return
+ }
+ current, err := qtx.GetIssueWorkflow(ctx, db.GetIssueWorkflowParams{ID: idUUID, WorkspaceID: wsUUID})
+ if err != nil {
+ writeError(w, http.StatusNotFound, "workflow not found")
+ return
+ }
+ var projects []db.Project
+ if current.IsDefault {
+ projects, err = qtx.ListProjectsUsingDefaultIssueWorkflow(ctx, wsUUID)
+ } else {
+ projects, err = qtx.ListProjectsUsingIssueWorkflow(ctx, db.ListProjectsUsingIssueWorkflowParams{WorkspaceID: wsUUID, WorkflowID: current.ID})
+ }
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save workflow")
+ return
+ }
+ currentSteps, err := issueworkflow.DecodeSteps(current.Steps)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to read workflow")
+ return
+ }
+ name, description, steps := current.Name, current.Description, currentSteps
+ if req.Name != nil && !current.IsDefault {
+ name = *req.Name
+ }
+ if req.Description != nil {
+ description = *req.Description
+ }
+ var createdStatuses []db.IssueStatus
+ if req.Steps != nil {
+ var msg string
+ steps, createdStatuses, msg, err = resolveStepInputs(ctx, qtx, wsUUID, *req.Steps)
+ if msg != "" {
+ writeErrorCode(w, http.StatusBadRequest, "invalid_workflow", msg)
+ return
+ }
+ if err != nil {
+ slog.Warn("UpdateIssueWorkflow statuses failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to save workflow")
+ return
+ }
+ }
+ name, description, steps = issueworkflow.Normalize(name, description, steps)
+ catalog, err := h.workflowStatusCatalog(ctx, qtx, wsUUID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load issue statuses")
+ return
+ }
+ if err := issueworkflow.Validate(name, description, steps, current.IsDefault, catalog); err != nil {
+ writeErrorCode(w, http.StatusBadRequest, "invalid_workflow", err.Error())
+ return
+ }
+ if status, msg := h.validateHandoffHandlers(ctx, r, workspaceID, steps, currentSteps); status != 0 {
+ writeErrorCode(w, status, "invalid_handoff", msg)
+ return
+ }
+
+ // Default accepts every status, so editing it never moves issues; issues
+ // on a status it drops stay there and show under hidden columns.
+ plan := workflowMappingPlan{Required: []StatusMappingRequirement{}, Unchanged: []StatusIssueCount{}}
+ projectIDs := make([]pgtype.UUID, len(projects))
+ for i, p := range projects {
+ projectIDs[i] = p.ID
+ }
+ if !current.IsDefault && len(projectIDs) > 0 {
+ next := issueworkflow.Definition{ID: current.ID, Name: name, Steps: steps}
+ counts, err := qtx.CountProjectIssuesByStatus(ctx, db.CountProjectIssuesByStatusParams{WorkspaceID: wsUUID, ProjectIds: projectIDs})
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save workflow")
+ return
+ }
+ categoryOf := func(key string) string { return catalog[key].Category }
+ plan = mappingPlan(counts, next.Has, func(key string) string { return issueworkflow.MoveTarget(next, key, categoryOf) })
+ if req.DryRun {
+ writeJSON(w, http.StatusOK, map[string]any{"dry_run": true, "plan": plan})
+ return
+ }
+ if msg := checkMapping(plan, req.StatusMapping, next.Has); msg != "" {
+ writeMappingRequired(w, plan, msg)
+ return
+ }
+ } else if req.DryRun {
+ writeJSON(w, http.StatusOK, map[string]any{"dry_run": true, "plan": plan})
+ return
+ }
+ raw, err := issueworkflow.EncodeSteps(steps)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save workflow")
+ return
+ }
+ row, err := qtx.UpdateIssueWorkflow(ctx, db.UpdateIssueWorkflowParams{
+ ID: current.ID,
+ WorkspaceID: wsUUID,
+ Name: name,
+ Description: description,
+ InitialStatusKey: issueworkflow.StartStatus,
+ Steps: raw,
+ })
+ if err != nil {
+ if isUniqueViolation(err) {
+ writeErrorCode(w, http.StatusConflict, "workflow_name_taken", "a workflow with this name already exists")
+ return
+ }
+ slog.Warn("UpdateIssueWorkflow failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to save workflow")
+ return
+ }
+ changed, cancelledWakeups, err := remapIssues(ctx, qtx, wsUUID, projectIDs, plan, req.StatusMapping)
+ if err != nil {
+ slog.Warn("UpdateIssueWorkflow remap failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to move issues to the new statuses")
+ return
+ }
+ if err := tx.Commit(ctx); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save workflow")
+ return
+ }
+ // Remapping is an administrative move: snapshots only, so it neither
+ // notifies subscribers per issue nor looks like a handoff.
+ h.publishIssueSnapshots(ctx, changed, "member", uuidToString(member.UserID))
+ h.broadcastCancelledWakeups(ctx, wsUUID, cancelledWakeups)
+ if len(createdStatuses) > 0 {
+ h.publishIssueStatusChanged(workspaceID, member, "created")
+ }
+ h.publishIssueWorkflowChanged(workspaceID, member, "updated")
+ h.writeIssueWorkflow(w, r, http.StatusOK, row)
+}
+
+func (h *Handler) DeleteIssueWorkflow(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+ member, ok := h.requireWorkspaceRole(w, r, workspaceID, "workspace not found", "owner", "admin")
+ if !ok {
+ return
+ }
+ idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workflow id")
+ if !ok {
+ return
+ }
+ ctx := r.Context()
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete workflow")
+ return
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+ if err := qtx.LockIssueStatusCatalog(ctx, wsUUID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete workflow")
+ return
+ }
+ row, err := qtx.GetIssueWorkflow(ctx, db.GetIssueWorkflowParams{ID: idUUID, WorkspaceID: wsUUID})
+ if err != nil {
+ writeError(w, http.StatusNotFound, "workflow not found")
+ return
+ }
+ if row.IsDefault {
+ writeErrorCode(w, http.StatusBadRequest, "workflow_is_default", "the Default workflow cannot be deleted")
+ return
+ }
+ projects, err := qtx.ListProjectsUsingIssueWorkflow(ctx, db.ListProjectsUsingIssueWorkflowParams{WorkspaceID: wsUUID, WorkflowID: idUUID})
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete workflow")
+ return
+ }
+ if len(projects) > 0 {
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": fmt.Sprintf("%d project(s) still use this workflow; switch them to another workflow first", len(projects)),
+ "code": "workflow_in_use",
+ "project_count": len(projects),
+ })
+ return
+ }
+ n, err := qtx.DeleteIssueWorkflow(ctx, db.DeleteIssueWorkflowParams{ID: idUUID, WorkspaceID: wsUUID})
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete workflow")
+ return
+ }
+ if n == 0 {
+ writeError(w, http.StatusNotFound, "workflow not found")
+ return
+ }
+ if err := tx.Commit(ctx); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete workflow")
+ return
+ }
+ h.publishIssueWorkflowChanged(workspaceID, member, "deleted")
+ w.WriteHeader(http.StatusNoContent)
+}
+
+func (h *Handler) publishIssueWorkflowChanged(workspaceID string, actor db.Member, action string) {
+ h.publish(protocol.EventIssueWorkflowChanged, workspaceID, "member", uuidToString(actor.UserID), map[string]any{
+ "action": action,
+ })
+}
+
+// publishProjectWorkflowUpdate announces a project whose workflow settings
+// changed and returns the project as the API shapes it.
+func (h *Handler) publishProjectWorkflowUpdate(ctx context.Context, workspaceID string, member db.Member, project db.Project) ProjectResponse {
+ resp := projectToResponse(project)
+ resp.IssueCount, resp.DoneCount = h.loadProjectIssueStats(ctx, project.WorkspaceID, project.ID)
+ resp.ResourceCount = h.loadProjectResourceCount(ctx, project.ID)
+ h.publish(protocol.EventProjectUpdated, workspaceID, "member", uuidToString(member.UserID), map[string]any{"project": resp})
+ return resp
+}
+
+// loadProjectForWorkflowWrite resolves the {id} project and checks that the
+// caller may change its workflow settings.
+func (h *Handler) loadProjectForWorkflowWrite(w http.ResponseWriter, r *http.Request) (db.Project, db.Member, string, bool) {
+ workspaceID := h.resolveWorkspaceID(r)
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return db.Project{}, db.Member{}, "", false
+ }
+ member, ok := h.requireWorkspaceMember(w, r, workspaceID, "workspace not found")
+ if !ok {
+ return db.Project{}, db.Member{}, "", false
+ }
+ projectUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "project id")
+ if !ok {
+ return db.Project{}, db.Member{}, "", false
+ }
+ project, err := h.Queries.GetProjectInWorkspace(r.Context(), db.GetProjectInWorkspaceParams{ID: projectUUID, WorkspaceID: wsUUID})
+ if err != nil {
+ writeError(w, http.StatusNotFound, "project not found")
+ return db.Project{}, db.Member{}, "", false
+ }
+ if !canManageProjectWorkflow(member, project) {
+ writeError(w, http.StatusForbidden, "only workspace admins and the project lead can change this project's workflow")
+ return db.Project{}, db.Member{}, "", false
+ }
+ return project, member, workspaceID, true
+}
+
+type SetProjectWorkflowRequest struct {
+ // WorkflowID is the workflow to use; null switches back to the workspace
+ // Default workflow.
+ WorkflowID *string `json:"workflow_id"`
+ StatusMapping map[string]string `json:"status_mapping,omitempty"`
+ DryRun bool `json:"dry_run,omitempty"`
+}
+
+// SetProjectWorkflow switches the workflow a project uses. Issues on statuses
+// the new workflow does not list move to the statuses the caller maps them to,
+// in the same transaction. The move is administrative: it neither reassigns
+// issues nor starts runs.
+func (h *Handler) SetProjectWorkflow(w http.ResponseWriter, r *http.Request) {
+ loaded, member, workspaceID, ok := h.loadProjectForWorkflowWrite(w, r)
+ if !ok {
+ return
+ }
+ wsUUID := loaded.WorkspaceID
+ var req SetProjectWorkflowRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ var targetID pgtype.UUID
+ if req.WorkflowID != nil && *req.WorkflowID != "" {
+ if !h.requireProjectWorkflowsV1(w, r) {
+ return
+ }
+ id, ok := parseUUIDOrBadRequest(w, *req.WorkflowID, "workflow_id")
+ if !ok {
+ return
+ }
+ targetID = id
+ }
+ ctx := r.Context()
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to change workflow")
+ return
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+ // Shared catalog lock: a workflow edit (exclusive) cannot change the
+ // target's steps between the census and the remap below.
+ if err := qtx.LockIssueStatusCatalogShared(ctx, wsUUID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to change workflow")
+ return
+ }
+ project, err := qtx.LockProjectForWorkflowChange(ctx, db.LockProjectForWorkflowChangeParams{ID: loaded.ID, WorkspaceID: wsUUID})
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "project not found")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to change workflow")
+ return
+ }
+ var target *issueworkflow.Definition
+ if targetID.Valid {
+ row, err := qtx.GetIssueWorkflow(ctx, db.GetIssueWorkflowParams{ID: targetID, WorkspaceID: wsUUID})
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "workflow not found in this workspace")
+ return
+ }
+ def, err := issueworkflow.Decode(row)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to read workflow")
+ return
+ }
+ if def.IsDefault {
+ // Choosing the Default row is the same as choosing Default.
+ targetID = pgtype.UUID{}
+ } else {
+ target = &def
+ }
+ }
+ catalog, err := h.workflowStatusCatalog(ctx, qtx, wsUUID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load issue statuses")
+ return
+ }
+ // The Default workflow accepts every catalog status, archived included:
+ // issues already on an archived status keep it, as they always have.
+ allowed := func(key string) bool {
+ if target == nil {
+ _, ok := catalog[key]
+ return ok
+ }
+ return target.Has(key)
+ }
+ targetAccepts := func(key string) bool {
+ if target == nil {
+ entry, ok := catalog[key]
+ return ok && !entry.Archived
+ }
+ return target.Has(key)
+ }
+ counts, err := qtx.CountProjectIssuesByStatus(ctx, db.CountProjectIssuesByStatusParams{WorkspaceID: wsUUID, ProjectIds: []pgtype.UUID{project.ID}})
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to change workflow")
+ return
+ }
+ categoryOf := func(key string) string { return catalog[key].Category }
+ plan := mappingPlan(counts, allowed, func(key string) string {
+ if target == nil {
+ return issuestatus.Todo
+ }
+ return issueworkflow.MoveTarget(*target, key, categoryOf)
+ })
+ if req.DryRun {
+ writeJSON(w, http.StatusOK, map[string]any{"dry_run": true, "plan": plan})
+ return
+ }
+ if msg := checkMapping(plan, req.StatusMapping, targetAccepts); msg != "" {
+ writeMappingRequired(w, plan, msg)
+ return
+ }
+ updated, err := qtx.SetProjectWorkflow(ctx, db.SetProjectWorkflowParams{ID: project.ID, WorkspaceID: wsUUID, WorkflowID: targetID})
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to change workflow")
+ return
+ }
+ changed, cancelledWakeups, err := remapIssues(ctx, qtx, wsUUID, []pgtype.UUID{project.ID}, plan, req.StatusMapping)
+ if err != nil {
+ slog.Warn("SetProjectWorkflow remap failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to move issues to the new statuses")
+ return
+ }
+ if err := tx.Commit(ctx); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to change workflow")
+ return
+ }
+ h.publishIssueSnapshots(ctx, changed, "member", uuidToString(member.UserID))
+ h.broadcastCancelledWakeups(ctx, wsUUID, cancelledWakeups)
+ resp := h.publishProjectWorkflowUpdate(ctx, workspaceID, member, updated)
+ writeJSON(w, http.StatusOK, map[string]any{
+ "project": resp,
+ "updated_issues": len(changed),
+ "plan": plan,
+ })
+}
+
+// SetIssueWorkflowHandoffRequest is a column's handoff. CopyForProjectID,
+// when set, leaves the workflow as it is and saves the handoff on a copy of
+// it that only that project uses.
+type SetIssueWorkflowHandoffRequest struct {
+ IssueWorkflowStepPayload
+ CopyForProjectID string `json:"copy_for_project_id,omitempty"`
+}
+
+// SetIssueWorkflowHandoff saves what a workflow does when an issue enters
+// one of its columns: who it is handed to, the instructions their run gets,
+// and where the handler moves it next. It applies to every project using the
+// workflow, unless the caller asks for a copy for one project: the project
+// then switches to the copy in the same transaction. The copy lists the same
+// statuses, so no issue moves.
+func (h *Handler) SetIssueWorkflowHandoff(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+ member, ok := h.requireWorkspaceRole(w, r, workspaceID, "workspace not found", "owner", "admin")
+ if !ok {
+ return
+ }
+ idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workflow id")
+ if !ok {
+ return
+ }
+ var req SetIssueWorkflowHandoffRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ step := issueworkflow.NormalizeHandoff(payloadToStep(chi.URLParam(r, "status"), req.IssueWorkflowStepPayload))
+ if (step.HandsOff() || req.CopyForProjectID != "") && !h.requireProjectWorkflowsV1(w, r) {
+ return
+ }
+ var copyFor pgtype.UUID
+ if req.CopyForProjectID != "" {
+ copyFor, ok = parseUUIDOrBadRequest(w, req.CopyForProjectID, "copy_for_project_id")
+ if !ok {
+ return
+ }
+ }
+ ctx := r.Context()
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save handoff")
+ return
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+ if err := qtx.LockIssueStatusCatalog(ctx, wsUUID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save handoff")
+ return
+ }
+ current, err := qtx.GetIssueWorkflow(ctx, db.GetIssueWorkflowParams{ID: idUUID, WorkspaceID: wsUUID})
+ if err != nil {
+ writeError(w, http.StatusNotFound, "workflow not found")
+ return
+ }
+ def, err := issueworkflow.Decode(current)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to read workflow")
+ return
+ }
+ if err := issueworkflow.ValidateHandoff(step, def); err != nil {
+ writeErrorCode(w, http.StatusBadRequest, "invalid_handoff", err.Error())
+ return
+ }
+ if status, msg := h.validateHandoffHandlers(ctx, r, workspaceID, []issueworkflow.Step{step}, def.Steps); status != 0 {
+ writeErrorCode(w, status, "invalid_handoff", msg)
+ return
+ }
+ for i, s := range def.Steps {
+ if s.StatusKey == step.StatusKey {
+ def.Steps[i] = step
+ }
+ }
+ raw, err := issueworkflow.EncodeSteps(def.Steps)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save handoff")
+ return
+ }
+ if copyFor.Valid {
+ h.saveHandoffOnProjectCopy(w, r, qtx, tx, member, workspaceID, current, raw, copyFor)
+ return
+ }
+ row, err := qtx.UpdateIssueWorkflow(ctx, db.UpdateIssueWorkflowParams{
+ ID: current.ID,
+ WorkspaceID: wsUUID,
+ Name: current.Name,
+ Description: current.Description,
+ InitialStatusKey: issueworkflow.StartStatus,
+ Steps: raw,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save handoff")
+ return
+ }
+ if err := tx.Commit(ctx); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save handoff")
+ return
+ }
+ h.publishIssueWorkflowChanged(workspaceID, member, "updated")
+ h.writeIssueWorkflow(w, r, http.StatusOK, row)
+}
+
+// saveHandoffOnProjectCopy finishes SetIssueWorkflowHandoff for a copy:
+// steps already carry the new handoff. The caller holds the exclusive catalog
+// lock in tx.
+func (h *Handler) saveHandoffOnProjectCopy(w http.ResponseWriter, r *http.Request, qtx *db.Queries, tx pgx.Tx, member db.Member, workspaceID string, source db.IssueWorkflow, steps []byte, projectID pgtype.UUID) {
+ ctx := r.Context()
+ if source.IsDefault {
+ writeErrorCode(w, http.StatusBadRequest, "invalid_handoff", "the Default workflow cannot be copied for one project")
+ return
+ }
+ project, err := qtx.LockProjectForWorkflowChange(ctx, db.LockProjectForWorkflowChangeParams{ID: projectID, WorkspaceID: source.WorkspaceID})
+ if err != nil {
+ writeError(w, http.StatusNotFound, "project not found")
+ return
+ }
+ if project.WorkflowID != source.ID {
+ writeErrorCode(w, http.StatusConflict, "invalid_handoff", "the project does not use this workflow")
+ return
+ }
+ existing, err := qtx.ListIssueWorkflows(ctx, source.WorkspaceID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save handoff")
+ return
+ }
+ taken := make(map[string]bool, len(existing))
+ for _, row := range existing {
+ taken[strings.ToLower(row.Name)] = true
+ }
+ row, err := qtx.CreateIssueWorkflow(ctx, db.CreateIssueWorkflowParams{
+ WorkspaceID: source.WorkspaceID,
+ Name: projectCopyName(source.Name, project.Title, taken),
+ Description: source.Description,
+ InitialStatusKey: issueworkflow.StartStatus,
+ Steps: steps,
+ })
+ if err != nil {
+ slog.Warn("SetIssueWorkflowHandoff copy failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to save handoff")
+ return
+ }
+ updated, err := qtx.SetProjectWorkflow(ctx, db.SetProjectWorkflowParams{ID: project.ID, WorkspaceID: source.WorkspaceID, WorkflowID: row.ID})
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save handoff")
+ return
+ }
+ if err := tx.Commit(ctx); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save handoff")
+ return
+ }
+ h.publishIssueWorkflowChanged(workspaceID, member, "created")
+ h.publishProjectWorkflowUpdate(ctx, workspaceID, member, updated)
+ h.writeIssueWorkflow(w, r, http.StatusCreated, row)
+}
+
+// projectCopyName names a workflow copied for one project, "Workflow
+// (Project)", numbered when that name is taken and cut to the name limit.
+func projectCopyName(workflow, project string, taken map[string]bool) string {
+ for n := 1; ; n++ {
+ suffix := " (" + project + ")"
+ if n > 1 {
+ suffix = " (" + project + " " + strconv.Itoa(n) + ")"
+ }
+ base := []rune(workflow)
+ if room := issueworkflow.MaxNameRunes - utf8.RuneCountInString(suffix); room < len(base) {
+ if room < 1 {
+ suffix = " " + strconv.Itoa(n)
+ room = issueworkflow.MaxNameRunes - len(suffix)
+ }
+ base = base[:room]
+ }
+ name := strings.TrimSpace(string(base)) + suffix
+ if !taken[strings.ToLower(name)] {
+ return name
+ }
+ }
+}
+
+// PreviewIssueWorkflowBriefRequest is a handoff being edited. ProjectID, when
+// set, names the project the preview is for.
+type PreviewIssueWorkflowBriefRequest struct {
+ IssueWorkflowStepPayload
+ ProjectID string `json:"project_id,omitempty"`
+}
+
+// PreviewIssueWorkflowBrief renders the brief a column's handler would
+// receive, for a handoff being edited before it is saved.
+func (h *Handler) PreviewIssueWorkflowBrief(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+ if _, ok := h.requireWorkspaceMember(w, r, workspaceID, "workspace not found"); !ok {
+ return
+ }
+ idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workflow id")
+ if !ok {
+ return
+ }
+ var req PreviewIssueWorkflowBriefRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ ctx := r.Context()
+ row, err := h.Queries.GetIssueWorkflow(ctx, db.GetIssueWorkflowParams{ID: idUUID, WorkspaceID: wsUUID})
+ if err != nil {
+ writeError(w, http.StatusNotFound, "workflow not found")
+ return
+ }
+ def, err := issueworkflow.Decode(row)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to read workflow")
+ return
+ }
+ projectName := ""
+ if req.ProjectID != "" {
+ if id, err := parseUUIDString(req.ProjectID); err == nil {
+ if p, err := h.Queries.GetProjectInWorkspace(ctx, db.GetProjectInWorkspaceParams{ID: id, WorkspaceID: wsUUID}); err == nil {
+ projectName = p.Title
+ }
+ }
+ }
+ step := issueworkflow.NormalizeHandoff(payloadToStep(req.StatusKey, req.IssueWorkflowStepPayload))
+ if !def.Has(step.StatusKey) {
+ writeError(w, http.StatusBadRequest, "status_key is not a column of this workflow")
+ return
+ }
+ for i, s := range def.Steps {
+ if s.StatusKey == step.StatusKey {
+ def.Steps[i] = step
+ }
+ }
+ resolver := issuestatus.NewResolver(wsUUID)
+ brief := issueworkflow.Brief(issueworkflow.BriefInput{
+ Workflow: def,
+ ProjectName: projectName,
+ StatusKey: step.StatusKey,
+ IssueIdentifier: h.getIssuePrefix(ctx, wsUUID) + "-123",
+ StatusName: func(key string) string {
+ return resolver.Name(ctx, h.Queries, key)
+ },
+ HandlerName: func(s issueworkflow.Step) string {
+ switch s.Handler.Type {
+ case issueworkflow.HandlerAgent, issueworkflow.HandlerSquad, issueworkflow.HandlerMember:
+ id, err := parseUUIDString(s.Handler.ID)
+ if err != nil {
+ return s.Handler.Type
+ }
+ return h.actorDisplayName(ctx, wsUUID, s.Handler.Type, id)
+ case issueworkflow.HandlerProjectLead:
+ return "the project lead"
+ case issueworkflow.HandlerCreator:
+ return "the issue creator"
+ }
+ return ""
+ },
+ })
+ writeJSON(w, http.StatusOK, map[string]any{"brief": brief})
+}
+
+// WorkflowHandoffRun is an active run of the agent or squad a handoff takes
+// the issue from.
+type WorkflowHandoffRun struct {
+ TaskID string `json:"task_id"`
+ AgentID string `json:"agent_id"`
+ Status string `json:"status"`
+ StartedAt *string `json:"started_at"`
+}
+
+type WorkflowHandoffPreviewResponse struct {
+ Handoff bool `json:"handoff"`
+ WorkflowName string `json:"workflow_name,omitempty"`
+ FromStatus string `json:"from_status"`
+ ToStatus string `json:"to_status"`
+ HandlerType string `json:"handler_type,omitempty"`
+ HandlerID string `json:"handler_id,omitempty"`
+ PreviousAssigneeType *string `json:"previous_assignee_type"`
+ PreviousAssigneeID *string `json:"previous_assignee_id"`
+ PreviousRuns []WorkflowHandoffRun `json:"previous_runs"`
+ Brief string `json:"brief,omitempty"`
+}
+
+// PreviewWorkflowHandoff says what moving an issue to a status would do under
+// its project's workflow, for the confirmation shown before a handoff: who
+// the issue would go to, which runs of its current agent are still active,
+// and the brief the new handler would receive. With project_id it previews
+// moving the issue into that project and entering the step it lands on
+// (status then optional). It writes nothing.
+func (h *Handler) PreviewWorkflowHandoff(w http.ResponseWriter, r *http.Request) {
+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))
+ if !ok {
+ return
+ }
+ status := r.URL.Query().Get("status")
+ projectParam := r.URL.Query().Get("project_id")
+ if status == "" && projectParam == "" {
+ writeError(w, http.StatusBadRequest, "status is required")
+ return
+ }
+ params := db.UpdateIssueParams{
+ ProjectID: issue.ProjectID,
+ AssigneeType: issue.AssigneeType,
+ AssigneeID: issue.AssigneeID,
+ }
+ if status != "" {
+ params.Status = pgtype.Text{String: status, Valid: true}
+ }
+ enterOnMove := false
+ if projectParam != "" {
+ projectID, ok := parseUUIDOrBadRequest(w, projectParam, "project_id")
+ if !ok {
+ return
+ }
+ if _, err := h.Queries.GetProjectInWorkspace(r.Context(), db.GetProjectInWorkspaceParams{ID: projectID, WorkspaceID: issue.WorkspaceID}); err != nil {
+ writeError(w, http.StatusNotFound, "project not found")
+ return
+ }
+ params.ProjectID = projectID
+ enterOnMove = true
+ }
+ hand, err := h.applyIssueWorkflow(r.Context(), issue, &params, status != "", false, enterOnMove, nil)
+ if err != nil {
+ if writeIssueWorkflowError(w, err) {
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to resolve project workflow")
+ return
+ }
+ if params.Status.Valid {
+ status = params.Status.String
+ } else {
+ status = issue.Status
+ }
+ resp := WorkflowHandoffPreviewResponse{
+ FromStatus: issue.Status,
+ ToStatus: status,
+ PreviousAssigneeType: textToPtr(issue.AssigneeType),
+ PreviousAssigneeID: uuidToPtr(issue.AssigneeID),
+ PreviousRuns: []WorkflowHandoffRun{},
+ }
+ if hand == nil {
+ writeJSON(w, http.StatusOK, resp)
+ return
+ }
+ resp.WorkflowName = hand.def.Name
+ resp.Handoff = true
+ resp.HandlerType = params.AssigneeType.String
+ resp.HandlerID = uuidToString(params.AssigneeID)
+ next := issue
+ next.Status = status
+ next.ProjectID = params.ProjectID
+ next.AssigneeType = params.AssigneeType
+ next.AssigneeID = params.AssigneeID
+ resp.Brief = h.workflowHandoffNote(r.Context(), next, hand)
+ if issue.AssigneeType != params.AssigneeType || issue.AssigneeID != params.AssigneeID {
+ for _, task := range h.assigneeActiveRuns(r.Context(), issue) {
+ started := task.StartedAt
+ if !started.Valid {
+ started = task.CreatedAt
+ }
+ resp.PreviousRuns = append(resp.PreviousRuns, WorkflowHandoffRun{
+ TaskID: uuidToString(task.ID),
+ AgentID: uuidToString(task.AgentID),
+ Status: task.Status,
+ StartedAt: timestampToPtr(started),
+ })
+ }
+ }
+ writeJSON(w, http.StatusOK, resp)
+}
diff --git a/server/internal/handler/issue_workflow_entry.go b/server/internal/handler/issue_workflow_entry.go
new file mode 100644
index 0000000000..977cdce019
--- /dev/null
+++ b/server/internal/handler/issue_workflow_entry.go
@@ -0,0 +1,378 @@
+package handler
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+ "net/http"
+ "strconv"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/issuestatus"
+ "github.com/multica-ai/multica/server/internal/issueworkflow"
+ "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"
+)
+
+// Project workflows on the issue write paths (MUL-7420).
+//
+// Two rules apply to an issue in a project:
+// - when the project uses a named workflow, its status must be one the
+// workflow lists; a move into such a project keeps an equivalent status
+// instead of failing. Default accepts every status;
+// - entering a column the project hands off, through an ordinary status
+// change of an issue that stays in its project, assigns the issue to that
+// handler and starts its run with the step's instructions. A write that
+// sets the assignee itself keeps its explicit choice. A project move
+// enters the column it lands on only when the caller asks for it.
+//
+// Handoffs reuse assignment wholesale: the resolved handler goes through the
+// same permission gate as a hand-picked assignee, and the run starts through
+// the same WillEnqueueRun predicate, with the step's brief as its handoff note.
+
+// workflowHandoff is a handoff an issue write triggers.
+type workflowHandoff struct {
+ def issueworkflow.Definition
+ step issueworkflow.Step
+ project db.Project
+}
+
+// applyIssueWorkflow enforces prev's (possibly new) project workflow on one
+// prospective update and may rewrite params: the status of an issue moving
+// into the project, and the assignee when the write enters a handoff step.
+// enterOnMove makes a project move enter the step the issue lands on.
+// run is the calling agent's run on this issue (nil for members): it may only
+// move the issue from the step it works on. It returns the handoff that write
+// triggers, or nil.
+func (h *Handler) applyIssueWorkflow(ctx context.Context, prev db.Issue, params *db.UpdateIssueParams, statusExplicit, assigneeTouched, enterOnMove bool, run *db.AgentTaskQueue) (*workflowHandoff, error) {
+ def, project, err := issueworkflow.ForProject(ctx, h.Queries, prev.WorkspaceID, params.ProjectID)
+ if err != nil || def == nil {
+ return nil, err
+ }
+ projectMoving := params.ProjectID != prev.ProjectID
+ if projectMoving && !statusExplicit && !def.IsDefault && !def.Has(prev.Status) {
+ target := issueworkflow.MoveTarget(*def, prev.Status, func(key string) string {
+ return issuestatus.Category(ctx, h.Queries, prev.WorkspaceID, key)
+ })
+ params.Status = pgtype.Text{String: target, Valid: true}
+ }
+ if params.Status.Valid {
+ if err := issueworkflow.CheckStatus(def, params.Status.String); err != nil {
+ return nil, err
+ }
+ }
+ // Someone else moved the issue while the run worked: the run's decision was
+ // made for a step the issue has left, and applying it would undo that move.
+ // Default without handoffs keeps the pre-workflow behavior, so workspaces
+ // that never adopt workflows see no change.
+ if run != nil && run.WorkflowStep.Valid && run.WorkflowStep.String != prev.Status &&
+ (!def.IsDefault || def.HandsOffAnywhere()) &&
+ statusExplicit && params.Status.Valid && params.Status.String != prev.Status {
+ return nil, h.stepMovedError(ctx, prev, run.WorkflowStep.String)
+ }
+ if assigneeTouched || prev.TriageState.Valid {
+ return nil, nil
+ }
+ entering := ""
+ switch {
+ case projectMoving && enterOnMove:
+ entering = prev.Status
+ if params.Status.Valid {
+ entering = params.Status.String
+ }
+ // A project move is administrative unless the caller opted in, and
+ // re-selecting the current status is a no-op: neither hands the issue off.
+ case !projectMoving && statusExplicit && params.Status.Valid && params.Status.String != prev.Status:
+ entering = params.Status.String
+ default:
+ return nil, nil
+ }
+ step, ok := def.Step(entering)
+ if !ok || !step.HandsOff() {
+ return nil, nil
+ }
+ assigneeType, assigneeID, ok := issueworkflow.ResolveHandler(step, project, prev.CreatorType, prev.CreatorID)
+ if !ok {
+ return nil, nil
+ }
+ params.AssigneeType = pgtype.Text{String: assigneeType, Valid: true}
+ params.AssigneeID = assigneeID
+ return &workflowHandoff{def: *def, step: step, project: project}, nil
+}
+
+// workflowHandoffPayload describes a handoff on the issue:updated event, so
+// the activity log can record the status change and the handoff as one
+// timeline entry.
+func workflowHandoffPayload(issue db.Issue, hand *workflowHandoff, note string, runStarted bool) map[string]string {
+ out := map[string]string{
+ "workflow": hand.def.Name,
+ "to_type": issue.AssigneeType.String,
+ "to_id": uuidToString(issue.AssigneeID),
+ "run": strconv.FormatBool(runStarted),
+ }
+ if runStarted && note != "" {
+ out["note"] = note
+ }
+ return out
+}
+
+// writeIssueWorkflowError answers a workflow rejection. It reports false when
+// err is not one, so the caller can fall through to its generic 500.
+func writeIssueWorkflowError(w http.ResponseWriter, err error) bool {
+ var notIn *issueworkflow.NotInWorkflowError
+ if errors.As(err, &notIn) {
+ writeJSON(w, http.StatusBadRequest, map[string]any{
+ "error": notIn.Error(),
+ "code": "status_not_in_workflow",
+ "workflow_name": notIn.WorkflowName,
+ "allowed_statuses": notIn.Allowed,
+ })
+ return true
+ }
+ var moved *issueworkflow.StepMovedError
+ if errors.As(err, &moved) {
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": moved.Error(),
+ "code": "workflow_step_moved",
+ "step": moved.Step,
+ "current_status": moved.Current,
+ })
+ return true
+ }
+ return false
+}
+
+// agentRunOnIssue returns the calling agent's run when it works on this issue,
+// nil for members and for runs on other issues. The task id is the
+// server-trusted X-Task-ID resolveActor vouched for.
+func (h *Handler) agentRunOnIssue(r *http.Request, actorType string, issue db.Issue) *db.AgentTaskQueue {
+ if actorType != "agent" {
+ return nil
+ }
+ taskID, err := util.ParseUUID(r.Header.Get("X-Task-ID"))
+ if err != nil {
+ return nil
+ }
+ task, err := h.Queries.GetAgentTask(r.Context(), taskID)
+ if err != nil || task.IssueID != issue.ID {
+ return nil
+ }
+ return &task
+}
+
+// handedToAgent names the agent a write hands the issue to: its new agent
+// assignee, the leader of its new squad assignee, or a workflow step's
+// handler even when that handler already owned the issue. Empty when the
+// write leaves the issue with whoever had it.
+func (h *Handler) handedToAgent(ctx context.Context, prev db.Issue, params db.UpdateIssueParams, handoff bool) string {
+ if !params.AssigneeID.Valid {
+ return ""
+ }
+ if !handoff && params.AssigneeType == prev.AssigneeType && params.AssigneeID == prev.AssigneeID {
+ return ""
+ }
+ switch params.AssigneeType.String {
+ case "agent":
+ return uuidToString(params.AssigneeID)
+ case "squad":
+ squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{ID: params.AssigneeID, WorkspaceID: prev.WorkspaceID})
+ if err == nil && squad.LeaderID.Valid {
+ return uuidToString(squad.LeaderID)
+ }
+ }
+ return ""
+}
+
+// advanceRunStep moves a run's workflow step along with a status change the
+// run made itself, so its next change is judged from where it put the issue.
+func (h *Handler) advanceRunStep(ctx context.Context, run *db.AgentTaskQueue, prev, issue db.Issue) {
+ if run == nil || !run.WorkflowStep.Valid || prev.Status == issue.Status {
+ return
+ }
+ if err := h.Queries.SetTaskWorkflowStep(ctx, db.SetTaskWorkflowStepParams{
+ ID: run.ID,
+ WorkflowStep: pgtype.Text{String: issue.Status, Valid: true},
+ }); err != nil {
+ slog.Warn("workflow: advance run step failed", "task_id", uuidToString(run.ID), "error", err)
+ }
+}
+
+// stepMovedError explains a refused status change: where the run's step was,
+// where the issue is now, and who moved it.
+func (h *Handler) stepMovedError(ctx context.Context, issue db.Issue, step string) error {
+ resolver := issuestatus.NewResolver(issue.WorkspaceID)
+ out := &issueworkflow.StepMovedError{
+ IssueIdentifier: h.getIssuePrefix(ctx, issue.WorkspaceID) + "-" + strconv.Itoa(int(issue.Number)),
+ Step: step,
+ StepName: resolver.Name(ctx, h.Queries, step),
+ Current: issue.Status,
+ CurrentName: resolver.Name(ctx, h.Queries, issue.Status),
+ }
+ if last, err := h.Queries.GetLastIssueStatusChange(ctx, issue.ID); err == nil && last.ActorID.Valid {
+ out.MovedBy = h.actorDisplayName(ctx, issue.WorkspaceID, last.ActorType.String, last.ActorID)
+ }
+ return out
+}
+
+// workflowHandoffNote renders the brief the handler's run receives. Only an
+// agent or squad handler runs, so members never need one.
+func (h *Handler) workflowHandoffNote(ctx context.Context, issue db.Issue, hand *workflowHandoff) string {
+ if hand == nil || !issue.AssigneeType.Valid {
+ return ""
+ }
+ if t := issue.AssigneeType.String; t != "agent" && t != "squad" {
+ return ""
+ }
+ resolver := issuestatus.NewResolver(issue.WorkspaceID)
+ identifier := h.getIssuePrefix(ctx, issue.WorkspaceID) + "-" + strconv.Itoa(int(issue.Number))
+ return issueworkflow.Brief(issueworkflow.BriefInput{
+ Workflow: hand.def,
+ ProjectName: hand.project.Title,
+ StatusKey: hand.step.StatusKey,
+ IssueIdentifier: identifier,
+ StatusName: func(key string) string {
+ return resolver.Name(ctx, h.Queries, key)
+ },
+ HandlerName: func(step issueworkflow.Step) string {
+ if !step.HandsOff() {
+ return ""
+ }
+ return h.stepHandlerName(ctx, issue, hand.project, step)
+ },
+ })
+}
+
+// actorDisplayName names an agent, squad or member for a brief. It falls back
+// to the actor type so a lookup failure never blocks a handoff.
+func (h *Handler) actorDisplayName(ctx context.Context, wsUUID pgtype.UUID, actorType string, id pgtype.UUID) string {
+ switch actorType {
+ case "agent":
+ if agent, err := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: id, WorkspaceID: wsUUID}); err == nil {
+ return agent.Name
+ }
+ case "squad":
+ if squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{ID: id, WorkspaceID: wsUUID}); err == nil {
+ return squad.Name
+ }
+ case "member":
+ if user, err := h.Queries.GetUser(ctx, id); err == nil {
+ return user.Name
+ }
+ }
+ return actorType
+}
+
+// stopPreviousAssigneeRuns cancels the active runs of whoever a handoff took
+// the issue from — an agent's runs, or every run made on a squad's behalf —
+// when the caller asked for it. A handoff back to the same handler keeps its
+// run, and the agent making the handoff keeps its own: that run is the one
+// making this write.
+func (h *Handler) stopPreviousAssigneeRuns(ctx context.Context, prev, issue db.Issue, actorType, actorID string) {
+ if issue.AssigneeType == prev.AssigneeType && issue.AssigneeID == prev.AssigneeID {
+ return
+ }
+ tasks := h.assigneeActiveRuns(ctx, prev)
+ if len(tasks) == 0 {
+ return
+ }
+ actor := service.TaskCancellationActor{Type: actorType}
+ if id, err := parseUUIDString(actorID); err == nil {
+ actor.ID = id
+ actor.Name = h.actorDisplayName(ctx, issue.WorkspaceID, actorType, id)
+ }
+ for _, task := range tasks {
+ if actorType == "agent" && uuidToString(task.AgentID) == actorID {
+ continue
+ }
+ if _, err := h.TaskService.CancelTaskByUser(ctx, task.ID, actor); err != nil {
+ slog.Warn("workflow: cancel previous run failed",
+ "issue_id", uuidToString(issue.ID), "task_id", uuidToString(task.ID), "error", err)
+ }
+ }
+}
+
+// assigneeActiveRuns lists the active runs of an issue's assignee on it: the
+// agent's own runs, or every run made on a squad's behalf. Members run
+// nothing.
+func (h *Handler) assigneeActiveRuns(ctx context.Context, issue db.Issue) []db.AgentTaskQueue {
+ if !issue.AssigneeID.Valid {
+ return nil
+ }
+ assigneeType := issue.AssigneeType.String
+ if assigneeType != "agent" && assigneeType != "squad" {
+ return nil
+ }
+ tasks, err := h.Queries.ListActiveTasksByIssue(ctx, issue.ID)
+ if err != nil {
+ slog.Warn("workflow: list active tasks failed", "issue_id", uuidToString(issue.ID), "error", err)
+ return nil
+ }
+ var out []db.AgentTaskQueue
+ for _, task := range tasks {
+ if (assigneeType == "agent" && task.AgentID == issue.AssigneeID) ||
+ (assigneeType == "squad" && task.SquadID == issue.AssigneeID) {
+ out = append(out, task)
+ }
+ }
+ return out
+}
+
+// claimProjectWorkflow describes the issue's project workflow for a task
+// claim, or nil when there is nothing to say beyond the runtime's own status
+// rules: no project, or Default with no handoffs.
+func (h *Handler) claimProjectWorkflow(ctx context.Context, issue db.Issue) *TaskProjectWorkflowData {
+ def, project, err := issueworkflow.ForProject(ctx, h.Queries, issue.WorkspaceID, issue.ProjectID)
+ if err != nil {
+ slog.Warn("task claim: failed to load project workflow for brief injection",
+ "issue_id", uuidToString(issue.ID), "error", err)
+ return nil
+ }
+ if def == nil || (def.IsDefault && !def.HandsOffAnywhere()) {
+ return nil
+ }
+ resolver := issuestatus.NewResolver(issue.WorkspaceID)
+ out := &TaskProjectWorkflowData{
+ Name: def.Name,
+ CurrentStatusKey: issue.Status,
+ Steps: make([]TaskProjectWorkflowStep, 0, len(def.Steps)),
+ }
+ for _, step := range def.Steps {
+ entry := TaskProjectWorkflowStep{
+ Key: step.StatusKey,
+ Name: resolver.Name(ctx, h.Queries, step.StatusKey),
+ NextStatusKey: def.NextStatus(step.StatusKey),
+ BackStatusKey: step.BackStatusKey,
+ }
+ if step.HandsOff() {
+ entry.Handler = h.stepHandlerName(ctx, issue, project, step)
+ }
+ if step.StatusKey == issue.Status {
+ entry.Instructions = step.Instructions
+ }
+ out.Steps = append(out.Steps, entry)
+ }
+ return out
+}
+
+// stepHandlerName describes who a step hands the issue to, for briefs.
+func (h *Handler) stepHandlerName(ctx context.Context, issue db.Issue, project db.Project, step issueworkflow.Step) string {
+ t, id, ok := issueworkflow.ResolveHandler(step, project, issue.CreatorType, issue.CreatorID)
+ if !ok {
+ switch step.Handler.Type {
+ case issueworkflow.HandlerProjectLead:
+ return "the project lead (none set)"
+ case issueworkflow.HandlerCreator:
+ return "the issue creator"
+ }
+ return ""
+ }
+ name := h.actorDisplayName(ctx, issue.WorkspaceID, t, id)
+ switch step.Handler.Type {
+ case issueworkflow.HandlerProjectLead:
+ return name + " (project lead)"
+ case issueworkflow.HandlerCreator:
+ return name + " (issue creator)"
+ }
+ return name
+}
diff --git a/server/internal/handler/issue_workflow_test.go b/server/internal/handler/issue_workflow_test.go
new file mode 100644
index 0000000000..2d14aaaa99
--- /dev/null
+++ b/server/internal/handler/issue_workflow_test.go
@@ -0,0 +1,1005 @@
+package handler
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+ "unicode/utf8"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/featureflags"
+ "github.com/multica-ai/multica/server/internal/issueworkflow"
+ "github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// Project workflow tests (MUL-7420).
+
+// workflowTestSuffix keeps names unique across tests sharing the workspace.
+func workflowTestSuffix() string {
+ return fmt.Sprintf("%d", time.Now().UnixNano())
+}
+
+func workflowRequest(method, path string, body any) *http.Request {
+ return newRequest(method, path+"?workspace_id="+testWorkspaceID, body)
+}
+
+// statusSteps names a workflow's own steps by status key.
+func statusSteps(keys ...string) []map[string]any {
+ out := make([]map[string]any, len(keys))
+ for i, key := range keys {
+ out[i] = map[string]any{"status_key": key}
+ }
+ return out
+}
+
+// createTestWorkflow creates a workflow with backlog and blocked through the
+// API and deletes it after the test, detaching any project still using it
+// first.
+func createTestWorkflow(t *testing.T, name string, middle ...string) IssueWorkflowResponse {
+ t.Helper()
+ return createTestWorkflowSteps(t, name, statusSteps(append(append([]string{"backlog"}, middle...), "blocked")...))
+}
+
+func createTestWorkflowSteps(t *testing.T, name string, steps []map[string]any) IssueWorkflowResponse {
+ t.Helper()
+ withFeatureFlag(t, testHandler, featureflags.ProjectWorkflowsV1, true)
+ var created IssueWorkflowResponse
+ testutil.Call(t, testHandler.CreateIssueWorkflow, workflowRequest("POST", "/api/issue-workflows", map[string]any{
+ "name": name,
+ "steps": steps,
+ })).Want(http.StatusCreated).JSON(&created)
+ t.Cleanup(func() {
+ ctx := context.Background()
+ testPool.Exec(ctx, `UPDATE project SET workflow_id = NULL WHERE workflow_id = $1`, created.ID)
+ testPool.Exec(ctx, `DELETE FROM issue_workflow WHERE id = $1`, created.ID)
+ })
+ return created
+}
+
+// resetDefaultWorkflow drops the shared workspace's stored Default after the
+// test, so the next test snapshots its own.
+func resetDefaultWorkflow(t *testing.T) {
+ t.Helper()
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM issue_workflow WHERE workspace_id = $1 AND is_default`, testWorkspaceID)
+ })
+}
+
+func createWorkflowTestProject(t *testing.T, title string) string {
+ t.Helper()
+ projectID := dbfx.Project(t, title)
+ t.Cleanup(func() {
+ ctx := context.Background()
+ testPool.Exec(ctx, `DELETE FROM issue_workflow WHERE id = (SELECT workflow_id FROM project WHERE id = $1)
+ AND NOT EXISTS (SELECT 1 FROM project p WHERE p.workflow_id = issue_workflow.id AND p.id <> $1)`, projectID)
+ testPool.Exec(ctx, `DELETE FROM issue WHERE project_id = $1`, projectID)
+ testPool.Exec(ctx, `DELETE FROM project WHERE id = $1`, projectID)
+ })
+ return projectID
+}
+
+func setProjectWorkflow(t *testing.T, projectID string, body map[string]any) *testutil.Response {
+ t.Helper()
+ req := withURLParam(workflowRequest("POST", "/api/projects/"+projectID+"/workflow", body), "id", projectID)
+ return testutil.Call(t, testHandler.SetProjectWorkflow, req)
+}
+
+// projectWorkflowID is the workflow a project uses. For a project on Default
+// it stores Default and drops it after the test, since Default's handoffs
+// apply to every test project on it.
+func projectWorkflowID(t *testing.T, projectID string) string {
+ t.Helper()
+ var id *string
+ dbfx.QueryRow(t, `SELECT workflow_id::text FROM project WHERE id = $1`, projectID).Scan(&id)
+ if id != nil {
+ return *id
+ }
+ resetDefaultWorkflow(t)
+ withFeatureFlag(t, testHandler, featureflags.ProjectWorkflowsV1, true)
+ var list struct {
+ Workflows []IssueWorkflowResponse `json:"workflows"`
+ }
+ testutil.Call(t, testHandler.ListIssueWorkflows, workflowRequest("GET", "/api/issue-workflows", nil)).Want(http.StatusOK).JSON(&list)
+ return list.Workflows[0].ID
+}
+
+func setWorkflowHandoff(t *testing.T, workflowID, statusKey string, body map[string]any) *testutil.Response {
+ t.Helper()
+ withFeatureFlag(t, testHandler, featureflags.ProjectWorkflowsV1, true)
+ req := withURLParams(workflowRequest("PUT", "/api/issue-workflows/"+workflowID+"/handoffs/"+statusKey, body),
+ "id", workflowID, "status", statusKey)
+ return testutil.Call(t, testHandler.SetIssueWorkflowHandoff, req)
+}
+
+// setColumnHandoff sets a column's handoff on the workflow a project uses.
+func setColumnHandoff(t *testing.T, projectID, statusKey string, body map[string]any) *testutil.Response {
+ t.Helper()
+ return setWorkflowHandoff(t, projectWorkflowID(t, projectID), statusKey, body)
+}
+
+func handToAgent(agentID, instructions string) map[string]any {
+ return map[string]any{"handler": map[string]any{"type": "agent", "id": agentID}, "instructions": instructions}
+}
+
+func updateIssueForTest(t *testing.T, issueID string, body map[string]any) *testutil.Response {
+ t.Helper()
+ req := withURLParam(newRequest("PUT", "/api/issues/"+issueID, body), "id", issueID)
+ return testutil.Call(t, testHandler.UpdateIssue, req)
+}
+
+func issueStatusAndAssignee(t *testing.T, issueID string) (status, assigneeType, assigneeID string) {
+ t.Helper()
+ var at, aid *string
+ dbfx.QueryRow(t, `SELECT status, assignee_type, assignee_id::text FROM issue WHERE id = $1`, issueID).Scan(&status, &at, &aid)
+ if at != nil {
+ assigneeType = *at
+ }
+ if aid != nil {
+ assigneeID = *aid
+ }
+ return status, assigneeType, assigneeID
+}
+
+// deliveryProject is the design's simplest case: a project on a Default that
+// hands in_progress to an agent and keeps everything else as is.
+func deliveryProject(t *testing.T, title, agentID string) string {
+ t.Helper()
+ projectID := createWorkflowTestProject(t, title)
+ setColumnHandoff(t, projectID, "in_progress", map[string]any{
+ "handler": map[string]any{"type": "agent", "id": agentID}, "instructions": "Implement it and open a PR.",
+ }).Want(http.StatusOK)
+ return projectID
+}
+
+func TestCreateIssueWorkflowRequiresFlag(t *testing.T) {
+ withFeatureFlag(t, testHandler, featureflags.ProjectWorkflowsV1, false)
+ testutil.Call(t, testHandler.CreateIssueWorkflow, workflowRequest("POST", "/api/issue-workflows", map[string]any{
+ "name": "Flag off " + workflowTestSuffix(),
+ "steps": statusSteps(),
+ })).Want(http.StatusForbidden)
+}
+
+func TestCreateIssueWorkflowPlacesFixedStatusesAndValidates(t *testing.T) {
+ seedTestCatalog(t)
+ resetDefaultWorkflow(t)
+ name := "Validate " + workflowTestSuffix()
+ created := createTestWorkflow(t, name, "done", "in_review")
+ keys := make([]string, len(created.Steps))
+ for i, s := range created.Steps {
+ keys[i] = s.StatusKey
+ }
+ if got := strings.Join(keys, ","); got != "backlog,todo,in_review,blocked,done,cancelled" {
+ t.Fatalf("steps = %s, want the fixed statuses around in_review", got)
+ }
+
+ for label, body := range map[string]map[string]any{
+ "unknown status": {"name": "x" + workflowTestSuffix(), "steps": statusSteps("no_such_status")},
+ "reserved name": {"name": "Default", "steps": statusSteps()},
+ "blank new": {"name": "z" + workflowTestSuffix(), "steps": []map[string]any{{"new_status": map[string]any{"name": " "}}}},
+ } {
+ t.Run(label, func(t *testing.T) {
+ testutil.Call(t, testHandler.CreateIssueWorkflow, workflowRequest("POST", "/api/issue-workflows", body)).
+ Want(http.StatusBadRequest)
+ })
+ }
+ testutil.Call(t, testHandler.CreateIssueWorkflow, workflowRequest("POST", "/api/issue-workflows", map[string]any{
+ "name": strings.ToUpper(name), "steps": statusSteps(),
+ })).Want(http.StatusConflict)
+}
+
+func TestCreateIssueWorkflowCreatesNewStatusesOutsideDefault(t *testing.T) {
+ seedTestCatalog(t)
+ resetDefaultWorkflow(t)
+ statusName := "Spec " + workflowTestSuffix()[10:]
+ withFeatureFlag(t, testHandler, featureflags.ProjectWorkflowsV1, true)
+ var created IssueWorkflowResponse
+ testutil.Call(t, testHandler.CreateIssueWorkflow, workflowRequest("POST", "/api/issue-workflows", map[string]any{
+ "name": "Template " + workflowTestSuffix(),
+ "steps": []map[string]any{{"new_status": map[string]any{"name": statusName, "category": "started"}}, {"status_key": "in_review"}},
+ })).Want(http.StatusCreated).JSON(&created)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM issue_workflow WHERE id = $1`, created.ID)
+ testPool.Exec(context.Background(), `DELETE FROM issue_status WHERE workspace_id = $1 AND name = $2`, testWorkspaceID, statusName)
+ })
+ newKey := created.Steps[1].StatusKey
+ if issuestatusName := lookupStatusName(t, newKey); issuestatusName != statusName {
+ t.Fatalf("step 2 = %q (%q), want the new status", newKey, issuestatusName)
+ }
+
+ var list struct {
+ Workflows []IssueWorkflowResponse `json:"workflows"`
+ }
+ testutil.Call(t, testHandler.ListIssueWorkflows, workflowRequest("GET", "/api/issue-workflows", nil)).Want(http.StatusOK).JSON(&list)
+ if len(list.Workflows) == 0 || !list.Workflows[0].IsDefault {
+ t.Fatalf("list = %+v, want Default first", list.Workflows)
+ }
+ for _, s := range list.Workflows[0].Steps {
+ if s.StatusKey == newKey {
+ t.Fatalf("a status made for a workflow joined Default: %+v", list.Workflows[0].Steps)
+ }
+ }
+}
+
+func lookupStatusName(t *testing.T, key string) string {
+ t.Helper()
+ var name string
+ dbfx.QueryRow(t, `SELECT name FROM issue_status WHERE workspace_id = $1 AND key = $2`, testWorkspaceID, key).Scan(&name)
+ return name
+}
+
+func TestDefaultWorkflowIsEditableButNotDeletable(t *testing.T) {
+ seedTestCatalog(t)
+ resetDefaultWorkflow(t)
+ withFeatureFlag(t, testHandler, featureflags.ProjectWorkflowsV1, true)
+ var list struct {
+ Workflows []IssueWorkflowResponse `json:"workflows"`
+ }
+ testutil.Call(t, testHandler.ListIssueWorkflows, workflowRequest("GET", "/api/issue-workflows", nil)).Want(http.StatusOK).JSON(&list)
+ def := list.Workflows[0]
+ if !def.IsDefault || def.Name != "Default" {
+ t.Fatalf("first workflow = %+v, want Default", def)
+ }
+ projectID := createWorkflowTestProject(t, "Default usage project")
+ issueID := dbfx.Issue(t, "stays on in_review", testutil.Cols{"project_id": projectID, "status": "in_review"})
+
+ var updated IssueWorkflowResponse
+ req := withURLParam(workflowRequest("PATCH", "/api/issue-workflows/"+def.ID, map[string]any{
+ "name": "Renamed", "steps": statusSteps("backlog", "in_progress", "blocked"),
+ }), "id", def.ID)
+ testutil.Call(t, testHandler.UpdateIssueWorkflow, req).Want(http.StatusOK).JSON(&updated)
+ if updated.Name != "Default" || len(updated.Steps) != 6 {
+ t.Fatalf("updated Default = %+v, want its name kept and in_review removed", updated)
+ }
+ // Default accepts every status, so dropping one moves no issue.
+ if status, _, _ := issueStatusAndAssignee(t, issueID); status != "in_review" {
+ t.Fatalf("editing Default moved an issue to %q", status)
+ }
+ updateIssueForTest(t, issueID, map[string]any{"status": "in_review"}).Want(http.StatusOK)
+
+ del := withURLParam(workflowRequest("DELETE", "/api/issue-workflows/"+def.ID, nil), "id", def.ID)
+ testutil.Call(t, testHandler.DeleteIssueWorkflow, del).Want(http.StatusBadRequest)
+}
+
+func TestSetProjectWorkflowMapsOnlyUnlistedStatuses(t *testing.T) {
+ seedTestCatalog(t)
+ resetDefaultWorkflow(t)
+ agentID := seededReadyAgentID(t)
+ wf := createTestWorkflow(t, "Map "+workflowTestSuffix(), "in_review")
+ projectID := createWorkflowTestProject(t, "Workflow map project")
+ setWorkflowHandoff(t, wf.ID, "in_review", handToAgent(agentID, "")).Want(http.StatusOK)
+ keep := dbfx.Issue(t, "stays on todo", testutil.Cols{"project_id": projectID, "status": "todo"})
+ moved := dbfx.Issue(t, "leaves in_progress", testutil.Cols{"project_id": projectID, "status": "in_progress"})
+
+ var dry struct {
+ Plan workflowMappingPlan `json:"plan"`
+ }
+ setProjectWorkflow(t, projectID, map[string]any{"workflow_id": wf.ID, "dry_run": true}).Want(http.StatusOK).JSON(&dry)
+ if len(dry.Plan.Required) != 1 || dry.Plan.Required[0].StatusKey != "in_progress" || dry.Plan.Required[0].IssueCount != 1 {
+ t.Fatalf("plan = %+v, want only in_progress with one issue", dry.Plan)
+ }
+ if len(dry.Plan.Unchanged) != 1 || dry.Plan.Unchanged[0].StatusKey != "todo" {
+ t.Fatalf("unchanged = %+v, want todo kept", dry.Plan.Unchanged)
+ }
+ if got := dry.Plan.Required[0].SuggestedStatusKey; got != "in_review" {
+ t.Fatalf("suggested target = %q, want the same-category step in_review", got)
+ }
+
+ setProjectWorkflow(t, projectID, map[string]any{"workflow_id": wf.ID}).Want(http.StatusConflict)
+ setProjectWorkflow(t, projectID, map[string]any{
+ "workflow_id": wf.ID,
+ "status_mapping": map[string]string{"in_progress": "code_review_nope"},
+ }).Want(http.StatusConflict)
+
+ setProjectWorkflow(t, projectID, map[string]any{
+ "workflow_id": wf.ID,
+ "status_mapping": map[string]string{"in_progress": "in_review"},
+ }).Want(http.StatusOK)
+
+ if status, _, _ := issueStatusAndAssignee(t, keep); status != "todo" {
+ t.Fatalf("an issue on a listed status moved to %q", status)
+ }
+ status, assigneeType, _ := issueStatusAndAssignee(t, moved)
+ if status != "in_review" {
+ t.Fatalf("mapped issue status = %q, want in_review", status)
+ }
+ // Mapping is administrative: entering a handoff column this way neither
+ // reassigns the issue nor starts a run.
+ if assigneeType != "" || taskCountFor(t, moved, agentID) != 0 {
+ t.Fatalf("a workflow switch handed the issue off (assignee type %q)", assigneeType)
+ }
+
+ // Switching back to Default needs no mapping and works with the flag off.
+ withFeatureFlag(t, testHandler, featureflags.ProjectWorkflowsV1, false)
+ setProjectWorkflow(t, projectID, map[string]any{"workflow_id": nil}).Want(http.StatusOK)
+}
+
+func TestUpdateIssueRejectsStatusOutsideNamedWorkflow(t *testing.T) {
+ seedTestCatalog(t)
+ resetDefaultWorkflow(t)
+ wf := createTestWorkflow(t, "Reject "+workflowTestSuffix())
+ projectID := createWorkflowTestProject(t, "Workflow reject project")
+ setProjectWorkflow(t, projectID, map[string]any{"workflow_id": wf.ID}).Want(http.StatusOK)
+ issueID := dbfx.Issue(t, "reject in_progress", testutil.Cols{"project_id": projectID, "status": "todo"})
+
+ body := updateIssueForTest(t, issueID, map[string]any{"status": "in_progress"}).Want(http.StatusBadRequest).Map()
+ if body["code"] != "status_not_in_workflow" {
+ t.Fatalf("code = %v, want status_not_in_workflow", body["code"])
+ }
+ if msg, _ := body["error"].(string); !strings.Contains(msg, "backlog, todo, blocked, done, cancelled") {
+ t.Fatalf("error %q should list the allowed keys", msg)
+ }
+ updateIssueForTest(t, issueID, map[string]any{"status": "blocked"}).Want(http.StatusOK)
+}
+
+func TestStatusChangeHandsOffOnDefaultProject(t *testing.T) {
+ seedTestCatalog(t)
+ agentID := seededReadyAgentID(t)
+ projectID := deliveryProject(t, "Workflow handoff project", agentID)
+ issueID := dbfx.Issue(t, "hand me off", testutil.Cols{"project_id": projectID, "status": "todo"})
+
+ updateIssueForTest(t, issueID, map[string]any{"status": "in_progress"}).Want(http.StatusOK)
+
+ _, assigneeType, assigneeID := issueStatusAndAssignee(t, issueID)
+ if assigneeType != "agent" || assigneeID != agentID {
+ t.Fatalf("assignee = %s/%s, want the column's agent %s", assigneeType, assigneeID, agentID)
+ }
+ tasks, err := testHandler.Queries.ListTasksByIssue(context.Background(), util.MustParseUUID(issueID))
+ if err != nil || len(tasks) != 1 {
+ t.Fatalf("tasks = %d (%v), want one handoff run", len(tasks), err)
+ }
+ note := tasks[0].HandoffNote.String
+ for _, want := range []string{"Implement it and open a PR.", "This project's workflow — Default (Workflow handoff project)", "Step done → multica issue status"} {
+ if !strings.Contains(note, want) {
+ t.Fatalf("handoff note is missing %q:\n%s", want, note)
+ }
+ }
+
+ // A caller-written note replaces the step's brief.
+ back := dbfx.Issue(t, "explicit note", testutil.Cols{"project_id": projectID, "status": "todo"})
+ updateIssueForTest(t, back, map[string]any{"status": "in_progress", "handoff_note": "Only the login flow."}).Want(http.StatusOK)
+ backTasks, _ := testHandler.Queries.ListTasksByIssue(context.Background(), util.MustParseUUID(back))
+ if len(backTasks) != 1 || backTasks[0].HandoffNote.String != "Only the login flow." {
+ t.Fatalf("explicit handoff note was not kept: %+v", backTasks)
+ }
+
+ // A project on a workflow without handoffs hands nothing off.
+ plainProject := createWorkflowTestProject(t, "Workflow no handoff project")
+ setProjectWorkflow(t, plainProject, map[string]any{"workflow_id": createTestWorkflow(t, "Plain "+workflowTestSuffix(), "in_progress").ID}).Want(http.StatusOK)
+ plain := dbfx.Issue(t, "no handoff", testutil.Cols{"project_id": plainProject, "status": "todo"})
+ updateIssueForTest(t, plain, map[string]any{"status": "in_progress"}).Want(http.StatusOK)
+ if _, at, _ := issueStatusAndAssignee(t, plain); at != "" {
+ t.Fatalf("a project without handoffs reassigned the issue to a %s", at)
+ }
+}
+
+func TestSetWorkflowHandoffValidatesAndClears(t *testing.T) {
+ seedTestCatalog(t)
+ agentID := seededReadyAgentID(t)
+ wf := createTestWorkflow(t, "Handoff validation "+workflowTestSuffix(), "in_progress")
+ setWorkflowHandoff(t, wf.ID, "done", map[string]any{"handler": map[string]any{"type": "project_lead"}}).Want(http.StatusBadRequest)
+ setWorkflowHandoff(t, wf.ID, "code_review_nope", handToAgent(agentID, "")).Want(http.StatusBadRequest)
+ setWorkflowHandoff(t, wf.ID, "in_progress", map[string]any{"handler": map[string]any{"type": "creator"}}).Want(http.StatusBadRequest)
+ setWorkflowHandoff(t, wf.ID, "in_progress", map[string]any{
+ "handler": map[string]any{"type": "agent", "id": agentID}, "next_status_key": "in_progress",
+ }).Want(http.StatusBadRequest)
+
+ step := func(resp IssueWorkflowResponse) IssueWorkflowStepPayload {
+ for _, s := range resp.Steps {
+ if s.StatusKey == "in_progress" {
+ return s
+ }
+ }
+ t.Fatalf("in_progress missing from %+v", resp.Steps)
+ return IssueWorkflowStepPayload{}
+ }
+ var saved IssueWorkflowResponse
+ setWorkflowHandoff(t, wf.ID, "in_progress", handToAgent(agentID, "Build it")).Want(http.StatusOK).JSON(&saved)
+ if got := step(saved); got.Handler.ID != agentID || got.Instructions != "Build it" || len(saved.Steps) != 6 {
+ t.Fatalf("saved = %+v", saved.Steps)
+ }
+ setWorkflowHandoff(t, wf.ID, "in_progress", map[string]any{"handler": map[string]any{"type": "none"}}).Want(http.StatusOK).JSON(&saved)
+ if got := step(saved); got.Handler.Type != "none" || got.Instructions != "" {
+ t.Fatalf("clearing left %+v", got)
+ }
+ var stored string
+ dbfx.QueryRow(t, `SELECT steps::text FROM issue_workflow WHERE id = $1`, wf.ID).Scan(&stored)
+ if strings.Contains(stored, "handler") {
+ t.Fatalf("cleared handoff still stored: %s", stored)
+ }
+}
+
+// A workflow's handoffs apply to every project using it, so only workspace
+// admins change them; a project's lead may still switch its workflow.
+func TestWorkflowHandoffsNeedAdmin(t *testing.T) {
+ seedTestCatalog(t)
+ agentID := seededReadyAgentID(t)
+ withFeatureFlag(t, testHandler, featureflags.ProjectWorkflowsV1, true)
+ suffix := workflowTestSuffix()
+ userID := dbfx.User(t, "Workflow member "+suffix, "workflow-member-"+suffix+"@example.com")
+ dbfx.Member(t, testWorkspaceID, userID, "member")
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM member WHERE user_id = $1`, userID)
+ testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userID)
+ })
+ wf := createTestWorkflow(t, "Permission "+suffix, "in_progress")
+ projectID := createWorkflowTestProject(t, "Workflow permission project")
+ dbfx.Exec(t, `UPDATE project SET lead_type = 'member', lead_id = $1 WHERE id = $2`, userID, projectID)
+ asMember := func(r *http.Request) *http.Request {
+ r.Header.Set("X-User-ID", userID)
+ return r
+ }
+ put := withURLParams(asMember(workflowRequest("PUT", "/api/issue-workflows/"+wf.ID+"/handoffs/in_progress", handToAgent(agentID, ""))),
+ "id", wf.ID, "status", "in_progress")
+ testutil.Call(t, testHandler.SetIssueWorkflowHandoff, put).Want(http.StatusForbidden)
+ patch := withURLParam(asMember(workflowRequest("PATCH", "/api/issue-workflows/"+wf.ID, map[string]any{"name": "Taken"})), "id", wf.ID)
+ testutil.Call(t, testHandler.UpdateIssueWorkflow, patch).Want(http.StatusForbidden)
+
+ sw := withURLParam(asMember(workflowRequest("POST", "/api/projects/"+projectID+"/workflow", map[string]any{"workflow_id": wf.ID})), "id", projectID)
+ testutil.Call(t, testHandler.SetProjectWorkflow, sw).Want(http.StatusOK)
+}
+
+// Backlog and blocked are optional: a workflow without them rejects them, and
+// dropping one maps the issues still on it.
+func TestWorkflowWithoutBacklogOrBlocked(t *testing.T) {
+ seedTestCatalog(t)
+ resetDefaultWorkflow(t)
+ lean := createTestWorkflowSteps(t, "Lean "+workflowTestSuffix(), statusSteps("in_progress"))
+ keys := make([]string, len(lean.Steps))
+ for i, s := range lean.Steps {
+ keys[i] = s.StatusKey
+ }
+ if got := strings.Join(keys, ","); got != "todo,in_progress,done,cancelled" {
+ t.Fatalf("lean steps = %s", got)
+ }
+ projectID := createWorkflowTestProject(t, "Workflow lean project")
+ setProjectWorkflow(t, projectID, map[string]any{"workflow_id": lean.ID}).Want(http.StatusOK)
+ issueID := dbfx.Issue(t, "lean", testutil.Cols{"project_id": projectID, "status": "todo"})
+ updateIssueForTest(t, issueID, map[string]any{"status": "blocked"}).Want(http.StatusBadRequest)
+
+ full := createTestWorkflow(t, "Full "+workflowTestSuffix(), "in_progress")
+ other := createWorkflowTestProject(t, "Workflow drop blocked project")
+ setProjectWorkflow(t, other, map[string]any{"workflow_id": full.ID}).Want(http.StatusOK)
+ stuck := dbfx.Issue(t, "stuck", testutil.Cols{"project_id": other, "status": "blocked"})
+ edit := func(body map[string]any) *testutil.Response {
+ return testutil.Call(t, testHandler.UpdateIssueWorkflow, withURLParam(workflowRequest("PATCH", "/api/issue-workflows/"+full.ID, body), "id", full.ID))
+ }
+ var conflict struct {
+ Plan workflowMappingPlan `json:"plan"`
+ }
+ edit(map[string]any{"steps": statusSteps("backlog", "in_progress")}).Want(http.StatusConflict).JSON(&conflict)
+ if len(conflict.Plan.Required) != 1 || conflict.Plan.Required[0].StatusKey != "blocked" || conflict.Plan.Required[0].SuggestedStatusKey != "in_progress" {
+ t.Fatalf("plan = %+v, want blocked mapped to the same-category in_progress", conflict.Plan)
+ }
+ edit(map[string]any{"steps": statusSteps("backlog", "in_progress"), "status_mapping": map[string]string{"blocked": "in_progress"}}).Want(http.StatusOK)
+ if status, _, _ := issueStatusAndAssignee(t, stuck); status != "in_progress" {
+ t.Fatalf("issue on the dropped blocked moved to %q", status)
+ }
+}
+
+func TestExplicitAssigneeWinsOverStepHandler(t *testing.T) {
+ seedTestCatalog(t)
+ agentID := seededReadyAgentID(t)
+ projectID := deliveryProject(t, "Workflow explicit project", agentID)
+ issueID := dbfx.Issue(t, "keep my assignee", testutil.Cols{"project_id": projectID, "status": "todo"})
+
+ updateIssueForTest(t, issueID, map[string]any{
+ "status": "in_progress", "assignee_type": "member", "assignee_id": testUserID,
+ }).Want(http.StatusOK)
+ _, assigneeType, assigneeID := issueStatusAndAssignee(t, issueID)
+ if assigneeType != "member" || assigneeID != testUserID {
+ t.Fatalf("assignee = %s/%s, want the explicit member", assigneeType, assigneeID)
+ }
+ if n := taskCountFor(t, issueID, agentID); n != 0 {
+ t.Fatalf("the step handler ran %d time(s) although the write chose an assignee", n)
+ }
+}
+
+func TestMoveIntoWorkflowProjectKeepsEquivalentStatusWithoutHandoff(t *testing.T) {
+ seedTestCatalog(t)
+ resetDefaultWorkflow(t)
+ agentID := seededReadyAgentID(t)
+ wf := createTestWorkflow(t, "Move "+workflowTestSuffix(), "in_review")
+ projectID := createWorkflowTestProject(t, "Workflow move project")
+ setProjectWorkflow(t, projectID, map[string]any{"workflow_id": wf.ID}).Want(http.StatusOK)
+ setColumnHandoff(t, projectID, "in_review", handToAgent(agentID, "")).Want(http.StatusOK)
+ issueID := dbfx.Issue(t, "moving in", testutil.Cols{"status": "in_progress"})
+
+ updateIssueForTest(t, issueID, map[string]any{"project_id": projectID}).Want(http.StatusOK)
+ status, assigneeType, _ := issueStatusAndAssignee(t, issueID)
+ if status != "in_review" {
+ t.Fatalf("status after move = %q, want the same-category step in_review", status)
+ }
+ if assigneeType != "" || taskCountFor(t, issueID, agentID) != 0 {
+ t.Fatal("moving an issue into a project must not hand it off")
+ }
+
+ // A move confirmed in the UI enters the column it lands on.
+ entering := dbfx.Issue(t, "entering", testutil.Cols{"status": "in_progress"})
+ var preview WorkflowHandoffPreviewResponse
+ req := withURLParam(newRequest("GET", "/api/issues/"+entering+"/workflow-handoff?project_id="+projectID, nil), "id", entering)
+ testutil.Call(t, testHandler.PreviewWorkflowHandoff, req).Want(http.StatusOK).JSON(&preview)
+ if !preview.Handoff || preview.ToStatus != "in_review" || preview.HandlerID != agentID {
+ t.Fatalf("move preview = %+v, want a handoff to in_review's agent", preview)
+ }
+ updateIssueForTest(t, entering, map[string]any{"project_id": projectID, "enter_workflow_step": true}).Want(http.StatusOK)
+ status, assigneeType, assigneeID := issueStatusAndAssignee(t, entering)
+ if status != "in_review" || assigneeType != "agent" || assigneeID != agentID || taskCountFor(t, entering, agentID) != 1 {
+ t.Fatalf("entering move = %s %s/%s, want in_review handed to the agent with one run", status, assigneeType, assigneeID)
+ }
+}
+
+// Saving a shared workflow's handoff for one project copies the workflow for
+// that project; the other projects keep the original.
+func TestWorkflowHandoffCopyForProject(t *testing.T) {
+ seedTestCatalog(t)
+ agentID := seededReadyAgentID(t)
+ withFeatureFlag(t, testHandler, featureflags.ProjectWorkflowsV1, true)
+ wf := createTestWorkflow(t, "Shared "+workflowTestSuffix(), "in_progress")
+ mine := createWorkflowTestProject(t, "Workflow copy mine")
+ theirs := createWorkflowTestProject(t, "Workflow copy theirs")
+ elsewhere := createWorkflowTestProject(t, "Workflow copy elsewhere")
+ setProjectWorkflow(t, mine, map[string]any{"workflow_id": wf.ID}).Want(http.StatusOK)
+ setProjectWorkflow(t, theirs, map[string]any{"workflow_id": wf.ID}).Want(http.StatusOK)
+
+ body := handToAgent(agentID, "Only here")
+ body["copy_for_project_id"] = elsewhere
+ setWorkflowHandoff(t, wf.ID, "in_progress", body).Want(http.StatusConflict)
+
+ body["copy_for_project_id"] = mine
+ var copied IssueWorkflowResponse
+ setWorkflowHandoff(t, wf.ID, "in_progress", body).Want(http.StatusCreated).JSON(&copied)
+ if copied.ID == wf.ID || !strings.HasPrefix(copied.Name, wf.Name+" (") || len(copied.ProjectIDs) != 1 || copied.ProjectIDs[0] != mine {
+ t.Fatalf("copy = %+v, want a new workflow used only by the project", copied)
+ }
+ handlerOf := func(id string) string {
+ var steps string
+ dbfx.QueryRow(t, `SELECT steps::text FROM issue_workflow WHERE id = $1`, id).Scan(&steps)
+ return steps
+ }
+ if !strings.Contains(handlerOf(copied.ID), agentID) || strings.Contains(handlerOf(wf.ID), agentID) {
+ t.Fatal("the handoff must land on the copy only")
+ }
+ var theirsWorkflow string
+ dbfx.QueryRow(t, `SELECT workflow_id::text FROM project WHERE id = $1`, theirs).Scan(&theirsWorkflow)
+ if theirsWorkflow != wf.ID {
+ t.Fatalf("the other project moved to %s", theirsWorkflow)
+ }
+}
+
+func TestProjectCopyName(t *testing.T) {
+ taken := map[string]bool{"delivery (payments)": true}
+ if got := projectCopyName("Delivery", "Payments", taken); got != "Delivery (Payments 2)" {
+ t.Fatalf("name = %q", got)
+ }
+ long := strings.Repeat("x", 70)
+ if got := projectCopyName(long, "P", nil); utf8.RuneCountInString(got) > issueworkflow.MaxNameRunes || !strings.HasSuffix(got, " (P)") {
+ t.Fatalf("long name = %q", got)
+ }
+}
+
+func TestCreateIssueHandsOffItsStartingColumn(t *testing.T) {
+ seedTestCatalog(t)
+ resetDefaultWorkflow(t)
+ agentID := seededReadyAgentID(t)
+ projectID := createWorkflowTestProject(t, "Workflow create project")
+ setColumnHandoff(t, projectID, "todo", map[string]any{
+ "handler": map[string]any{"type": "agent", "id": agentID}, "instructions": "Triage it.",
+ }).Want(http.StatusOK)
+
+ created := createIssueForTest(t, map[string]any{"title": "starts in todo", "project_id": projectID})
+ if created.Status != "todo" {
+ t.Fatalf("status = %q, want todo", created.Status)
+ }
+ if created.AssigneeID == nil || *created.AssigneeID != agentID {
+ t.Fatalf("assignee = %v, want the todo column's agent", created.AssigneeID)
+ }
+ tasks, _ := testHandler.Queries.ListTasksByIssue(context.Background(), util.MustParseUUID(created.ID))
+ if len(tasks) != 1 || !strings.Contains(tasks[0].HandoffNote.String, "Triage it.") {
+ t.Fatalf("create did not start the column's run with its brief: %+v", tasks)
+ }
+
+ wf := createTestWorkflow(t, "Create "+workflowTestSuffix())
+ named := createWorkflowTestProject(t, "Workflow create named project")
+ setProjectWorkflow(t, named, map[string]any{"workflow_id": wf.ID}).Want(http.StatusOK)
+ testutil.Call(t, testHandler.CreateIssue, newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "outside the workflow", "project_id": named, "status": "in_progress",
+ })).Want(http.StatusBadRequest)
+}
+
+func TestArchiveStatusGuardsNamedWorkflowsOnly(t *testing.T) {
+ seedTestCatalog(t)
+ resetDefaultWorkflow(t)
+ entry := createTestCustomStatus(t, "wf_guard_"+workflowTestSuffix()[10:], "started")
+ createTestWorkflow(t, "Guard "+workflowTestSuffix(), entry.Key)
+
+ req := withURLParam(newRequest("DELETE", "/api/issue-statuses/"+util.UUIDToString(entry.ID), nil), "id", util.UUIDToString(entry.ID))
+ body := testutil.Call(t, testHandler.ArchiveIssueStatus, req).Want(http.StatusConflict).Map()
+ if body["code"] != "issue_status_in_workflow" {
+ t.Fatalf("code = %v, want issue_status_in_workflow", body["code"])
+ }
+
+ // A status only Default lists archives and leaves Default.
+ loose := createTestCustomStatus(t, "wf_loose_"+workflowTestSuffix()[10:], "started")
+ var list struct {
+ Workflows []IssueWorkflowResponse `json:"workflows"`
+ }
+ testutil.Call(t, testHandler.ListIssueWorkflows, workflowRequest("GET", "/api/issue-workflows", nil)).Want(http.StatusOK).JSON(&list)
+ def := list.Workflows[0]
+ patch := withURLParam(workflowRequest("PATCH", "/api/issue-workflows/"+def.ID, map[string]any{
+ "steps": statusSteps("in_progress", loose.Key),
+ }), "id", def.ID)
+ testutil.Call(t, testHandler.UpdateIssueWorkflow, patch).Want(http.StatusOK)
+ archive := withURLParam(newRequest("DELETE", "/api/issue-statuses/"+util.UUIDToString(loose.ID), nil), "id", util.UUIDToString(loose.ID))
+ testutil.Call(t, testHandler.ArchiveIssueStatus, archive).Want(http.StatusOK)
+ var steps string
+ dbfx.QueryRow(t, `SELECT steps::text FROM issue_workflow WHERE id = $1`, def.ID).Scan(&steps)
+ if strings.Contains(steps, loose.Key) {
+ t.Fatalf("Default still lists the archived status: %s", steps)
+ }
+}
+
+func TestClaimCarriesProjectWorkflow(t *testing.T) {
+ seedTestCatalog(t)
+ resetDefaultWorkflow(t)
+ agentID := seededReadyAgentID(t)
+ quietProject := createWorkflowTestProject(t, "Workflow quiet project")
+ quiet := dbfx.Issue(t, "no handoffs", testutil.Cols{"project_id": quietProject, "status": "todo"})
+ quietIssue, _ := testHandler.Queries.GetIssue(context.Background(), util.MustParseUUID(quiet))
+ if testHandler.claimProjectWorkflow(context.Background(), quietIssue) != nil {
+ t.Fatal("a Default project without handoffs must not carry a workflow")
+ }
+
+ projectID := deliveryProject(t, "Workflow claim project", agentID)
+ issueID := dbfx.Issue(t, "claim context", testutil.Cols{"project_id": projectID, "status": "in_progress"})
+
+ issue, err := testHandler.Queries.GetIssue(context.Background(), util.MustParseUUID(issueID))
+ if err != nil {
+ t.Fatalf("load issue: %v", err)
+ }
+ got := testHandler.claimProjectWorkflow(context.Background(), issue)
+ if got == nil || got.CurrentStatusKey != "in_progress" || len(got.Steps) != 7 {
+ t.Fatalf("claim workflow = %+v", got)
+ }
+ current := got.Steps[2]
+ if current.Handler == "" || current.Handler == "agent" || current.Instructions == "" || current.NextStatusKey != "in_review" {
+ t.Fatalf("current step = %+v, want a named handler, its instructions and the next column", current)
+ }
+ if got.Steps[3].Instructions != "" {
+ t.Fatal("only the current step's instructions ride the claim")
+ }
+
+ plain := dbfx.Issue(t, "no workflow", testutil.Cols{"status": "todo"})
+ plainIssue, _ := testHandler.Queries.GetIssue(context.Background(), util.MustParseUUID(plain))
+ if testHandler.claimProjectWorkflow(context.Background(), plainIssue) != nil {
+ t.Fatal("an issue outside a project must not carry a workflow")
+ }
+}
+
+func TestPreviewWorkflowHandoffNamesHandlerRunsAndBrief(t *testing.T) {
+ seedTestCatalog(t)
+ agentID := seededReadyAgentID(t)
+ projectID := deliveryProject(t, "Workflow preview project", agentID)
+ issueID := dbfx.Issue(t, "preview me", testutil.Cols{"project_id": projectID, "status": "todo"})
+
+ call := func(status string) *testutil.Response {
+ req := withURLParam(newRequest("GET", "/api/issues/"+issueID+"/workflow-handoff?status="+status, nil), "id", issueID)
+ return testutil.Call(t, testHandler.PreviewWorkflowHandoff, req)
+ }
+ var got WorkflowHandoffPreviewResponse
+ call("in_progress").Want(http.StatusOK).JSON(&got)
+ if !got.Handoff || got.HandlerType != "agent" || got.HandlerID != agentID || got.WorkflowName != "Default" {
+ t.Fatalf("preview = %+v, want a handoff to the column's agent", got)
+ }
+ if !strings.Contains(got.Brief, "Implement it and open a PR.") {
+ t.Fatalf("preview brief is missing the step instructions:\n%s", got.Brief)
+ }
+ if status, _, _ := issueStatusAndAssignee(t, issueID); status != "todo" {
+ t.Fatalf("a preview moved the issue to %q", status)
+ }
+
+ var manual WorkflowHandoffPreviewResponse
+ call("done").Want(http.StatusOK).JSON(&manual)
+ if manual.Handoff {
+ t.Fatalf("a column without a handoff previewed one: %+v", manual)
+ }
+}
+
+func TestPreviewIssueWorkflowBriefUsesTheDraft(t *testing.T) {
+ seedTestCatalog(t)
+ agentID := seededReadyAgentID(t)
+ projectID := createWorkflowTestProject(t, "Workflow brief project")
+ workflowID := projectWorkflowID(t, projectID)
+ var got struct {
+ Brief string `json:"brief"`
+ }
+ preview := func(body map[string]any) *testutil.Response {
+ req := withURLParam(workflowRequest("POST", "/api/issue-workflows/"+workflowID+"/brief", body), "id", workflowID)
+ return testutil.Call(t, testHandler.PreviewIssueWorkflowBrief, req)
+ }
+ preview(map[string]any{
+ "status_key": "in_progress", "handler": map[string]any{"type": "agent", "id": agentID}, "instructions": "Draft step.",
+ "project_id": projectID,
+ }).Want(http.StatusOK).JSON(&got)
+ for _, want := range []string{"Default (Workflow brief project)", "Draft step.", "← current", "in_review\nCan't proceed"} {
+ if !strings.Contains(got.Brief, want) {
+ t.Fatalf("draft brief is missing %q:\n%s", want, got.Brief)
+ }
+ }
+ preview(map[string]any{"status_key": "no_such_column"}).Want(http.StatusBadRequest)
+}
+
+// agentUpdateIssue changes an issue as the agent running taskID, the way a
+// task token reaches the handler.
+func agentUpdateIssue(t *testing.T, issueID, agentID, taskID string, body map[string]any) *testutil.Response {
+ t.Helper()
+ req := withURLParam(newRequest("PUT", "/api/issues/"+issueID, body), "id", issueID)
+ req.Header.Set("X-Actor-Source", "task_token")
+ req.Header.Set("X-Agent-ID", agentID)
+ req.Header.Set("X-Task-ID", taskID)
+ return testutil.Call(t, testHandler.UpdateIssue, req)
+}
+
+func taskWorkflowStep(t *testing.T, taskID string) string {
+ t.Helper()
+ var step *string
+ dbfx.QueryRow(t, `SELECT workflow_step FROM agent_task_queue WHERE id = $1`, taskID).Scan(&step)
+ if step == nil {
+ return ""
+ }
+ return *step
+}
+
+// The validation report: an agent handling two adjacent columns moves the
+// issue into the second from its own run. Entering the step is new work, so a
+// run for it is queued although the agent is still running.
+func TestSameAgentNextStepQueuesARun(t *testing.T) {
+ seedTestCatalog(t)
+ agentID := seededReadyAgentID(t)
+ projectID := deliveryProject(t, "Workflow same agent project", agentID)
+ setColumnHandoff(t, projectID, "in_review", handToAgent(agentID, "Review your own PR.")).Want(http.StatusOK)
+ issueID := dbfx.Issue(t, "same agent twice", testutil.Cols{"project_id": projectID, "status": "todo"})
+
+ updateIssueForTest(t, issueID, map[string]any{"status": "in_progress"}).Want(http.StatusOK)
+ var taskID string
+ dbfx.QueryRow(t, `SELECT id::text FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2`, issueID, agentID).Scan(&taskID)
+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'running', started_at = now() WHERE id = $1`, taskID)
+
+ agentUpdateIssue(t, issueID, agentID, taskID, map[string]any{"status": "in_review"}).Want(http.StatusOK)
+ var queued int
+ var note string
+ dbfx.QueryRow(t, `SELECT count(*), COALESCE(max(handoff_note), '') FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'`, issueID, agentID).Scan(&queued, &note)
+ if queued != 1 || !strings.Contains(note, "Review your own PR.") {
+ t.Fatalf("queued runs for the next step = %d (note %q), want one with the step's brief", queued, note)
+ }
+}
+
+// A run works on the step the issue was at when it was queued. Once someone
+// else moves the issue, the run's status changes are refused — they were
+// decided for a step the issue has left — and the refusal names the move.
+func TestAgentStatusChangeRefusedAfterIssueMoved(t *testing.T) {
+ seedTestCatalog(t)
+ agentID := seededReadyAgentID(t)
+ projectID := deliveryProject(t, "Workflow stale step project", agentID)
+ issueID := dbfx.Issue(t, "stale step", testutil.Cols{"project_id": projectID, "status": "todo"})
+
+ updateIssueForTest(t, issueID, map[string]any{"status": "in_progress"}).Want(http.StatusOK)
+ var taskID string
+ dbfx.QueryRow(t, `SELECT id::text FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2`, issueID, agentID).Scan(&taskID)
+ if got := taskWorkflowStep(t, taskID); got != "in_progress" {
+ t.Fatalf("handoff run step = %q, want in_progress", got)
+ }
+
+ // The run's own move is allowed and carries its step along.
+ agentUpdateIssue(t, issueID, agentID, taskID, map[string]any{"status": "in_review"}).Want(http.StatusOK)
+ if got := taskWorkflowStep(t, taskID); got != "in_review" {
+ t.Fatalf("step after the run's own move = %q, want in_review", got)
+ }
+
+ // A member parks the issue while the run is still going. The activity row
+ // is what the server's listener records for that move; handler tests run
+ // without the listeners.
+ updateIssueForTest(t, issueID, map[string]any{"status": "blocked"}).Want(http.StatusOK)
+ dbfx.Exec(t, `INSERT INTO activity_log (workspace_id, issue_id, actor_type, actor_id, action, details)
+ VALUES ($1, $2, 'member', $3, 'status_changed', '{"from":"in_review","to":"blocked"}')`, testWorkspaceID, issueID, testUserID)
+
+ body := agentUpdateIssue(t, issueID, agentID, taskID, map[string]any{"status": "done"}).Want(http.StatusConflict).Map()
+ if body["code"] != "workflow_step_moved" || body["step"] != "in_review" || body["current_status"] != "blocked" {
+ t.Fatalf("refusal = %v", body)
+ }
+ var memberName string
+ dbfx.QueryRow(t, `SELECT name FROM "user" WHERE id = $1`, testUserID).Scan(&memberName)
+ msg, _ := body["error"].(string)
+ for _, want := range []string{memberName + " moved it to", `"blocked"`, "not applied"} {
+ if !strings.Contains(msg, want) {
+ t.Fatalf("refusal %q is missing %q", msg, want)
+ }
+ }
+ if status, _, _ := issueStatusAndAssignee(t, issueID); status != "blocked" {
+ t.Fatalf("status = %q, the refused change must not apply", status)
+ }
+
+ // Anything but a status change still goes through.
+ agentUpdateIssue(t, issueID, agentID, taskID, map[string]any{"title": "stale step, noted"}).Want(http.StatusOK)
+ agentUpdateIssue(t, issueID, agentID, taskID, map[string]any{"status": "blocked"}).Want(http.StatusOK)
+
+ // A run queued after the move works on the new step.
+ var runtimeID string
+ dbfx.QueryRow(t, `SELECT runtime_id::text FROM agent WHERE id = $1`, agentID).Scan(&runtimeID)
+ fresh := dbfx.Task(t, agentID, testutil.Cols{
+ "issue_id": issueID, "runtime_id": runtimeID, "status": "running", "started_at": time.Now(), "workflow_step": "blocked",
+ })
+ agentUpdateIssue(t, issueID, agentID, fresh, map[string]any{"status": "in_review"}).Want(http.StatusOK)
+}
+
+// A project on Default with no handoffs keeps the pre-workflow behavior: a run
+// may still change the status after someone else moved the issue.
+func TestAgentStatusChangeOnDefaultIgnoresStep(t *testing.T) {
+ seedTestCatalog(t)
+ agentID := seededReadyAgentID(t)
+ projectID := createWorkflowTestProject(t, "Workflow default step project")
+ issueID := dbfx.Issue(t, "default step", testutil.Cols{"project_id": projectID, "status": "blocked"})
+ var runtimeID string
+ dbfx.QueryRow(t, `SELECT runtime_id::text FROM agent WHERE id = $1`, agentID).Scan(&runtimeID)
+ taskID := dbfx.Task(t, agentID, testutil.Cols{
+ "issue_id": issueID, "runtime_id": runtimeID, "status": "running", "started_at": time.Now(), "workflow_step": "todo",
+ })
+
+ agentUpdateIssue(t, issueID, agentID, taskID, map[string]any{"status": "in_review"}).Want(http.StatusOK)
+}
+
+// Squads can't be handed to, but a handoff away from an issue a squad owns
+// offers to stop — and stops — the runs made on
+// the squad's behalf, recording who stopped them.
+func TestHandoffStopsPreviousSquadRuns(t *testing.T) {
+ seedTestCatalog(t)
+ agentID := seededReadyAgentID(t)
+ squadID := dbfx.Squad(t, "Workflow review squad "+workflowTestSuffix(), agentID)
+ projectID := createWorkflowTestProject(t, "Workflow squad stop project")
+ setColumnHandoff(t, projectID, "in_progress", map[string]any{"handler": map[string]any{"type": "member", "id": testUserID}}).Want(http.StatusOK)
+ setColumnHandoff(t, projectID, "in_review", map[string]any{"handler": map[string]any{"type": "squad", "id": squadID}}).Want(http.StatusBadRequest)
+ issueID := dbfx.Issue(t, "squad reviewing", testutil.Cols{
+ "project_id": projectID, "status": "in_review", "assignee_type": "squad", "assignee_id": squadID,
+ })
+ var runtimeID string
+ dbfx.QueryRow(t, `SELECT runtime_id::text FROM agent WHERE id = $1`, agentID).Scan(&runtimeID)
+ running := dbfx.Task(t, agentID, testutil.Cols{
+ "issue_id": issueID, "squad_id": squadID, "runtime_id": runtimeID, "status": "running", "started_at": time.Now(),
+ })
+
+ var preview WorkflowHandoffPreviewResponse
+ req := withURLParam(newRequest("GET", "/api/issues/"+issueID+"/workflow-handoff?status=in_progress", nil), "id", issueID)
+ testutil.Call(t, testHandler.PreviewWorkflowHandoff, req).Want(http.StatusOK).JSON(&preview)
+ if len(preview.PreviousRuns) != 1 || preview.PreviousRuns[0].TaskID != running {
+ t.Fatalf("preview runs = %+v, want the squad's run", preview.PreviousRuns)
+ }
+
+ updateIssueForTest(t, issueID, map[string]any{"status": "in_progress", "stop_previous_assignee_runs": true}).Want(http.StatusOK)
+ var status string
+ var stoppedBy *string
+ dbfx.QueryRow(t, `SELECT status, cancelled_by_name FROM agent_task_queue WHERE id = $1`, running).Scan(&status, &stoppedBy)
+ var memberName string
+ dbfx.QueryRow(t, `SELECT name FROM "user" WHERE id = $1`, testUserID).Scan(&memberName)
+ if status != "cancelled" || stoppedBy == nil || *stoppedBy != memberName {
+ t.Fatalf("squad run = %s stopped by %v, want cancelled by %s", status, stoppedBy, memberName)
+ }
+}
+
+// Remapping an issue into a done status on a workflow switch ends its wakeups,
+// as any status write into done does.
+func TestWorkflowSwitchIntoDoneEndsWakeups(t *testing.T) {
+ seedTestCatalog(t)
+ resetDefaultWorkflow(t)
+ agentID := seededReadyAgentID(t)
+ projectID := createWorkflowTestProject(t, "Workflow switch wakeups project")
+ issueID := dbfx.Issue(t, "wakeups end with the issue", testutil.Cols{"project_id": projectID, "status": "in_review"})
+ svc := service.IssueWakeupService{Tasks: testHandler.TaskService}
+ wakeup, err := svc.Create(context.Background(), parseUUID(issueID), parseUUID(testUserID), pgtype.UUID{},
+ service.WakeupInput{AgentID: agentID, Kind: "at", AfterSeconds: 600, Instruction: "check the PR"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue_wakeup WHERE issue_id = $1`, issueID) })
+ var runtimeID string
+ dbfx.QueryRow(t, `SELECT runtime_id::text FROM agent WHERE id = $1`, agentID).Scan(&runtimeID)
+ pending := dbfx.Task(t, agentID, testutil.Cols{
+ "issue_id": issueID, "runtime_id": runtimeID, "status": "queued",
+ "context": testutil.Raw("jsonb_build_object('wakeup_id', '" + uuidToString(wakeup.ID) + "')"),
+ })
+
+ wf := createTestWorkflow(t, "Wakeup switch "+workflowTestSuffix())
+ setProjectWorkflow(t, projectID, map[string]any{
+ "workflow_id": wf.ID, "status_mapping": map[string]string{"in_review": "done"},
+ }).Want(http.StatusOK)
+
+ var enabled bool
+ var taskStatus string
+ dbfx.QueryRow(t, `SELECT enabled FROM issue_wakeup WHERE id = $1`, uuidToString(wakeup.ID)).Scan(&enabled)
+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, pending).Scan(&taskStatus)
+ if enabled || taskStatus != "cancelled" {
+ t.Fatalf("after the switch into done: wakeup enabled=%v, pending wakeup run %s", enabled, taskStatus)
+ }
+}
+
+// A write that hands an issue to an agent delivers the change to that agent
+// as its run, so the agent's event wakeups skip it; other agents' wakeups and
+// the platform's own rules (which have no agent) still capture it. Holds for
+// workflow handoffs and plain assignment alike.
+func TestHandoffDoesNotAlsoWakeTheHandler(t *testing.T) {
+ seedTestCatalog(t)
+ handler := seededReadyAgentID(t)
+ var runtimeID string
+ dbfx.QueryRow(t, `SELECT runtime_id::text FROM agent WHERE id = $1`, handler).Scan(&runtimeID)
+ watcher := dbfx.Agent(t, "Workflow wakeup watcher "+workflowTestSuffix(), runtimeID)
+ projectID := deliveryProject(t, "Workflow wakeup dedupe project", handler)
+ svc := service.IssueWakeupService{Tasks: testHandler.TaskService}
+ subscribe := func(issueID, agentID string) string {
+ t.Helper()
+ w, err := svc.Create(context.Background(), parseUUID(issueID), parseUUID(testUserID), pgtype.UUID{}, service.WakeupInput{
+ AgentID: agentID, Kind: "event", EventTypes: []string{"issue.status_changed", "issue.assignee_changed"}, Instruction: "look again",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM issue_wakeup_receipt WHERE wakeup_id = $1`, w.ID)
+ })
+ return uuidToString(w.ID)
+ }
+ pending := func(wakeupID string) int {
+ t.Helper()
+ var n int
+ dbfx.QueryRow(t, `SELECT count(*) FROM issue_wakeup_receipt WHERE wakeup_id = $1 AND processed_at IS NULL`, wakeupID).Scan(&n)
+ return n
+ }
+
+ handedOff := dbfx.Issue(t, "handed off", testutil.Cols{"project_id": projectID, "status": "todo"})
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue_wakeup WHERE issue_id = $1`, handedOff) })
+ handlerWakeup, watcherWakeup := subscribe(handedOff, handler), subscribe(handedOff, watcher)
+ platformRule := func(issueID string) string {
+ t.Helper()
+ var id string
+ dbfx.QueryRow(t, `INSERT INTO issue_wakeup (id, workspace_id, issue_id, instruction, kind, mode, event_types, system_rule)
+ VALUES (gen_random_uuid(), $1, $2, 'stage closed', 'event', 'continuous', ARRAY['issue.status_changed'], 'child_done')
+ RETURNING id::text`, testWorkspaceID, issueID).Scan(&id)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM issue_wakeup_receipt WHERE wakeup_id = $1`, id)
+ })
+ return id
+ }
+ handedOffRule := platformRule(handedOff)
+ updateIssueForTest(t, handedOff, map[string]any{"status": "in_progress"}).Want(http.StatusOK)
+ if n := pending(handlerWakeup); n != 0 {
+ t.Fatalf("the handoff also woke its handler: %d receipt(s)", n)
+ }
+ if n := pending(watcherWakeup); n == 0 {
+ t.Fatal("another agent's wakeup missed the handoff")
+ }
+ if n := pending(handedOffRule); n == 0 {
+ t.Fatal("the platform rule missed the handoff")
+ }
+
+ parked := dbfx.Issue(t, "parked without a handoff", testutil.Cols{"status": "todo"})
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue_wakeup WHERE issue_id = $1`, parked) })
+ parkedRule := platformRule(parked)
+ updateIssueForTest(t, parked, map[string]any{"status": "backlog"}).Want(http.StatusOK)
+ if n := pending(parkedRule); n == 0 {
+ t.Fatal("the platform rule missed a status change that handed the issue to nobody")
+ }
+
+ assigned := dbfx.Issue(t, "assigned", testutil.Cols{"status": "todo"})
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue_wakeup WHERE issue_id = $1`, assigned) })
+ handlerWakeup, watcherWakeup = subscribe(assigned, handler), subscribe(assigned, watcher)
+ updateIssueForTest(t, assigned, map[string]any{"assignee_type": "agent", "assignee_id": handler}).Want(http.StatusOK)
+ if n := pending(handlerWakeup); n != 0 {
+ t.Fatalf("assignment also woke the assignee: %d receipt(s)", n)
+ }
+ if n := pending(watcherWakeup); n == 0 {
+ t.Fatal("another agent's wakeup missed the assignment")
+ }
+}
diff --git a/server/internal/handler/project.go b/server/internal/handler/project.go
index 6a6592284a..accfb0ce8a 100644
--- a/server/internal/handler/project.go
+++ b/server/internal/handler/project.go
@@ -44,6 +44,9 @@ type ProjectResponse struct {
// payload to keep parent metadata and child collections separate; clients
// that need the list call ListProjectResources directly.
ResourceCount int64 `json:"resource_count"`
+ // WorkflowID is the workflow this project uses; null means the workspace
+ // Default workflow. (MUL-7420)
+ WorkflowID *string `json:"workflow_id"`
}
func projectToResponse(p db.Project) ProjectResponse {
@@ -61,6 +64,7 @@ func projectToResponse(p db.Project) ProjectResponse {
DueDate: dateToPtr(p.DueDate),
CreatedAt: timestampToString(p.CreatedAt),
UpdatedAt: timestampToString(p.UpdatedAt),
+ WorkflowID: uuidToPtr(p.WorkflowID),
}
}
@@ -109,6 +113,10 @@ type CreateProjectRequest struct {
StartDate *string `json:"start_date"`
DueDate *string `json:"due_date"`
Resources []CreateProjectResourceRequestPayload `json:"resources,omitempty"`
+ // WorkflowID picks the project's workflow at creation; omitted or null
+ // uses the workspace Default workflow. A new project has no issues, so no
+ // status mapping is involved. (MUL-7420)
+ WorkflowID *string `json:"workflow_id,omitempty"`
}
// CreateProjectResourceRequestPayload mirrors CreateProjectResourceRequest but
@@ -300,6 +308,24 @@ func (h *Handler) CreateProject(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ var workflowID pgtype.UUID
+ if req.WorkflowID != nil && *req.WorkflowID != "" {
+ if !h.requireProjectWorkflowsV1(w, r) {
+ return
+ }
+ id, ok := parseUUIDOrBadRequest(w, *req.WorkflowID, "workflow_id")
+ if !ok {
+ return
+ }
+ row, err := h.Queries.GetIssueWorkflow(r.Context(), db.GetIssueWorkflowParams{ID: id, WorkspaceID: wsUUID})
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "workflow not found in this workspace")
+ return
+ }
+ if !row.IsDefault {
+ workflowID = id
+ }
+ }
// start_date / due_date are optional calendar days; an absent or empty
// value leaves the column NULL. Mirrors CreateIssue's date handling.
@@ -378,6 +404,7 @@ func (h *Handler) CreateProject(w http.ResponseWriter, r *http.Request) {
Priority: priority,
StartDate: startDate,
DueDate: dueDate,
+ WorkflowID: workflowID,
}
// Without resources, keep the simple non-tx path.
diff --git a/server/internal/handler/wakeup_actor.go b/server/internal/handler/wakeup_actor.go
index 50bcc7285a..a1fc0a4d78 100644
--- a/server/internal/handler/wakeup_actor.go
+++ b/server/internal/handler/wakeup_actor.go
@@ -10,6 +10,17 @@ import (
type wakeupActorKey struct{}
type wakeupActor struct{ kind, id, task string }
+type wakeupHandedToKey struct{}
+
+// withWakeupHandedTo names the agent a write hands the issue to. That agent
+// gets the change as its own run, so the write's issue events skip its event
+// wakeups (migration 558, MUL-7420).
+func withWakeupHandedTo(ctx context.Context, agentID string) context.Context {
+ if agentID == "" {
+ return ctx
+ }
+ return context.WithValue(ctx, wakeupHandedToKey{}, agentID)
+}
// Carry only server-resolved request identity into transaction-local settings.
// In particular, mutation of another agent's comment must not reuse its author
@@ -39,6 +50,12 @@ func (h *Handler) beginWakeupWrite(ctx context.Context) (pgx.Tx, error) {
return nil, err
}
}
+ if agent, ok := ctx.Value(wakeupHandedToKey{}).(string); ok {
+ if _, err = tx.Exec(ctx, `SELECT set_config('multica.handed_to_agent',$1,true)`, agent); err != nil {
+ _ = tx.Rollback(ctx)
+ return nil, err
+ }
+ }
return tx, nil
}
diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.go
index 35f652fdd1..232c2fa338 100644
--- a/server/internal/handler/workspace.go
+++ b/server/internal/handler/workspace.go
@@ -1293,6 +1293,14 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {
return qtx.DeleteIssueStatusEntriesForWorkspace(ctx, requester.WorkspaceID)
},
},
+ {
+ // issue_workflow references the status catalog and projects by
+ // value only, so it is swept alongside the catalog. (MUL-7420)
+ name: "delete issue workflows",
+ run: func() error {
+ return qtx.DeleteIssueWorkflowsForWorkspace(ctx, requester.WorkspaceID)
+ },
+ },
{
name: "delete autopilot children",
run: func() error { return qtx.DeleteWorkspaceAutopilotChildren(ctx, requester.WorkspaceID) },
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index cb9ede8950..357a68902d 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -87,6 +87,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"issue_source_context": workspaceDelete,
"issue_source_context_object_intent": workspaceDeleteSettle,
"issue_status": workspaceDelete,
+ "issue_workflow": workspaceDelete,
"issue_subscriber": workspaceDelete,
"issue_to_label": workspaceDelete,
"issue_vcs_pull_request": workspaceDelete,
diff --git a/server/internal/issueworkflow/default.go b/server/internal/issueworkflow/default.go
new file mode 100644
index 0000000000..6ceb317e7b
--- /dev/null
+++ b/server/internal/issueworkflow/default.go
@@ -0,0 +1,82 @@
+package issueworkflow
+
+import (
+ "context"
+ "errors"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/issuestatus"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// DefaultStore is what storing the Default workflow needs.
+type DefaultStore interface {
+ issuestatus.Querier
+ GetDefaultIssueWorkflow(ctx context.Context, workspaceID pgtype.UUID) (db.IssueWorkflow, error)
+ ListNamedIssueWorkflowSteps(ctx context.Context, workspaceID pgtype.UUID) ([][]byte, error)
+ CreateDefaultIssueWorkflow(ctx context.Context, arg db.CreateDefaultIssueWorkflowParams) ([]db.IssueWorkflow, error)
+}
+
+// EnsureDefault returns the workspace's stored Default workflow, creating it
+// first when needed. The new row lists every active status no other workflow
+// lists, so a workspace that already uses custom statuses keeps its columns,
+// while statuses added for one workflow stay out of Default.
+func EnsureDefault(ctx context.Context, q DefaultStore, workspaceID pgtype.UUID) (db.IssueWorkflow, error) {
+ row, err := q.GetDefaultIssueWorkflow(ctx, workspaceID)
+ if err == nil {
+ return row, nil
+ }
+ if !errors.Is(err, pgx.ErrNoRows) {
+ return db.IssueWorkflow{}, err
+ }
+ keys, err := DefaultSnapshotKeys(ctx, q, workspaceID)
+ if err != nil {
+ return db.IssueWorkflow{}, err
+ }
+ raw, err := EncodeKeys(keys)
+ if err != nil {
+ return db.IssueWorkflow{}, err
+ }
+ created, err := q.CreateDefaultIssueWorkflow(ctx, db.CreateDefaultIssueWorkflowParams{WorkspaceID: workspaceID, Steps: raw})
+ if err != nil {
+ return db.IssueWorkflow{}, err
+ }
+ if len(created) > 0 {
+ return created[0], nil
+ }
+ // Another request stored it first.
+ return q.GetDefaultIssueWorkflow(ctx, workspaceID)
+}
+
+// DefaultSnapshotKeys lists what a new Default row holds: the built-in
+// statuses, backlog and blocked included, plus every active custom status no
+// other workflow lists, in catalog order.
+func DefaultSnapshotKeys(ctx context.Context, q DefaultStore, workspaceID pgtype.UUID) ([]string, error) {
+ active, err := issuestatus.ActiveKeys(ctx, q, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ named, err := q.ListNamedIssueWorkflowSteps(ctx, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ claimed := map[string]bool{}
+ for _, raw := range named {
+ keys, err := DecodeKeys(raw)
+ if err != nil {
+ continue
+ }
+ for _, key := range keys {
+ claimed[key] = true
+ }
+ }
+ middle := make([]string, 0, len(active))
+ for _, key := range active {
+ if claimed[key] && !issuestatus.IsBuiltIn(key) {
+ continue
+ }
+ middle = append(middle, key)
+ }
+ return ArrangeKeys(middle), nil
+}
diff --git a/server/internal/issueworkflow/issueworkflow.go b/server/internal/issueworkflow/issueworkflow.go
new file mode 100644
index 0000000000..cd5cf9c3e5
--- /dev/null
+++ b/server/internal/issueworkflow/issueworkflow.go
@@ -0,0 +1,686 @@
+// Package issueworkflow owns project workflows (MUL-7420).
+//
+// A workflow is a whole pipeline: it selects and orders statuses from the
+// workspace's shared issue_status catalog, and says who each column hands an
+// issue to. Every workflow lists todo, done and cancelled; backlog and
+// blocked are optional; only their positions are fixed (backlog, todo first;
+// blocked, done, cancelled last). Statuses stay shared and peer-level, so
+// issue.status keeps holding a catalog key.
+//
+// When an issue of a project enters a status through an ordinary issue write,
+// it is assigned to the workflow's handler for that status and, for an agent,
+// its run starts with the step's instructions. A relative handler (the project
+// lead) resolves per project, so projects can share a workflow.
+//
+// A project without a workflow uses the workspace Default workflow. Default
+// is a stored row once created; before that it is the built-in statuses.
+// Status writes on a Default project are never rejected: issues already on
+// statuses Default does not list keep them, as they always have.
+package issueworkflow
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "unicode/utf8"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/issuestatus"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// Handler types a project can hand an issue to when it enters a status.
+const (
+ HandlerNone = "none"
+ HandlerAgent = "agent"
+ HandlerSquad = "squad"
+ HandlerMember = "member"
+ HandlerProjectLead = "project_lead"
+ HandlerCreator = "creator"
+)
+
+const (
+ MaxSteps = 50
+ MaxNameRunes = 64
+ MaxDescriptionRunes = 256
+ MaxInstructionsRunes = 8000
+ DefaultName = "Default"
+)
+
+// StartStatus is where a new issue lands unless its creator picks a status.
+const StartStatus = issuestatus.Todo
+
+// These statuses sit in fixed places around a workflow's own steps. Backlog
+// and blocked are optional; the rest every workflow lists.
+var (
+ fixedHead = []string{issuestatus.Backlog, issuestatus.Todo}
+ fixedTail = []string{issuestatus.Blocked, issuestatus.Done, issuestatus.Cancelled}
+)
+
+// IsRequired reports whether every workflow must list the status: new issues
+// start on todo, and done and cancelled are how work ends.
+func IsRequired(key string) bool {
+ switch key {
+ case issuestatus.Todo, issuestatus.Done, issuestatus.Cancelled:
+ return true
+ }
+ return false
+}
+
+// IsFixed reports whether the status has a fixed place when listed.
+func IsFixed(key string) bool {
+ for _, k := range fixedHead {
+ if k == key {
+ return true
+ }
+ }
+ for _, k := range fixedTail {
+ if k == key {
+ return true
+ }
+ }
+ return false
+}
+
+// AcceptsHandoff reports whether entering the status can hand an issue off.
+// Parking, finishing and cancelling an issue never reassign it.
+func AcceptsHandoff(key string) bool {
+ switch key {
+ case issuestatus.Backlog, issuestatus.Done, issuestatus.Cancelled:
+ return false
+ }
+ return true
+}
+
+// Arrange puts a workflow's steps in board order: the fixed statuses it
+// lists in their places around its own steps, with the required ones added
+// when missing. A repeated fixed status keeps its first step.
+func Arrange(steps []Step) []Step {
+ fixed := map[string]Step{}
+ middle := make([]Step, 0, len(steps))
+ for _, s := range steps {
+ if !IsFixed(s.StatusKey) {
+ middle = append(middle, s)
+ continue
+ }
+ if _, ok := fixed[s.StatusKey]; !ok {
+ fixed[s.StatusKey] = s
+ }
+ }
+ place := func(out []Step, keys []string) []Step {
+ for _, key := range keys {
+ if s, ok := fixed[key]; ok {
+ out = append(out, s)
+ } else if IsRequired(key) {
+ out = append(out, Step{StatusKey: key, Handler: Handler{Type: HandlerNone}})
+ }
+ }
+ return out
+ }
+ out := place(make([]Step, 0, len(steps)+len(fixedHead)+len(fixedTail)), fixedHead)
+ out = append(out, middle...)
+ return place(out, fixedTail)
+}
+
+// ArrangeKeys is Arrange for bare status keys.
+func ArrangeKeys(keys []string) []string {
+ return keysOf(Arrange(stepsFor(keys)))
+}
+
+func keysOf(steps []Step) []string {
+ keys := make([]string, len(steps))
+ for i, s := range steps {
+ keys[i] = s.StatusKey
+ }
+ return keys
+}
+
+// MiddleKeys returns the workflow's own steps, without the fixed statuses.
+func MiddleKeys(keys []string) []string {
+ out := make([]string, 0, len(keys))
+ for _, key := range keys {
+ if !IsFixed(key) {
+ out = append(out, key)
+ }
+ }
+ return out
+}
+
+// BuiltInDefaultKeys is Default before a workspace stores its own.
+func BuiltInDefaultKeys() []string {
+ return ArrangeKeys([]string{issuestatus.Backlog, issuestatus.InProgress, issuestatus.InReview, issuestatus.Blocked})
+}
+
+// Handler names who receives an issue when it enters a step. ID is set only
+// for the concrete types (agent, squad, member).
+type Handler struct {
+ Type string `json:"type"`
+ ID string `json:"id,omitempty"`
+}
+
+// Step is one status of a workflow with its handoff.
+type Step struct {
+ StatusKey string `json:"status_key"`
+ Handler Handler `json:"handler"`
+ Instructions string `json:"instructions"`
+ NextStatusKey string `json:"next_status_key,omitempty"`
+ BackStatusKey string `json:"back_status_key,omitempty"`
+}
+
+// Definition is a decoded workflow.
+type Definition struct {
+ ID pgtype.UUID
+ Name string
+ IsDefault bool
+ Steps []Step
+}
+
+// HandsOff reports whether entering the step reassigns the issue.
+func (s Step) HandsOff() bool {
+ switch s.Handler.Type {
+ case HandlerAgent, HandlerSquad, HandlerMember, HandlerProjectLead, HandlerCreator:
+ return true
+ }
+ return false
+}
+
+// storedStep is a step as the workflow row stores it; a step without a
+// handoff is just its status key.
+type storedStep struct {
+ StatusKey string `json:"status_key"`
+ Handler *Handler `json:"handler,omitempty"`
+ Instructions string `json:"instructions,omitempty"`
+ NextStatusKey string `json:"next_status_key,omitempty"`
+ BackStatusKey string `json:"back_status_key,omitempty"`
+}
+
+// Decode parses a stored workflow row.
+func Decode(row db.IssueWorkflow) (Definition, error) {
+ steps, err := DecodeSteps(row.Steps)
+ if err != nil {
+ return Definition{}, err
+ }
+ return Definition{ID: row.ID, Name: row.Name, IsDefault: row.IsDefault, Steps: steps}, nil
+}
+
+// DecodeSteps parses a stored steps array, normalizing a missing handler to
+// "none".
+func DecodeSteps(raw []byte) ([]Step, error) {
+ if len(raw) == 0 {
+ return []Step{}, nil
+ }
+ var stored []storedStep
+ if err := json.Unmarshal(raw, &stored); err != nil {
+ return nil, fmt.Errorf("decode workflow steps: %w", err)
+ }
+ steps := make([]Step, len(stored))
+ for i, s := range stored {
+ steps[i] = Step{
+ StatusKey: s.StatusKey,
+ Handler: Handler{Type: HandlerNone},
+ Instructions: s.Instructions,
+ NextStatusKey: s.NextStatusKey,
+ BackStatusKey: s.BackStatusKey,
+ }
+ if s.Handler != nil && s.Handler.Type != "" {
+ steps[i].Handler = *s.Handler
+ }
+ }
+ return steps, nil
+}
+
+// DecodeKeys parses a stored steps array into its status keys, in order.
+func DecodeKeys(raw []byte) ([]string, error) {
+ steps, err := DecodeSteps(raw)
+ if err != nil {
+ return nil, err
+ }
+ return keysOf(steps), nil
+}
+
+// EncodeSteps serializes a workflow's steps for storage.
+func EncodeSteps(steps []Step) ([]byte, error) {
+ stored := make([]storedStep, len(steps))
+ for i, s := range steps {
+ stored[i] = storedStep{StatusKey: s.StatusKey, NextStatusKey: s.NextStatusKey, BackStatusKey: s.BackStatusKey}
+ if s.HandsOff() {
+ h := s.Handler
+ stored[i].Handler = &h
+ stored[i].Instructions = s.Instructions
+ }
+ }
+ return json.Marshal(stored)
+}
+
+// EncodeKeys serializes statuses without handoffs for storage.
+func EncodeKeys(keys []string) ([]byte, error) {
+ return EncodeSteps(stepsFor(keys))
+}
+
+func stepsFor(keys []string) []Step {
+ steps := make([]Step, len(keys))
+ for i, key := range keys {
+ steps[i] = Step{StatusKey: key, Handler: Handler{Type: HandlerNone}}
+ }
+ return steps
+}
+
+// Has reports whether the workflow lists the status key.
+func (d Definition) Has(key string) bool {
+ _, ok := d.Step(key)
+ return ok
+}
+
+// Step returns the step for a status key.
+func (d Definition) Step(key string) (Step, bool) {
+ for _, s := range d.Steps {
+ if s.StatusKey == key {
+ return s, true
+ }
+ }
+ return Step{}, false
+}
+
+// StatusKeys lists the workflow's statuses in board order.
+func (d Definition) StatusKeys() []string {
+ return keysOf(d.Steps)
+}
+
+// HandsOffAnywhere reports whether any step hands an issue off.
+func (d Definition) HandsOffAnywhere() bool {
+ for _, s := range d.Steps {
+ if s.HandsOff() {
+ return true
+ }
+ }
+ return false
+}
+
+// NextStatus is where a step's handler moves the issue when done: the step's
+// own choice, or else the next status on the board that is not blocked.
+func (d Definition) NextStatus(key string) string {
+ step, ok := d.Step(key)
+ if !ok {
+ return ""
+ }
+ if step.NextStatusKey != "" {
+ return step.NextStatusKey
+ }
+ for i, s := range d.Steps {
+ if s.StatusKey != key {
+ continue
+ }
+ for _, next := range d.Steps[i+1:] {
+ if next.StatusKey != issuestatus.Blocked {
+ return next.StatusKey
+ }
+ }
+ }
+ return ""
+}
+
+// CatalogEntry is the slice of an issue_status row validation needs.
+type CatalogEntry struct {
+ Key string
+ Name string
+ Category string
+ Archived bool
+}
+
+// Normalize trims free text and handoffs and puts the steps in board order.
+func Normalize(name, description string, steps []Step) (string, string, []Step) {
+ normalized := make([]Step, len(steps))
+ for i, s := range steps {
+ normalized[i] = NormalizeHandoff(s)
+ }
+ return strings.TrimSpace(name), strings.TrimSpace(description), Arrange(normalized)
+}
+
+// ValidationError is a user-correctable problem with a workflow definition.
+type ValidationError struct{ Message string }
+
+func (e *ValidationError) Error() string { return e.Message }
+
+func invalid(format string, args ...any) error {
+ return &ValidationError{Message: fmt.Sprintf(format, args...)}
+}
+
+// Validate checks a normalized workflow and its handoffs against the status
+// catalog. The Default workflow keeps its reserved name. Handler ids are
+// checked by the caller, which owns the workspace lookups.
+func Validate(name, description string, steps []Step, isDefault bool, catalog map[string]CatalogEntry) error {
+ if !isDefault {
+ if name == "" || utf8.RuneCountInString(name) > MaxNameRunes {
+ return invalid("name must be 1-%d characters", MaxNameRunes)
+ }
+ if strings.EqualFold(name, DefaultName) {
+ return invalid("%q is reserved for the workspace default workflow", DefaultName)
+ }
+ }
+ if utf8.RuneCountInString(description) > MaxDescriptionRunes {
+ return invalid("description must be at most %d characters", MaxDescriptionRunes)
+ }
+ if len(steps) > MaxSteps {
+ return invalid("a workflow can have at most %d statuses", MaxSteps)
+ }
+ seen := make(map[string]bool, len(steps))
+ for _, key := range keysOf(steps) {
+ entry, ok := catalog[key]
+ if !ok && !issuestatus.IsBuiltIn(key) {
+ return invalid("status %q does not exist", key)
+ }
+ if ok && entry.Archived {
+ return invalid("status %q is archived", key)
+ }
+ if seen[key] {
+ return invalid("status %q appears more than once", key)
+ }
+ seen[key] = true
+ }
+ def := Definition{Steps: steps}
+ for _, s := range steps {
+ if err := ValidateHandoff(s, def); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// NormalizeHandoff trims a handoff and drops fields its handler type does
+// not use.
+func NormalizeHandoff(s Step) Step {
+ s.StatusKey = strings.TrimSpace(s.StatusKey)
+ s.Handler.Type = strings.TrimSpace(s.Handler.Type)
+ s.Handler.ID = strings.TrimSpace(s.Handler.ID)
+ if s.Handler.Type == "" {
+ s.Handler.Type = HandlerNone
+ }
+ switch s.Handler.Type {
+ case HandlerAgent, HandlerSquad, HandlerMember:
+ default:
+ // Only the concrete handler types carry an id; a stale one left
+ // by a type switch in the form would otherwise be stored.
+ s.Handler.ID = ""
+ }
+ s.Instructions = strings.TrimSpace(s.Instructions)
+ if s.Handler.Type == HandlerNone {
+ s.Instructions = ""
+ }
+ s.NextStatusKey = strings.TrimSpace(s.NextStatusKey)
+ s.BackStatusKey = strings.TrimSpace(s.BackStatusKey)
+ return s
+}
+
+// ValidateHandoff checks one normalized handoff against its workflow.
+// Handler ids are checked by the caller, which owns the workspace lookups.
+func ValidateHandoff(s Step, def Definition) error {
+ if !def.Has(s.StatusKey) {
+ return invalid("status %q is not part of this workflow", s.StatusKey)
+ }
+ switch s.Handler.Type {
+ case HandlerNone, HandlerProjectLead:
+ case HandlerAgent, HandlerMember:
+ if s.Handler.ID == "" {
+ return invalid("choose a %s to hand off to", s.Handler.Type)
+ }
+ case HandlerSquad, HandlerCreator:
+ // A squad routes work itself, so a handoff to one would compete with
+ // its own assignment. (MUL-7420)
+ return invalid("hand off to an agent, a member or the project lead")
+ default:
+ return invalid("unknown handler type %q", s.Handler.Type)
+ }
+ if s.HandsOff() && !AcceptsHandoff(s.StatusKey) {
+ return invalid("issues entering %q cannot be handed off", s.StatusKey)
+ }
+ if utf8.RuneCountInString(s.Instructions) > MaxInstructionsRunes {
+ return invalid("instructions must be at most %d characters", MaxInstructionsRunes)
+ }
+ for _, ref := range []string{s.NextStatusKey, s.BackStatusKey} {
+ if ref != "" && (ref == s.StatusKey || !def.Has(ref)) {
+ return invalid("%q is not another status of this workflow", ref)
+ }
+ }
+ return nil
+}
+
+// Querier is the read surface workflow resolution needs.
+type Querier interface {
+ GetIssueWorkflow(ctx context.Context, arg db.GetIssueWorkflowParams) (db.IssueWorkflow, error)
+ GetDefaultIssueWorkflow(ctx context.Context, workspaceID pgtype.UUID) (db.IssueWorkflow, error)
+ GetProjectInWorkspace(ctx context.Context, arg db.GetProjectInWorkspaceParams) (db.Project, error)
+}
+
+// DefaultFor loads the workspace Default workflow, or the built-in one when
+// the workspace has not stored its own yet.
+func DefaultFor(ctx context.Context, q Querier, workspaceID pgtype.UUID) (Definition, error) {
+ row, err := q.GetDefaultIssueWorkflow(ctx, workspaceID)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return Definition{Name: DefaultName, IsDefault: true, Steps: stepsFor(BuiltInDefaultKeys())}, nil
+ }
+ return Definition{}, err
+ }
+ return Decode(row)
+}
+
+// ForProject loads the workflow a project uses. def is nil only for an issue
+// outside any project.
+func ForProject(ctx context.Context, q Querier, workspaceID, projectID pgtype.UUID) (*Definition, db.Project, error) {
+ if !projectID.Valid {
+ return nil, db.Project{}, nil
+ }
+ project, err := q.GetProjectInWorkspace(ctx, db.GetProjectInWorkspaceParams{ID: projectID, WorkspaceID: workspaceID})
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, db.Project{}, nil
+ }
+ return nil, db.Project{}, err
+ }
+ def, err := ForProjectRow(ctx, q, project)
+ return def, project, err
+}
+
+// ForProjectRow loads the workflow of an already-loaded project. A dangling
+// workflow reference falls back to Default.
+func ForProjectRow(ctx context.Context, q Querier, project db.Project) (*Definition, error) {
+ var def Definition
+ var err error
+ if project.WorkflowID.Valid {
+ var row db.IssueWorkflow
+ row, err = q.GetIssueWorkflow(ctx, db.GetIssueWorkflowParams{ID: project.WorkflowID, WorkspaceID: project.WorkspaceID})
+ if err == nil {
+ def, err = Decode(row)
+ return &def, err
+ }
+ if !errors.Is(err, pgx.ErrNoRows) {
+ return nil, err
+ }
+ }
+ def, err = DefaultFor(ctx, q, project.WorkspaceID)
+ if err != nil {
+ return nil, err
+ }
+ return &def, nil
+}
+
+// ResolveHandler turns a step's handler into a concrete assignee for one
+// issue. ok is false when the step does not hand off, or when a relative
+// handler (project lead, creator) has nobody to resolve to.
+func ResolveHandler(step Step, project db.Project, issueCreatorType string, issueCreatorID pgtype.UUID) (assigneeType string, assigneeID pgtype.UUID, ok bool) {
+ switch step.Handler.Type {
+ case HandlerAgent, HandlerSquad, HandlerMember:
+ var id pgtype.UUID
+ if err := id.Scan(step.Handler.ID); err != nil || !id.Valid {
+ return "", pgtype.UUID{}, false
+ }
+ return step.Handler.Type, id, true
+ case HandlerProjectLead:
+ if !project.LeadType.Valid || !project.LeadID.Valid {
+ return "", pgtype.UUID{}, false
+ }
+ return project.LeadType.String, project.LeadID, true
+ case HandlerCreator:
+ if issueCreatorType == "" || !issueCreatorID.Valid {
+ return "", pgtype.UUID{}, false
+ }
+ return issueCreatorType, issueCreatorID, true
+ }
+ return "", pgtype.UUID{}, false
+}
+
+// MoveTarget picks the status an issue keeps when it moves into a project
+// using def: its current status when the workflow lists it, otherwise the
+// first step of the same lifecycle category, otherwise the start status.
+func MoveTarget(def Definition, currentKey string, categoryOf func(string) string) string {
+ if def.Has(currentKey) {
+ return currentKey
+ }
+ category := categoryOf(currentKey)
+ for _, s := range def.Steps {
+ if category != "" && categoryOf(s.StatusKey) == category {
+ return s.StatusKey
+ }
+ }
+ return StartStatus
+}
+
+// NotInWorkflowError explains a status write the project's workflow rejects.
+// Its message lists the allowed keys because agents read it verbatim.
+type NotInWorkflowError struct {
+ StatusKey string
+ WorkflowName string
+ Allowed []string
+}
+
+func (e *NotInWorkflowError) Error() string {
+ return fmt.Sprintf("status %q is not part of this project's workflow %q; use one of: %s",
+ e.StatusKey, e.WorkflowName, strings.Join(e.Allowed, ", "))
+}
+
+// StepMovedError refuses an agent's status change on an issue that has left
+// the step the agent's run works on: someone else moved it while the run
+// worked, so the run's decision no longer applies, and applying it would undo
+// that move.
+type StepMovedError struct {
+ IssueIdentifier string
+ // Step is the status the run works on; Current is where the issue is now.
+ Step, StepName string
+ Current, CurrentName string
+ // MovedBy names whoever last changed the status; empty when unknown.
+ MovedBy string
+}
+
+func (e *StepMovedError) Error() string {
+ mover := e.MovedBy
+ if mover == "" {
+ mover = "someone else"
+ }
+ return fmt.Sprintf("%s is no longer at %s: %s moved it to %s while this run was working, so this status change was not applied. "+
+ "Do not change the status again in this run; leave a comment if something still needs attention.",
+ e.IssueIdentifier, statusLabel(e.StepName, e.Step), mover, statusLabel(e.CurrentName, e.Current))
+}
+
+// statusLabel names a status for an agent: its display name with the key the
+// CLI takes, or the bare key when the two are the same.
+func statusLabel(name, key string) string {
+ if name == "" || name == key {
+ return fmt.Sprintf("%q", key)
+ }
+ return fmt.Sprintf("%q (%s)", name, key)
+}
+
+// CheckStatus rejects a status a named workflow does not list. Default
+// accepts every status, so issues already on statuses it no longer lists
+// keep working.
+func CheckStatus(def *Definition, key string) error {
+ if def == nil || def.IsDefault || def.Has(key) {
+ return nil
+ }
+ return &NotInWorkflowError{StatusKey: key, WorkflowName: def.Name, Allowed: def.StatusKeys()}
+}
+
+// BriefInput carries what the handoff brief names.
+type BriefInput struct {
+ Workflow Definition
+ ProjectName string
+ StatusKey string
+ IssueIdentifier string
+ // StatusName resolves a catalog key to its display name.
+ StatusName func(key string) string
+ // HandlerName describes who a step hands off to, e.g. "Sentinel" or
+ // "Lin (project lead)". Empty means the step does not hand off.
+ HandlerName func(step Step) string
+}
+
+// Brief renders the handoff note an agent receives when an
+// issue enters a step that hands off to it. The runtime brief's built-in
+// status rules (for example in_review on delivery) name statuses this project
+// may not use, so the note spells out the workflow's own statuses and the
+// exact commands for the next move.
+func Brief(in BriefInput) string {
+ step, _ := in.Workflow.Step(in.StatusKey)
+ name := func(key string) string {
+ if in.StatusName == nil {
+ return key
+ }
+ if n := in.StatusName(key); n != "" {
+ return n
+ }
+ return key
+ }
+ var b strings.Builder
+ title := in.Workflow.Name
+ if in.ProjectName != "" {
+ title = fmt.Sprintf("%s (%s)", title, in.ProjectName)
+ }
+ fmt.Fprintf(&b, "This project's workflow — %s\n", title)
+ fmt.Fprintf(&b, "You are handling the %q step of %s. You were assigned because the issue entered this status.\n",
+ name(in.StatusKey), in.IssueIdentifier)
+ if step.Instructions != "" {
+ b.WriteString("\nStep instructions:\n")
+ for _, line := range strings.Split(step.Instructions, "\n") {
+ b.WriteString("> ")
+ b.WriteString(line)
+ b.WriteString("\n")
+ }
+ }
+ b.WriteString("\nStatuses in this workflow (use only these keys):\n")
+ for _, s := range in.Workflow.Steps {
+ // Built-in statuses have no stored name; their key reads on its own.
+ fmt.Fprintf(&b, "- `%s`", s.StatusKey)
+ if n := name(s.StatusKey); n != s.StatusKey {
+ fmt.Fprintf(&b, " %s", n)
+ }
+ if in.HandlerName != nil {
+ if who := in.HandlerName(s); who != "" {
+ fmt.Fprintf(&b, " — hands off to %s", who)
+ }
+ }
+ if s.StatusKey == in.StatusKey {
+ b.WriteString(" ← current")
+ }
+ b.WriteString("\n")
+ }
+ b.WriteString("\nHand off by changing the status:\n")
+ if next := in.Workflow.NextStatus(in.StatusKey); next != "" {
+ fmt.Fprintf(&b, "Step done → multica issue status %s %s\n", in.IssueIdentifier, next)
+ }
+ if step.BackStatusKey != "" {
+ fmt.Fprintf(&b, "Needs changes → multica issue status %s %s\n", in.IssueIdentifier, step.BackStatusKey)
+ }
+ switch {
+ case in.Workflow.Has(issuestatus.Blocked):
+ fmt.Fprintf(&b, "Can't proceed → multica issue status %s blocked, then comment why\n", in.IssueIdentifier)
+ case step.BackStatusKey != "":
+ b.WriteString("Can't proceed → this workflow has no blocked status: comment why, then use the \"Needs changes\" command above\n")
+ default:
+ b.WriteString("Can't proceed → this workflow has no blocked status: comment why and leave the status as it is\n")
+ }
+ b.WriteString("The system does not advance the status when your run ends. Where your runtime instructions name a status this list does not include, use the commands above instead.\n")
+ b.WriteString("Each step's handler gets a run when the issue enters that step, so do not use `multica issue wakeup` to watch this issue's status, assignee or runs; use wakeups only to wait for a time or for something outside this issue.\n")
+ return b.String()
+}
diff --git a/server/internal/issueworkflow/issueworkflow_test.go b/server/internal/issueworkflow/issueworkflow_test.go
new file mode 100644
index 0000000000..772a963aa4
--- /dev/null
+++ b/server/internal/issueworkflow/issueworkflow_test.go
@@ -0,0 +1,301 @@
+package issueworkflow
+
+import (
+ "errors"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+const testAgentID = "0f0e0d0c-0b0a-4909-8807-060504030201"
+
+func testCatalog() map[string]CatalogEntry {
+ return map[string]CatalogEntry{
+ "backlog": {Key: "backlog", Name: "Backlog", Category: "unstarted"},
+ "todo": {Key: "todo", Name: "Todo", Category: "unstarted"},
+ "implement": {Key: "implement", Name: "Implement", Category: "started"},
+ "code_review": {Key: "code_review", Name: "Code review", Category: "started"},
+ "blocked": {Key: "blocked", Name: "Blocked", Category: "started"},
+ "done": {Key: "done", Name: "Done", Category: "done"},
+ "cancelled": {Key: "cancelled", Name: "Cancelled", Category: "closed"},
+ "retired": {Key: "retired", Name: "Retired", Category: "started", Archived: true},
+ }
+}
+
+// withHandoffs replaces the steps of def that handoffs name.
+func withHandoffs(def Definition, handoffs []Step) Definition {
+ for _, h := range handoffs {
+ for i, s := range def.Steps {
+ if s.StatusKey == h.StatusKey {
+ def.Steps[i] = h
+ }
+ }
+ }
+ return def
+}
+
+func devDefinition() Definition {
+ def := Definition{Name: "Delivery", Steps: stepsFor(ArrangeKeys([]string{"backlog", "implement", "code_review", "blocked"}))}
+ return withHandoffs(def, []Step{
+ {StatusKey: "implement", Handler: Handler{Type: HandlerAgent, ID: testAgentID}, Instructions: "Implement it."},
+ {StatusKey: "code_review", Handler: Handler{Type: HandlerProjectLead}, NextStatusKey: "done", BackStatusKey: "implement"},
+ })
+}
+
+func TestNormalizePlacesFixedStatusesAroundOwnSteps(t *testing.T) {
+ name, _, steps := Normalize(" Delivery ", "", stepsFor([]string{"done", " implement ", "blocked", "todo", "code_review", "backlog"}))
+ if name != "Delivery" {
+ t.Fatalf("name was not trimmed: %q", name)
+ }
+ want := []string{"backlog", "todo", "implement", "code_review", "blocked", "done", "cancelled"}
+ if got := keysOf(steps); !reflect.DeepEqual(got, want) {
+ t.Fatalf("keys = %v, want %v", got, want)
+ }
+ // Backlog and blocked are optional; the required statuses are added.
+ _, _, steps = Normalize("Lean", "", stepsFor([]string{"implement"}))
+ if got := keysOf(steps); !reflect.DeepEqual(got, []string{"todo", "implement", "done", "cancelled"}) {
+ t.Fatalf("lean keys = %v", got)
+ }
+ if got := BuiltInDefaultKeys(); !reflect.DeepEqual(got, []string{"backlog", "todo", "in_progress", "in_review", "blocked", "done", "cancelled"}) {
+ t.Fatalf("built-in Default = %v", got)
+ }
+}
+
+func TestValidateRejectsBrokenWorkflows(t *testing.T) {
+ cases := map[string]struct {
+ name string
+ middle []string
+ isDefault bool
+ want string
+ }{
+ "empty name": {name: "", want: "name"},
+ "reserved name": {name: "default", want: "reserved"},
+ "unknown status": {name: "x", middle: []string{"nope"}, want: "does not exist"},
+ "archived status": {name: "x", middle: []string{"retired"}, want: "archived"},
+ "duplicate status": {name: "x", middle: []string{"implement", "implement"}, want: "more than once"},
+ }
+ broken := stepsFor([]string{"implement"})
+ broken[0].Handler = Handler{Type: HandlerSquad, ID: testAgentID}
+ name, desc, steps := Normalize("x", "", broken)
+ if err := Validate(name, desc, steps, false, testCatalog()); err == nil || !strings.Contains(err.Error(), "hand off to an agent") {
+ t.Fatalf("Validate must check handoffs, got %v", err)
+ }
+ for label, tc := range cases {
+ t.Run(label, func(t *testing.T) {
+ name, desc, steps := Normalize(tc.name, "", stepsFor(tc.middle))
+ err := Validate(name, desc, steps, tc.isDefault, testCatalog())
+ var verr *ValidationError
+ if !errors.As(err, &verr) {
+ t.Fatalf("Validate = %v, want a ValidationError", err)
+ }
+ if !strings.Contains(err.Error(), tc.want) {
+ t.Fatalf("error %q does not mention %q", err, tc.want)
+ }
+ })
+ }
+ name, desc, steps = Normalize(DefaultName, "", stepsFor([]string{"implement"}))
+ if err := Validate(name, desc, steps, true, testCatalog()); err != nil {
+ t.Fatalf("Default keeps its reserved name: %v", err)
+ }
+}
+
+func TestValidateHandoff(t *testing.T) {
+ def := devDefinition()
+ cases := map[string]struct {
+ step Step
+ want string
+ }{
+ "not a column": {step: Step{StatusKey: "nope", Handler: Handler{Type: HandlerProjectLead}}, want: "not part"},
+ "needs an id": {step: Step{StatusKey: "implement", Handler: Handler{Type: HandlerAgent}}, want: "choose a agent"},
+ "unknown handler": {step: Step{StatusKey: "implement", Handler: Handler{Type: "robot"}}, want: "unknown handler"},
+ "backlog parks": {step: Step{StatusKey: "backlog", Handler: Handler{Type: HandlerProjectLead}}, want: "cannot be handed off"},
+ "done finishes": {step: Step{StatusKey: "done", Handler: Handler{Type: HandlerProjectLead}}, want: "cannot be handed off"},
+ "next outside flow": {step: Step{StatusKey: "implement", Handler: Handler{Type: HandlerProjectLead}, NextStatusKey: "in_review"}, want: "not another status"},
+ "next is itself": {step: Step{StatusKey: "implement", Handler: Handler{Type: HandlerProjectLead}, NextStatusKey: "implement"}, want: "not another status"},
+ }
+ for label, tc := range cases {
+ t.Run(label, func(t *testing.T) {
+ err := ValidateHandoff(NormalizeHandoff(tc.step), def)
+ if err == nil || !strings.Contains(err.Error(), tc.want) {
+ t.Fatalf("ValidateHandoff = %v, want it to mention %q", err, tc.want)
+ }
+ })
+ }
+ if err := ValidateHandoff(NormalizeHandoff(Step{StatusKey: "todo", Handler: Handler{Type: HandlerProjectLead}}), def); err != nil {
+ t.Fatalf("todo may hand off: %v", err)
+ }
+}
+
+func TestNormalizeHandoffDropsStaleHandlerData(t *testing.T) {
+ lead := NormalizeHandoff(Step{StatusKey: "a", Handler: Handler{Type: HandlerProjectLead, ID: testAgentID}, Instructions: " keep "})
+ if lead.Handler.ID != "" || lead.Instructions != "keep" {
+ t.Fatalf("project-lead handoff = %+v, want no id and trimmed instructions", lead)
+ }
+ none := NormalizeHandoff(Step{StatusKey: "b", Handler: Handler{Type: HandlerNone, ID: testAgentID}, Instructions: "drop"})
+ if none.Handler.ID != "" || none.Instructions != "" {
+ t.Fatalf("no-handoff = %+v, want no id and no instructions", none)
+ }
+ if empty := NormalizeHandoff(Step{StatusKey: "c"}); empty.Handler.Type != HandlerNone {
+ t.Fatalf("empty handler type = %q, want none", empty.Handler.Type)
+ }
+}
+
+func TestEncodeStepsRoundTripsHandoffs(t *testing.T) {
+ def := devDefinition()
+ raw, err := EncodeSteps(def.Steps)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(raw), `"status_key":"todo","handler"`) {
+ t.Fatalf("a step without a handoff should store only its key: %s", raw)
+ }
+ got, err := DecodeSteps(raw)
+ if err != nil || !reflect.DeepEqual(got, def.Steps) {
+ t.Fatalf("DecodeSteps = %+v, %v; want %+v", got, err, def.Steps)
+ }
+}
+
+func TestNextStatusFallsBackToTheNextColumn(t *testing.T) {
+ def := devDefinition()
+ if got := def.NextStatus("implement"); got != "code_review" {
+ t.Fatalf("implement next = %q, want the next column", got)
+ }
+ if got := def.NextStatus("code_review"); got != "done" {
+ t.Fatalf("code_review next = %q, want its own choice", got)
+ }
+ // The column after the last own step is blocked, which is skipped.
+ plain := Definition{Steps: stepsFor(ArrangeKeys([]string{"implement", "blocked"}))}
+ if got := plain.NextStatus("implement"); got != "done" {
+ t.Fatalf("last step next = %q, want done", got)
+ }
+}
+
+func TestResolveHandler(t *testing.T) {
+ var lead pgtype.UUID
+ _ = lead.Scan(testAgentID)
+ project := db.Project{LeadType: pgtype.Text{String: "member", Valid: true}, LeadID: lead}
+ creator := lead
+
+ def := devDefinition()
+ implement, _ := def.Step("implement")
+ review, _ := def.Step("code_review")
+ todo, _ := def.Step("todo")
+ if typ, id, ok := ResolveHandler(implement, project, "member", creator); !ok || typ != "agent" || id != lead {
+ t.Fatalf("agent handler = %s %v %v", typ, id, ok)
+ }
+ if typ, _, ok := ResolveHandler(review, project, "member", creator); !ok || typ != "member" {
+ t.Fatalf("project lead handler = %s %v, want member", typ, ok)
+ }
+ if _, _, ok := ResolveHandler(review, db.Project{}, "member", creator); ok {
+ t.Fatal("a project without a lead must not resolve a handoff")
+ }
+ if _, _, ok := ResolveHandler(Step{StatusKey: "x", Handler: Handler{Type: HandlerCreator}}, project, "agent", creator); !ok {
+ t.Fatal("creator handler should resolve to the issue creator")
+ }
+ if _, _, ok := ResolveHandler(todo, project, "member", creator); ok {
+ t.Fatal("a column without a handoff must not resolve one")
+ }
+}
+
+func TestMoveTargetPrefersSameStatusThenCategory(t *testing.T) {
+ def := devDefinition()
+ category := func(key string) string {
+ if key == "in_review" {
+ return "started"
+ }
+ if key == "elsewhere" {
+ return "unknown"
+ }
+ return testCatalog()[key].Category
+ }
+ if got := MoveTarget(def, "done", category); got != "done" {
+ t.Fatalf("listed status moved to %q", got)
+ }
+ if got := MoveTarget(def, "in_review", category); got != "implement" {
+ t.Fatalf("in_review moved to %q, want the first started step", got)
+ }
+ if got := MoveTarget(def, "elsewhere", category); got != StartStatus {
+ t.Fatalf("a category the workflow lacks moved to %q, want todo", got)
+ }
+}
+
+func TestCheckStatusListsAllowedKeys(t *testing.T) {
+ def := devDefinition()
+ if err := CheckStatus(nil, "anything"); err != nil {
+ t.Fatalf("an issue outside projects accepts any status, got %v", err)
+ }
+ if err := CheckStatus(&Definition{Name: DefaultName, IsDefault: true, Steps: stepsFor(BuiltInDefaultKeys())}, "code_review"); err != nil {
+ t.Fatalf("Default accepts any status, got %v", err)
+ }
+ err := CheckStatus(&def, "in_review")
+ var notIn *NotInWorkflowError
+ if !errors.As(err, &notIn) {
+ t.Fatalf("CheckStatus = %v, want NotInWorkflowError", err)
+ }
+ if !strings.Contains(err.Error(), "backlog, todo, implement, code_review, blocked, done, cancelled") {
+ t.Fatalf("error %q should list the workflow's keys for agents", err)
+ }
+}
+
+func TestBriefNamesStepCommandsAndHandlers(t *testing.T) {
+ brief := Brief(BriefInput{
+ Workflow: devDefinition(),
+ ProjectName: "Payments",
+ StatusKey: "code_review",
+ IssueIdentifier: "MUL-7",
+ StatusName: func(key string) string { return testCatalog()[key].Name },
+ HandlerName: func(step Step) string {
+ if step.Handler.Type == HandlerAgent {
+ return "Forge"
+ }
+ if step.Handler.Type == HandlerProjectLead {
+ return "Lin (project lead)"
+ }
+ return ""
+ },
+ })
+ for _, want := range []string{
+ "This project's workflow — Delivery (Payments)\n",
+ `You are handling the "Code review" step of MUL-7.`,
+ "- `implement` Implement — hands off to Forge\n",
+ "- `code_review` Code review — hands off to Lin (project lead) ← current\n",
+ "- `done` Done\n",
+ "Step done → multica issue status MUL-7 done\n",
+ "Needs changes → multica issue status MUL-7 implement\n",
+ "Can't proceed → multica issue status MUL-7 blocked",
+ } {
+ if !strings.Contains(brief, want) {
+ t.Fatalf("brief is missing %q:\n%s", want, brief)
+ }
+ }
+}
+
+func TestBriefPrintsBuiltInKeysOnce(t *testing.T) {
+ def := withHandoffs(Definition{Name: DefaultName, IsDefault: true, Steps: stepsFor(BuiltInDefaultKeys())},
+ []Step{{StatusKey: "in_review", Handler: Handler{Type: HandlerProjectLead}}})
+ brief := Brief(BriefInput{
+ Workflow: def,
+ StatusKey: "in_review",
+ IssueIdentifier: "MUL-1",
+ // Built-ins resolve to no stored name.
+ StatusName: func(string) string { return "" },
+ })
+ if !strings.Contains(brief, "- `todo`\n") || strings.Contains(brief, "`todo` todo") {
+ t.Fatalf("a built-in step should print its key once:\n%s", brief)
+ }
+ if !strings.Contains(brief, "Step done → multica issue status MUL-1 done\n") {
+ t.Fatalf("the last own step should suggest done:\n%s", brief)
+ }
+}
+
+func TestBriefWithoutBlockedPointsAtTheBackStatus(t *testing.T) {
+ def := withHandoffs(Definition{Name: "Lean", Steps: stepsFor(ArrangeKeys([]string{"implement", "code_review"}))},
+ []Step{{StatusKey: "code_review", Handler: Handler{Type: HandlerProjectLead}, BackStatusKey: "implement"}})
+ brief := Brief(BriefInput{Workflow: def, StatusKey: "code_review", IssueIdentifier: "MUL-2"})
+ if strings.Contains(brief, "MUL-2 blocked") || !strings.Contains(brief, "no blocked status") || !strings.Contains(brief, "Needs changes") {
+ t.Fatalf("a workflow without blocked should not suggest it:\n%s", brief)
+ }
+}
diff --git a/server/internal/service/issue.go b/server/internal/service/issue.go
index c7a7085016..1a0369c9f6 100644
--- a/server/internal/service/issue.go
+++ b/server/internal/service/issue.go
@@ -19,6 +19,7 @@ import (
"github.com/multica-ai/multica/server/internal/issueposition"
"github.com/multica-ai/multica/server/internal/issueproperty"
"github.com/multica-ai/multica/server/internal/issuestatus"
+ "github.com/multica-ai/multica/server/internal/issueworkflow"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -135,6 +136,13 @@ type IssueCreateOpts struct {
// still resolving, then promotes the returned task after attachment binding.
// Zero preserves the ordinary immediate enqueue path.
AssignedAgentRunFireAt time.Time
+
+ // HandoffNote, when set, renders the note that rides the run the create
+ // starts for its assignee. The HTTP handler sets it when a project
+ // workflow's starting step hands the new issue off, so the handler's run
+ // receives the step's instructions. It takes the created issue because the
+ // note names the issue's identifier. (MUL-7420)
+ HandoffNote func(issue db.Issue) string
}
// ErrActiveDuplicate signals that the duplicate guard found an active
@@ -272,6 +280,18 @@ func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts Iss
}
}
+ // Project workflow (MUL-7420): an issue created in a project whose named
+ // workflow does not list the requested status starts on todo instead.
+ // The HTTP create path already rejects an explicit status outside the
+ // workflow; this keeps the other creators (channels, captured comments)
+ // inside it too. Resolved before the custom-status guard below so that
+ // guard checks the status actually written.
+ if def, err := s.createWorkflow(ctx, qtx, p); err != nil {
+ return IssueCreateResult{}, err
+ } else if def != nil && !def.IsDefault && !def.Has(p.Status) {
+ p.Status = issueworkflow.StartStatus
+ }
+
// A create landing on a CUSTOM status takes the shared catalog lock AND
// re-resolves the status inside this transaction. The caller validated the
// status before the transaction opened, which is early enough to return a
@@ -535,7 +555,11 @@ func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts Iss
s.publishIssueCreated(issue, attachments, labels, p.CreatorType, actorID, opts)
s.captureCreatedAnalytics(issue, p.CreatorType, actorID, opts)
if opts.AssignedAgentRunFireAt.IsZero() {
- assignedTaskID = s.maybeEnqueueOnAssign(ctx, issue, p.CreatorType, actorID, opts.AssignedAgentRunFireAt)
+ handoffNote := ""
+ if opts.HandoffNote != nil {
+ handoffNote = opts.HandoffNote(issue)
+ }
+ assignedTaskID = s.maybeEnqueueOnAssign(ctx, issue, p.CreatorType, actorID, opts.AssignedAgentRunFireAt, handoffNote)
}
return IssueCreateResult{Issue: issue, Attachments: attachments, Labels: labels, AssignedTaskID: assignedTaskID}, nil
@@ -825,7 +849,23 @@ func classifyOrigin(issue db.Issue, opts IssueCreateOpts) (source, taskID, autop
}
}
-func (s *IssueService) maybeEnqueueOnAssign(ctx context.Context, issue db.Issue, creatorType, actorID string, agentRunFireAt time.Time) pgtype.UUID {
+// createWorkflow resolves the workflow of the project a new issue lands in:
+// its own project, or its parent's when it names none.
+func (s *IssueService) createWorkflow(ctx context.Context, qtx *db.Queries, p IssueCreateParams) (*issueworkflow.Definition, error) {
+ projectID := p.ProjectID
+ if !projectID.Valid && p.ParentIssueID.Valid {
+ parent, err := qtx.GetIssueInWorkspace(ctx, db.GetIssueInWorkspaceParams{ID: p.ParentIssueID, WorkspaceID: p.WorkspaceID})
+ if err != nil {
+ // The parent check below reports a missing parent.
+ return nil, nil
+ }
+ projectID = parent.ProjectID
+ }
+ def, _, err := issueworkflow.ForProject(ctx, qtx, p.WorkspaceID, projectID)
+ return def, err
+}
+
+func (s *IssueService) maybeEnqueueOnAssign(ctx context.Context, issue db.Issue, creatorType, actorID string, agentRunFireAt time.Time, handoffNote string) pgtype.UUID {
if !issue.AssigneeType.Valid || !issue.AssigneeID.Valid {
return pgtype.UUID{}
}
@@ -849,7 +889,9 @@ func (s *IssueService) maybeEnqueueOnAssign(ctx context.Context, issue db.Issue,
if admitted {
var task db.AgentTaskQueue
var err error
- if agentRunFireAt.IsZero() {
+ if agentRunFireAt.IsZero() && handoffNote != "" {
+ task, err = s.TaskService.EnqueueTaskForIssueWithHandoff(ctx, issue, handoffNote, pgtype.UUID{})
+ } else if agentRunFireAt.IsZero() {
task, err = s.TaskService.EnqueueTaskForIssue(ctx, issue)
} else {
task, err = s.TaskService.EnqueueDeferredChannelIssueTask(ctx, issue, agentRunFireAt)
@@ -863,11 +905,42 @@ func (s *IssueService) maybeEnqueueOnAssign(ctx context.Context, issue db.Issue,
}
}
if s.shouldEnqueueSquadLeaderOnAssign(ctx, issue) {
- s.enqueueSquadLeaderTask(ctx, issue, pgtype.UUID{}, creatorType, actorID)
+ if handoffNote != "" {
+ s.enqueueSquadLeaderHandoffTask(ctx, issue, handoffNote)
+ } else {
+ s.enqueueSquadLeaderTask(ctx, issue, pgtype.UUID{}, creatorType, actorID)
+ }
}
return pgtype.UUID{}
}
+// enqueueSquadLeaderHandoffTask starts a squad leader's run carrying a
+// workflow step's handoff note, with the same pending-task dedup as
+// enqueueSquadLeaderTask. (MUL-7420)
+func (s *IssueService) enqueueSquadLeaderHandoffTask(ctx context.Context, issue db.Issue, handoffNote string) {
+ squad, err := s.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{
+ ID: issue.AssigneeID,
+ WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil {
+ return
+ }
+ hasPending, err := s.Queries.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{
+ IssueID: issue.ID,
+ AgentID: squad.LeaderID,
+ HeadSha: headShaText(s.TaskService.ResolveIssueReviewSHA(ctx, issue.ID)),
+ })
+ if err != nil || hasPending {
+ return
+ }
+ if _, err := s.TaskService.EnqueueTaskForSquadLeaderWithHandoff(ctx, issue, squad.LeaderID, squad.ID, handoffNote, pgtype.UUID{}); err != nil {
+ slog.Warn("enqueue squad leader handoff task on create failed",
+ "issue_id", util.UUIDToString(issue.ID),
+ "squad_id", util.UUIDToString(squad.ID),
+ "error", err)
+ }
+}
+
// shouldEnqueueAgentTaskWithQueries returns true when an issue create should
// trigger the assigned agent. Backlog issues are skipped — backlog acts as a
// parking lot for pre-assigning without immediate execution. The assignment
diff --git a/server/internal/service/issue_trigger.go b/server/internal/service/issue_trigger.go
index 582c1af29d..902748b464 100644
--- a/server/internal/service/issue_trigger.go
+++ b/server/internal/service/issue_trigger.go
@@ -55,6 +55,11 @@ type IssueTriggerInput struct {
IsCreate bool
AssigneeChanged bool
StatusChanged bool
+ // EnteredHandoffStep marks a write that moved the issue into a project
+ // workflow column with a handler (MUL-7420). The step is new work even
+ // when its handler is the agent whose run made the move, so the
+ // self-assignment suppression does not apply.
+ EnteredHandoffStep bool
}
// IssueRunTrigger is the resolved decision shared by preview and the write
@@ -151,11 +156,13 @@ func (s *IssueService) WillEnqueueRun(ctx context.Context, in IssueTriggerInput,
if !canAccess(agent) {
return IssueRunTrigger{}, false
}
- if source == RunSourceAssign && !in.IsCreate && probe.SuppressActiveSelfAssignment != nil &&
+ if source == RunSourceAssign && !in.IsCreate && !in.EnteredHandoffStep && probe.SuppressActiveSelfAssignment != nil &&
probe.SuppressActiveSelfAssignment(issue.AssigneeID) {
return IssueRunTrigger{}, false
}
- if source == RunSourceStatus && s.hasPendingRun(ctx, issue.ID, issue.AssigneeID) {
+ // A step entered under the agent's own run queues behind it; one
+ // already queued covers the new step too.
+ if (source == RunSourceStatus || in.EnteredHandoffStep) && s.hasPendingRun(ctx, issue.ID, issue.AssigneeID) {
return IssueRunTrigger{}, false
}
return IssueRunTrigger{
diff --git a/server/internal/service/issue_wakeup_workflow_test.go b/server/internal/service/issue_wakeup_workflow_test.go
new file mode 100644
index 0000000000..d4fe476602
--- /dev/null
+++ b/server/internal/service/issue_wakeup_workflow_test.go
@@ -0,0 +1,79 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// Project workflows × wakeups (MUL-7420).
+
+// A wakeup continues the run that registered it, so its run keeps that run's
+// workflow step: when someone else moved the issue in between, the wakeup's
+// status changes are refused like the registering run's would be. A wakeup a
+// member registered has no such run and starts from the issue's status.
+func TestWakeupRunKeepsTheRegisteringRunsStep(t *testing.T) {
+ f, s, issue, agent := wakeFixture(t)
+ ctx := context.Background()
+ source := f.Task(t, agent, testutil.Cols{
+ "issue_id": issue, "status": "completed", "workflow_step": "in_progress",
+ "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')"),
+ })
+ fire := func(w db.IssueWakeup) db.AgentTaskQueue {
+ t.Helper()
+ f.Exec(t, "UPDATE issue_wakeup SET next_fire_at=now()-interval '1 second' WHERE id=$1", w.ID)
+ wakeDispatch(t, s, w)
+ got, _ := f.q.GetIssueWakeup(ctx, db.GetIssueWakeupParams{ID: w.ID, WorkspaceID: w.WorkspaceID})
+ task, err := f.q.GetAgentTask(ctx, got.LastTaskID)
+ if err != nil {
+ t.Fatalf("wakeup did not queue a run: %v", err)
+ }
+ return task
+ }
+
+ fromRun, err := s.Create(ctx, issue, parseTestUUID(t, f.UserID), parseTestUUID(t, source),
+ WakeupInput{AgentID: agent, Kind: "at", AfterSeconds: 1, Instruction: "check CI, then hand to review"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ fromMember := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "at", AfterSeconds: 1, Instruction: "daily check"})
+ // Someone else parks the issue before either fires.
+ f.Exec(t, "UPDATE issue SET status='blocked' WHERE id=$1", issue)
+
+ if got := fire(fromRun).WorkflowStep; got.String != "in_progress" {
+ t.Fatalf("wakeup from a run works on %q, want the run's in_progress", got.String)
+ }
+ f.Exec(t, "UPDATE agent_task_queue SET status='cancelled',completed_at=now() WHERE issue_id=$1 AND status='queued'", issue)
+ if got := fire(fromMember).WorkflowStep; got.String != "blocked" {
+ t.Fatalf("wakeup from a member works on %q, want the issue's blocked", got.String)
+ }
+}
+
+// A retried workflow handoff keeps its brief, as a retried wakeup keeps its
+// prompt; a row from before workflow steps drops its retired note.
+func TestRetryKeepsWorkflowHandoffBrief(t *testing.T) {
+ f, _, issue, agent := wakeFixture(t)
+ ctx := context.Background()
+ runtime := testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')")
+ retry := func(cols testutil.Cols) db.AgentTaskQueue {
+ t.Helper()
+ cols["issue_id"], cols["status"], cols["runtime_id"] = issue, "failed", runtime
+ parent := f.Task(t, agent, cols)
+ child, err := f.q.CreateRetryTask(ctx, db.CreateRetryTaskParams{ID: parseTestUUID(t, parent)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.Cleanup(t, "DELETE FROM agent_task_queue WHERE id=$1", child.ID)
+ f.Exec(t, "UPDATE agent_task_queue SET status='cancelled' WHERE id=$1", child.ID)
+ return child
+ }
+ if got := retry(testutil.Cols{"handoff_note": "This project's workflow — Delivery", "workflow_step": "in_progress"}); got.HandoffNote != (pgtype.Text{String: "This project's workflow — Delivery", Valid: true}) || got.WorkflowStep.String != "in_progress" {
+ t.Fatalf("retry lost the handoff brief or step: %+v / %+v", got.HandoffNote, got.WorkflowStep)
+ }
+ if got := retry(testutil.Cols{"handoff_note": "retired assignment note"}); got.HandoffNote.Valid {
+ t.Fatalf("retry revived a retired note: %q", got.HandoffNote.String)
+ }
+}
diff --git a/server/migrations/573_issue_workflow.down.sql b/server/migrations/573_issue_workflow.down.sql
new file mode 100644
index 0000000000..8c64f028d0
--- /dev/null
+++ b/server/migrations/573_issue_workflow.down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS issue_workflow;
diff --git a/server/migrations/573_issue_workflow.up.sql b/server/migrations/573_issue_workflow.up.sql
new file mode 100644
index 0000000000..8b71be772b
--- /dev/null
+++ b/server/migrations/573_issue_workflow.up.sql
@@ -0,0 +1,29 @@
+-- Project workflows (MUL-7420).
+--
+-- A workflow is a named, workspace-level selection of statuses from the
+-- issue_status catalog, in the order a project's board shows them, with an
+-- optional handoff on each step: entering the step assigns the issue to the
+-- step's handler and starts its run with the step's instructions.
+--
+-- Statuses stay shared: steps reference issue_status by key, so issue.status
+-- keeps holding a catalog key and cross-project filters, sorting and saved
+-- views keep working unchanged. Projects opt in through project.workflow_id; a
+-- project without one keeps the whole catalog (the implicit Default workflow),
+-- so existing workspaces see no behavior change.
+--
+-- steps is JSONB because the editor saves a workflow as one unit and nothing
+-- queries individual steps across workflows. Status keys and handler ids are
+-- validated in application code; no foreign keys by project rule.
+--
+-- id is attached as the primary key in 575 from the index built CONCURRENTLY
+-- in 574 (repo convention, see 332-334).
+CREATE TABLE IF NOT EXISTS issue_workflow (
+ id UUID NOT NULL DEFAULT gen_random_uuid(),
+ workspace_id UUID NOT NULL,
+ name TEXT NOT NULL CHECK (char_length(name) BETWEEN 1 AND 64),
+ description TEXT NOT NULL DEFAULT '' CHECK (char_length(description) <= 256),
+ initial_status_key TEXT NOT NULL,
+ steps JSONB NOT NULL DEFAULT '[]'::jsonb CHECK (jsonb_typeof(steps) = 'array'),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/server/migrations/574_issue_workflow_pkey_index.down.sql b/server/migrations/574_issue_workflow_pkey_index.down.sql
new file mode 100644
index 0000000000..0d910d68a2
--- /dev/null
+++ b/server/migrations/574_issue_workflow_pkey_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS issue_workflow_pkey_uidx;
diff --git a/server/migrations/574_issue_workflow_pkey_index.up.sql b/server/migrations/574_issue_workflow_pkey_index.up.sql
new file mode 100644
index 0000000000..83bd9449ea
--- /dev/null
+++ b/server/migrations/574_issue_workflow_pkey_index.up.sql
@@ -0,0 +1,3 @@
+-- Backing index for issue_workflow's primary key, attached in 575.
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS issue_workflow_pkey_uidx
+ ON issue_workflow (id);
diff --git a/server/migrations/575_issue_workflow_primary_key.down.sql b/server/migrations/575_issue_workflow_primary_key.down.sql
new file mode 100644
index 0000000000..57ed8511af
--- /dev/null
+++ b/server/migrations/575_issue_workflow_primary_key.down.sql
@@ -0,0 +1,3 @@
+-- Dropping the constraint drops the index it took over, leaving 574's down
+-- direction a no-op via IF EXISTS.
+ALTER TABLE issue_workflow DROP CONSTRAINT IF EXISTS issue_workflow_pkey;
diff --git a/server/migrations/575_issue_workflow_primary_key.up.sql b/server/migrations/575_issue_workflow_primary_key.up.sql
new file mode 100644
index 0000000000..5817c79c88
--- /dev/null
+++ b/server/migrations/575_issue_workflow_primary_key.up.sql
@@ -0,0 +1,3 @@
+-- Attach the CONCURRENTLY-built unique index as the table's primary key.
+ALTER TABLE issue_workflow
+ ADD CONSTRAINT issue_workflow_pkey PRIMARY KEY USING INDEX issue_workflow_pkey_uidx;
diff --git a/server/migrations/576_issue_workflow_workspace_name_index.down.sql b/server/migrations/576_issue_workflow_workspace_name_index.down.sql
new file mode 100644
index 0000000000..0609abe70d
--- /dev/null
+++ b/server/migrations/576_issue_workflow_workspace_name_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_workflow_workspace_name;
diff --git a/server/migrations/576_issue_workflow_workspace_name_index.up.sql b/server/migrations/576_issue_workflow_workspace_name_index.up.sql
new file mode 100644
index 0000000000..5789adc53b
--- /dev/null
+++ b/server/migrations/576_issue_workflow_workspace_name_index.up.sql
@@ -0,0 +1,4 @@
+-- Workflow names are unique per workspace, case-insensitively, because the
+-- project picker and the CLI address a workflow by name.
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_workflow_workspace_name
+ ON issue_workflow (workspace_id, lower(name));
diff --git a/server/migrations/577_project_workflow_id.down.sql b/server/migrations/577_project_workflow_id.down.sql
new file mode 100644
index 0000000000..2f710bc7e8
--- /dev/null
+++ b/server/migrations/577_project_workflow_id.down.sql
@@ -0,0 +1 @@
+ALTER TABLE project DROP COLUMN IF EXISTS workflow_id;
diff --git a/server/migrations/577_project_workflow_id.up.sql b/server/migrations/577_project_workflow_id.up.sql
new file mode 100644
index 0000000000..441e10144d
--- /dev/null
+++ b/server/migrations/577_project_workflow_id.up.sql
@@ -0,0 +1,4 @@
+-- The workflow a project uses. NULL means the implicit Default workflow (the
+-- whole issue_status catalog, no handoffs), which is what every existing
+-- project keeps. Nullable with no default, so adding it is metadata-only.
+ALTER TABLE project ADD COLUMN IF NOT EXISTS workflow_id UUID;
diff --git a/server/migrations/578_agent_task_workflow_step.down.sql b/server/migrations/578_agent_task_workflow_step.down.sql
new file mode 100644
index 0000000000..c47aaac61f
--- /dev/null
+++ b/server/migrations/578_agent_task_workflow_step.down.sql
@@ -0,0 +1 @@
+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS workflow_step;
diff --git a/server/migrations/578_agent_task_workflow_step.up.sql b/server/migrations/578_agent_task_workflow_step.up.sql
new file mode 100644
index 0000000000..3407748ce5
--- /dev/null
+++ b/server/migrations/578_agent_task_workflow_step.up.sql
@@ -0,0 +1,10 @@
+-- The workflow step a run is working on (MUL-7420): the issue's status when
+-- the task was queued, moved along by the run's own status changes. When the
+-- issue has left that step — someone else moved it while the run worked — the
+-- run's status changes are refused instead of undoing that move.
+--
+-- Written by the task INSERTs from the issue row, and by the status-change
+-- path when the run moves the issue itself; nothing else writes it. NULL on
+-- rows written before this migration and on tasks without an issue, and NULL
+-- means "not checked", never "matches".
+ALTER TABLE agent_task_queue ADD COLUMN IF NOT EXISTS workflow_step TEXT;
diff --git a/server/migrations/579_wakeup_skip_handed_to_agent.down.sql b/server/migrations/579_wakeup_skip_handed_to_agent.down.sql
new file mode 100644
index 0000000000..05ebfdd46b
--- /dev/null
+++ b/server/migrations/579_wakeup_skip_handed_to_agent.down.sql
@@ -0,0 +1,50 @@
+-- Restore capture without the handed-to-agent skip (migration 532).
+CREATE OR REPLACE FUNCTION capture_issue_wakeup(p_issue uuid, p_type text, p_key text, p_agent uuid, p_task uuid, p_payload jsonb)
+RETURNS void LANGUAGE plpgsql AS $$
+DECLARE w issue_wakeup; owner_workspace uuid; evidence jsonb; violated_constraint text;
+BEGIN
+ IF NOT EXISTS (SELECT 1 FROM issue_wakeup WHERE issue_id=p_issue AND enabled AND kind='event' AND p_type=ANY(event_types)) THEN RETURN; END IF;
+ IF p_agent IS NULL AND current_setting('multica.actor_type',true)='agent' THEN
+ p_agent := NULLIF(current_setting('multica.actor_id',true),'')::uuid;
+ END IF;
+ SELECT i.workspace_id INTO owner_workspace FROM issue i
+ WHERE i.id=p_issue AND i.status NOT IN ('done','cancelled') AND NOT EXISTS
+ (SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'));
+ IF owner_workspace IS NULL THEN RETURN; END IF;
+ evidence := jsonb_build_object('event_id',p_key,'event_type',p_type,'version',1,
+ 'occurred_at',clock_timestamp(),'workspace_id',owner_workspace,'issue_id',p_issue,
+ 'source_task_id',p_task,'agent_id',p_agent,
+ 'actor_type',COALESCE(NULLIF(current_setting('multica.actor_type',true),''),CASE WHEN p_agent IS NOT NULL THEN 'agent' ELSE 'system' END),
+ 'actor_id',COALESCE(NULLIF(current_setting('multica.actor_id',true),''),p_agent::text)) || p_payload;
+ FOR w IN SELECT * FROM issue_wakeup WHERE issue_id=p_issue AND workspace_id=owner_workspace AND enabled AND kind='event'
+ AND p_type=ANY(event_types)
+ AND (filter_actor_type IS NULL OR (filter_actor_type=evidence->>'actor_type' AND filter_actor_id::text=evidence->>'actor_id'))
+ AND (filter_agent_id IS NULL OR filter_agent_id=p_agent)
+ AND (filter_task_id IS NULL OR filter_task_id=p_task)
+ AND (p_task IS NULL OR source_task_id IS DISTINCT FROM p_task)
+ AND NOT EXISTS (SELECT 1 FROM agent_task_queue t WHERE t.id=p_task AND t.context->>'wakeup_id'=issue_wakeup.id::text)
+ ORDER BY id
+ LOOP
+ -- One pending notification per event type. Preserve the first key for
+ -- duplicate suppression and the latest source reference for state reads.
+ BEGIN
+ INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload,coalesce_key)
+ VALUES(gen_random_uuid(),w.id,w.revision,p_key,p_type,
+ evidence || jsonb_build_object('coalesced_count',1,'first_occurred_at',evidence->'occurred_at'),p_type)
+ ON CONFLICT(wakeup_id,revision,coalesce_key) WHERE processed_at IS NULL AND coalesce_key IS NOT NULL
+ -- Rotate the receipt identity on merge. An older dispatcher that read
+ -- without FOR UPDATE can only consume its observed version, leaving the
+ -- replacement pending instead of silently consuming unseen evidence.
+ DO UPDATE SET id=EXCLUDED.id,payload=EXCLUDED.payload || jsonb_build_object(
+ 'coalesced_count',COALESCE((issue_wakeup_receipt.payload->>'coalesced_count')::bigint,1)+1,
+ 'first_occurred_at',issue_wakeup_receipt.payload->'first_occurred_at')
+ WHERE issue_wakeup_receipt.event_key<>p_key AND issue_wakeup_receipt.payload->>'event_id' IS DISTINCT FROM p_key;
+ EXCEPTION WHEN unique_violation THEN
+ GET STACKED DIAGNOSTICS violated_constraint = CONSTRAINT_NAME;
+ -- A retained receipt already handled this exact source fact. This also
+ -- fences the locked registration snapshot against terminal-task capture.
+ IF violated_constraint <> 'issue_wakeup_receipt_key_idx' THEN RAISE; END IF;
+ END;
+
+ END LOOP;
+END $$;
diff --git a/server/migrations/579_wakeup_skip_handed_to_agent.up.sql b/server/migrations/579_wakeup_skip_handed_to_agent.up.sql
new file mode 100644
index 0000000000..9931361106
--- /dev/null
+++ b/server/migrations/579_wakeup_skip_handed_to_agent.up.sql
@@ -0,0 +1,58 @@
+-- A write that hands an issue to an agent — assigning it, or entering a
+-- project workflow step it handles (MUL-7420) — delivers that change to the
+-- agent as its own run. Recording the same write for the agent's event wakeups
+-- would start a second run for one fact, so the write names the agent in the
+-- transaction-local multica.handed_to_agent and its issue.* events skip that
+-- agent's subscriptions. Everyone else's wakeups — including platform rules,
+-- which have no agent_id — and every task, comment and reaction event, are
+-- captured as before.
+CREATE OR REPLACE FUNCTION capture_issue_wakeup(p_issue uuid, p_type text, p_key text, p_agent uuid, p_task uuid, p_payload jsonb)
+RETURNS void LANGUAGE plpgsql AS $$
+DECLARE w issue_wakeup; owner_workspace uuid; evidence jsonb; violated_constraint text;
+BEGIN
+ IF NOT EXISTS (SELECT 1 FROM issue_wakeup WHERE issue_id=p_issue AND enabled AND kind='event' AND p_type=ANY(event_types)) THEN RETURN; END IF;
+ IF p_agent IS NULL AND current_setting('multica.actor_type',true)='agent' THEN
+ p_agent := NULLIF(current_setting('multica.actor_id',true),'')::uuid;
+ END IF;
+ SELECT i.workspace_id INTO owner_workspace FROM issue i
+ WHERE i.id=p_issue AND i.status NOT IN ('done','cancelled') AND NOT EXISTS
+ (SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'));
+ IF owner_workspace IS NULL THEN RETURN; END IF;
+ evidence := jsonb_build_object('event_id',p_key,'event_type',p_type,'version',1,
+ 'occurred_at',clock_timestamp(),'workspace_id',owner_workspace,'issue_id',p_issue,
+ 'source_task_id',p_task,'agent_id',p_agent,
+ 'actor_type',COALESCE(NULLIF(current_setting('multica.actor_type',true),''),CASE WHEN p_agent IS NOT NULL THEN 'agent' ELSE 'system' END),
+ 'actor_id',COALESCE(NULLIF(current_setting('multica.actor_id',true),''),p_agent::text)) || p_payload;
+ FOR w IN SELECT * FROM issue_wakeup WHERE issue_id=p_issue AND workspace_id=owner_workspace AND enabled AND kind='event'
+ AND p_type=ANY(event_types)
+ AND (filter_actor_type IS NULL OR (filter_actor_type=evidence->>'actor_type' AND filter_actor_id::text=evidence->>'actor_id'))
+ AND (filter_agent_id IS NULL OR filter_agent_id=p_agent)
+ AND (filter_task_id IS NULL OR filter_task_id=p_task)
+ AND (p_task IS NULL OR source_task_id IS DISTINCT FROM p_task)
+ AND NOT EXISTS (SELECT 1 FROM agent_task_queue t WHERE t.id=p_task AND t.context->>'wakeup_id'=issue_wakeup.id::text)
+ AND (p_type NOT LIKE 'issue.%' OR agent_id IS NULL OR agent_id IS DISTINCT FROM NULLIF(current_setting('multica.handed_to_agent',true),'')::uuid)
+ ORDER BY id
+ LOOP
+ -- One pending notification per event type. Preserve the first key for
+ -- duplicate suppression and the latest source reference for state reads.
+ BEGIN
+ INSERT INTO issue_wakeup_receipt(id,wakeup_id,revision,event_key,event_type,payload,coalesce_key)
+ VALUES(gen_random_uuid(),w.id,w.revision,p_key,p_type,
+ evidence || jsonb_build_object('coalesced_count',1,'first_occurred_at',evidence->'occurred_at'),p_type)
+ ON CONFLICT(wakeup_id,revision,coalesce_key) WHERE processed_at IS NULL AND coalesce_key IS NOT NULL
+ -- Rotate the receipt identity on merge. An older dispatcher that read
+ -- without FOR UPDATE can only consume its observed version, leaving the
+ -- replacement pending instead of silently consuming unseen evidence.
+ DO UPDATE SET id=EXCLUDED.id,payload=EXCLUDED.payload || jsonb_build_object(
+ 'coalesced_count',COALESCE((issue_wakeup_receipt.payload->>'coalesced_count')::bigint,1)+1,
+ 'first_occurred_at',issue_wakeup_receipt.payload->'first_occurred_at')
+ WHERE issue_wakeup_receipt.event_key<>p_key AND issue_wakeup_receipt.payload->>'event_id' IS DISTINCT FROM p_key;
+ EXCEPTION WHEN unique_violation THEN
+ GET STACKED DIAGNOSTICS violated_constraint = CONSTRAINT_NAME;
+ -- A retained receipt already handled this exact source fact. This also
+ -- fences the locked registration snapshot against terminal-task capture.
+ IF violated_constraint <> 'issue_wakeup_receipt_key_idx' THEN RAISE; END IF;
+ END;
+
+ END LOOP;
+END $$;
diff --git a/server/migrations/581_issue_workflow_is_default.down.sql b/server/migrations/581_issue_workflow_is_default.down.sql
new file mode 100644
index 0000000000..d525bcf6d6
--- /dev/null
+++ b/server/migrations/581_issue_workflow_is_default.down.sql
@@ -0,0 +1 @@
+ALTER TABLE issue_workflow DROP COLUMN IF EXISTS is_default;
diff --git a/server/migrations/581_issue_workflow_is_default.up.sql b/server/migrations/581_issue_workflow_is_default.up.sql
new file mode 100644
index 0000000000..56001d7e0a
--- /dev/null
+++ b/server/migrations/581_issue_workflow_is_default.up.sql
@@ -0,0 +1,8 @@
+-- The workspace Default workflow becomes a real, editable row (MUL-7420).
+-- Projects without a workflow_id use it. Before the row exists, Default is
+-- the built-in statuses plus the custom statuses no other workflow lists;
+-- the row is created from that snapshot the first time workflows are read
+-- with the feature on, so statuses added for one workflow no longer pile up
+-- in Default and in every cross-project board. At most one per workspace
+-- (582).
+ALTER TABLE issue_workflow ADD COLUMN IF NOT EXISTS is_default BOOLEAN NOT NULL DEFAULT false;
diff --git a/server/migrations/582_issue_workflow_default_index.down.sql b/server/migrations/582_issue_workflow_default_index.down.sql
new file mode 100644
index 0000000000..98cb2c7230
--- /dev/null
+++ b/server/migrations/582_issue_workflow_default_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_workflow_workspace_default;
diff --git a/server/migrations/582_issue_workflow_default_index.up.sql b/server/migrations/582_issue_workflow_default_index.up.sql
new file mode 100644
index 0000000000..efd5766c67
--- /dev/null
+++ b/server/migrations/582_issue_workflow_default_index.up.sql
@@ -0,0 +1,3 @@
+-- One Default workflow per workspace (581).
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_workflow_workspace_default
+ ON issue_workflow (workspace_id) WHERE is_default;
diff --git a/server/pkg/db/generated/activity.sql.go b/server/pkg/db/generated/activity.sql.go
index badd12f9c2..a11cfbd62c 100644
--- a/server/pkg/db/generated/activity.sql.go
+++ b/server/pkg/db/generated/activity.sql.go
@@ -120,6 +120,27 @@ func (q *Queries) GetActivity(ctx context.Context, id pgtype.UUID) (ActivityLog,
return i, err
}
+const getLastIssueStatusChange = `-- name: GetLastIssueStatusChange :one
+SELECT actor_type, actor_id FROM activity_log
+WHERE issue_id = $1 AND action = 'status_changed'
+ORDER BY created_at DESC, id DESC
+LIMIT 1
+`
+
+type GetLastIssueStatusChangeRow struct {
+ ActorType pgtype.Text `json:"actor_type"`
+ ActorID pgtype.UUID `json:"actor_id"`
+}
+
+// Who last changed an issue's status, and to what: names the mover when an
+// agent's status change is refused because the issue left its step (MUL-7420).
+func (q *Queries) GetLastIssueStatusChange(ctx context.Context, issueID pgtype.UUID) (GetLastIssueStatusChangeRow, error) {
+ row := q.db.QueryRow(ctx, getLastIssueStatusChange, issueID)
+ var i GetLastIssueStatusChangeRow
+ err := row.Scan(&i.ActorType, &i.ActorID)
+ return i, err
+}
+
const hasSquadLeaderNoActionEvaluationForTask = `-- name: HasSquadLeaderNoActionEvaluationForTask :one
SELECT EXISTS (
SELECT 1
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index b58582e0e9..62aab47fa0 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -32,7 +32,7 @@ WHERE acknowledged.id = (
WHERE attempt_count.trigger_evidence_kind = 'delegated_failure'
AND attempt_count.trigger_evidence_ref_id = $2
) >= $3::int
-RETURNING acknowledged.id, acknowledged.agent_id, acknowledged.issue_id, acknowledged.status, acknowledged.priority, acknowledged.dispatched_at, acknowledged.started_at, acknowledged.completed_at, acknowledged.result, acknowledged.error, acknowledged.created_at, acknowledged.context, acknowledged.runtime_id, acknowledged.session_id, acknowledged.work_dir, acknowledged.trigger_comment_id, acknowledged.chat_session_id, acknowledged.autopilot_run_id, acknowledged.attempt, acknowledged.max_attempts, acknowledged.parent_task_id, acknowledged.failure_reason, acknowledged.trigger_summary, acknowledged.force_fresh_session, acknowledged.is_leader_task, acknowledged.wait_reason, acknowledged.initiator_user_id, acknowledged.handoff_note, acknowledged.prepare_lease_expires_at, acknowledged.squad_id, acknowledged.runtime_mcp_overlay, acknowledged.escalation_for_task_id, acknowledged.fire_at, acknowledged.originator_user_id, acknowledged.runtime_connected_apps, acknowledged.coalesced_comment_ids, acknowledged.delivered_comment_ids, acknowledged.chat_input_task_id, acknowledged.chat_finalize_deferred_at, acknowledged.originator_source, acknowledged.delegated_from_task_id, acknowledged.retry_of_task_id, acknowledged.rerun_of_task_id, acknowledged.rule_version_id, acknowledged.trigger_evidence_kind, acknowledged.trigger_evidence_ref_id, acknowledged.accountable_user_id, acknowledged.session_rollout_missing, acknowledged.retired_session_id, acknowledged.quick_actions_disabled, acknowledged.regenerate_quick_actions_for, acknowledged.branch_name, acknowledged.durable_work_dir, acknowledged.channel_context_revision, acknowledged.comment_thread_id, acknowledged.cancelled_by_type, acknowledged.cancelled_by_id, acknowledged.cancelled_by_name, acknowledged.issue_snapshot
+RETURNING acknowledged.id, acknowledged.agent_id, acknowledged.issue_id, acknowledged.status, acknowledged.priority, acknowledged.dispatched_at, acknowledged.started_at, acknowledged.completed_at, acknowledged.result, acknowledged.error, acknowledged.created_at, acknowledged.context, acknowledged.runtime_id, acknowledged.session_id, acknowledged.work_dir, acknowledged.trigger_comment_id, acknowledged.chat_session_id, acknowledged.autopilot_run_id, acknowledged.attempt, acknowledged.max_attempts, acknowledged.parent_task_id, acknowledged.failure_reason, acknowledged.trigger_summary, acknowledged.force_fresh_session, acknowledged.is_leader_task, acknowledged.wait_reason, acknowledged.initiator_user_id, acknowledged.handoff_note, acknowledged.prepare_lease_expires_at, acknowledged.squad_id, acknowledged.runtime_mcp_overlay, acknowledged.escalation_for_task_id, acknowledged.fire_at, acknowledged.originator_user_id, acknowledged.runtime_connected_apps, acknowledged.coalesced_comment_ids, acknowledged.delivered_comment_ids, acknowledged.chat_input_task_id, acknowledged.chat_finalize_deferred_at, acknowledged.originator_source, acknowledged.delegated_from_task_id, acknowledged.retry_of_task_id, acknowledged.rerun_of_task_id, acknowledged.rule_version_id, acknowledged.trigger_evidence_kind, acknowledged.trigger_evidence_ref_id, acknowledged.accountable_user_id, acknowledged.session_rollout_missing, acknowledged.retired_session_id, acknowledged.quick_actions_disabled, acknowledged.regenerate_quick_actions_for, acknowledged.branch_name, acknowledged.durable_work_dir, acknowledged.channel_context_revision, acknowledged.comment_thread_id, acknowledged.cancelled_by_type, acknowledged.cancelled_by_id, acknowledged.cancelled_by_name, acknowledged.issue_snapshot, acknowledged.workflow_step
`
type AcknowledgeExhaustedDelegatedFailureRecoveryParams struct {
@@ -108,6 +108,7 @@ func (q *Queries) AcknowledgeExhaustedDelegatedFailureRecovery(ctx context.Conte
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -309,7 +310,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULL
WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
// Automatic cancellation without an explicit persisted failure reason. Unlike
@@ -377,6 +378,7 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -438,7 +440,7 @@ SET status = 'cancelled',
END
WHERE task.id = $1
AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step
`
type CancelAgentTaskByUserParams struct {
@@ -520,6 +522,7 @@ func (q *Queries) CancelAgentTaskByUser(ctx context.Context, arg CancelAgentTask
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -535,7 +538,7 @@ SET status = 'cancelled',
cancelled_by_id = NULL,
cancelled_by_name = NULL
WHERE id = $3 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type CancelAgentTaskWithReasonParams struct {
@@ -614,6 +617,7 @@ func (q *Queries) CancelAgentTaskWithReason(ctx context.Context, arg CancelAgent
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -623,7 +627,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULL
WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
// Bulk-cancel every active (queued/dispatched/running) task for an agent.
@@ -700,6 +704,7 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -716,7 +721,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULL
WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
// Cancels active tasks belonging to a chat session. Called from
@@ -793,6 +798,7 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -809,7 +815,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULL
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
// Cancels every active task on the issue and returns the affected rows so the
@@ -886,6 +892,7 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -904,7 +911,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
context = COALESCE(context, '{}'::jsonb) || jsonb_build_object('comment_change_cancelled_task_id', id::text)
WHERE (trigger_comment_id = $1 OR $1 = ANY(coalesced_comment_ids))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
// Cancels active tasks whose planned batch contains the edited/deleted comment.
@@ -980,6 +987,7 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -997,7 +1005,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULL
WHERE issue_id = $1 AND agent_id = $2
AND status IN ('queued', 'dispatched', 'deferred')
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type CancelPendingTasksByIssueAndAgentParams struct {
@@ -1090,6 +1098,7 @@ func (q *Queries) CancelPendingTasksByIssueAndAgent(ctx context.Context, arg Can
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -1108,7 +1117,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
WHERE issue_id = $1 AND agent_id = $2
AND status IN ('queued', 'dispatched', 'deferred')
AND comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id($3::uuid)
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type CancelPendingTasksByIssueAndAgentInThreadParams struct {
@@ -1188,6 +1197,7 @@ func (q *Queries) CancelPendingTasksByIssueAndAgentInThread(ctx context.Context,
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -1208,7 +1218,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
WHERE id = $4
AND chat_session_id = $5
AND status = 'queued'
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type CancelQueuedAgentTaskParams struct {
@@ -1290,6 +1300,7 @@ func (q *Queries) CancelQueuedAgentTask(ctx context.Context, arg CancelQueuedAge
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -1318,7 +1329,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
WHERE queued.chat_session_id = $1
AND queued.status = 'queued'
AND queued.id IS DISTINCT FROM (SELECT id FROM head)
-RETURNING queued.id, queued.agent_id, queued.issue_id, queued.status, queued.priority, queued.dispatched_at, queued.started_at, queued.completed_at, queued.result, queued.error, queued.created_at, queued.context, queued.runtime_id, queued.session_id, queued.work_dir, queued.trigger_comment_id, queued.chat_session_id, queued.autopilot_run_id, queued.attempt, queued.max_attempts, queued.parent_task_id, queued.failure_reason, queued.trigger_summary, queued.force_fresh_session, queued.is_leader_task, queued.wait_reason, queued.initiator_user_id, queued.handoff_note, queued.prepare_lease_expires_at, queued.squad_id, queued.runtime_mcp_overlay, queued.escalation_for_task_id, queued.fire_at, queued.originator_user_id, queued.runtime_connected_apps, queued.coalesced_comment_ids, queued.delivered_comment_ids, queued.chat_input_task_id, queued.chat_finalize_deferred_at, queued.originator_source, queued.delegated_from_task_id, queued.retry_of_task_id, queued.rerun_of_task_id, queued.rule_version_id, queued.trigger_evidence_kind, queued.trigger_evidence_ref_id, queued.accountable_user_id, queued.session_rollout_missing, queued.retired_session_id, queued.quick_actions_disabled, queued.regenerate_quick_actions_for, queued.branch_name, queued.durable_work_dir, queued.channel_context_revision, queued.comment_thread_id, queued.cancelled_by_type, queued.cancelled_by_id, queued.cancelled_by_name, queued.issue_snapshot
+RETURNING queued.id, queued.agent_id, queued.issue_id, queued.status, queued.priority, queued.dispatched_at, queued.started_at, queued.completed_at, queued.result, queued.error, queued.created_at, queued.context, queued.runtime_id, queued.session_id, queued.work_dir, queued.trigger_comment_id, queued.chat_session_id, queued.autopilot_run_id, queued.attempt, queued.max_attempts, queued.parent_task_id, queued.failure_reason, queued.trigger_summary, queued.force_fresh_session, queued.is_leader_task, queued.wait_reason, queued.initiator_user_id, queued.handoff_note, queued.prepare_lease_expires_at, queued.squad_id, queued.runtime_mcp_overlay, queued.escalation_for_task_id, queued.fire_at, queued.originator_user_id, queued.runtime_connected_apps, queued.coalesced_comment_ids, queued.delivered_comment_ids, queued.chat_input_task_id, queued.chat_finalize_deferred_at, queued.originator_source, queued.delegated_from_task_id, queued.retry_of_task_id, queued.rerun_of_task_id, queued.rule_version_id, queued.trigger_evidence_kind, queued.trigger_evidence_ref_id, queued.accountable_user_id, queued.session_rollout_missing, queued.retired_session_id, queued.quick_actions_disabled, queued.regenerate_quick_actions_for, queued.branch_name, queued.durable_work_dir, queued.channel_context_revision, queued.comment_thread_id, queued.cancelled_by_type, queued.cancelled_by_id, queued.cancelled_by_name, queued.issue_snapshot, queued.workflow_step
`
// Clear only positional follow-ups. The first visible task is current even
@@ -1394,6 +1405,7 @@ func (q *Queries) CancelQueuedAgentTasksForSession(ctx context.Context, chatSess
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -1422,7 +1434,7 @@ WHERE r.runtime_id = ANY($1::uuid[])
AND successor.id <> r.id
AND successor.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
)
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
// Cancels deferred auto-retry rows that a newer active task has already
@@ -1516,6 +1528,7 @@ func (q *Queries) CancelSupersededDeferredRetriesForRuntimes(ctx context.Context
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -1578,7 +1591,7 @@ WHERE id = (
LIMIT 1
FOR 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, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type ClaimAgentTaskParams struct {
@@ -1666,6 +1679,7 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -1674,7 +1688,7 @@ const claimChatFinalizeDeferred = `-- name: ClaimChatFinalizeDeferred :one
UPDATE agent_task_queue
SET chat_finalize_deferred_at = NULL
WHERE id = $1 AND chat_finalize_deferred_at IS NOT NULL
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
// Atomically claims the deferred marker so the daemon ack and the sweeper
@@ -1742,6 +1756,7 @@ func (q *Queries) ClaimChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -1940,7 +1955,7 @@ SET status = 'completed', completed_at = now(), result = $2,
retired_session_id = COALESCE($8, retired_session_id),
prepare_lease_expires_at = NULL
WHERE 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, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type CompleteAgentTaskParams struct {
@@ -2037,6 +2052,7 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -2253,7 +2269,7 @@ INSERT INTO agent_task_queue (
coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,
squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id, trigger_evidence_kind, trigger_evidence_ref_id,
- id
+ workflow_step, id
)
SELECT
$1, $2, $3, 'queued', $4, $5,
@@ -2278,9 +2294,11 @@ SELECT
$20,
$21,
$22,
+ -- The issue's status as this task is queued: the workflow step it works on (MUL-7420).
+ (SELECT i.status FROM issue i WHERE i.id = $3),
COALESCE($23::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type CreateAgentTaskParams struct {
@@ -2414,6 +2432,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -2425,7 +2444,7 @@ INSERT INTO agent_task_queue (
squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id,
trigger_evidence_kind, trigger_evidence_ref_id, fire_at,
- id
+ workflow_step, id
)
SELECT
$1, $2, $3, 'deferred', $4, $5,
@@ -2450,9 +2469,11 @@ SELECT
$21,
$22,
$23,
+ -- The issue's status as this task is queued: the workflow step it works on (MUL-7420).
+ (SELECT i.status FROM issue i WHERE i.id = $3),
COALESCE($24::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type CreateDeferredChannelIssueTaskParams struct {
@@ -2577,6 +2598,7 @@ func (q *Queries) CreateDeferredChannelIssueTask(ctx context.Context, arg Create
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -2602,7 +2624,7 @@ WHERE p.id = $5
AND p.chat_session_id IS NULL
AND p.autopilot_run_id IS NULL
AND lock_task_owner_rows(p.agent_id, p.issue_id, p.runtime_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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type CreateManualQuickCreateRetryTaskParams struct {
@@ -2691,6 +2713,7 @@ func (q *Queries) CreateManualQuickCreateRetryTask(ctx context.Context, arg Crea
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -2713,7 +2736,7 @@ SELECT
$11,
COALESCE($12::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, NULL, $2)
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type CreateQuickCreateTaskParams struct {
@@ -2817,6 +2840,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -2831,7 +2855,7 @@ INSERT INTO agent_task_queue (
originator_source, delegated_from_task_id, rule_version_id,
trigger_evidence_kind, trigger_evidence_ref_id, retry_of_task_id,
chat_input_task_id, fire_at,
- channel_context_revision, handoff_note, id
+ channel_context_revision, handoff_note, workflow_step, id
)
SELECT
p.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,
@@ -2852,7 +2876,11 @@ SELECT
p.trigger_evidence_kind, p.trigger_evidence_ref_id, p.id,
p.chat_input_task_id, $2,
p.channel_context_revision,
- CASE WHEN p.context->>'wakeup_id' IS NOT NULL THEN p.handoff_note END,
+ -- Carried for a wakeup's prompt and a workflow handoff's brief (MUL-7420);
+ -- rows from before workflow_step existed may hold a retired assignment note.
+ CASE WHEN p.context->>'wakeup_id' IS NOT NULL OR p.workflow_step IS NOT NULL THEN p.handoff_note END,
+ -- A retry continues its parent's work, so it keeps the parent's step (MUL-7420).
+ p.workflow_step,
-- Named new_task_id, not id: $1 above is the PARENT task's id.
COALESCE($6::uuid, gen_random_uuid())
FROM agent_task_queue p
@@ -2861,7 +2889,7 @@ WHERE p.id = $1
ON CONFLICT (issue_id, agent_id, (COALESCE(comment_thread_id, '00000000-0000-0000-0000-000000000000'::uuid))) WHERE status IN ('queued', 'dispatched')
OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')
DO NOTHING
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type CreateRetryTaskParams struct {
@@ -2959,6 +2987,7 @@ func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -3139,7 +3168,7 @@ WHERE t.id = v.id
WHERE retry_parent.id = t.parent_task_id
AND retry_parent.failure_reason = 'runtime_offline'
)
-RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision, t.comment_thread_id, t.cancelled_by_type, t.cancelled_by_id, t.cancelled_by_name, t.issue_snapshot
+RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision, t.comment_thread_id, t.cancelled_by_type, t.cancelled_by_id, t.cancelled_by_name, t.issue_snapshot, t.workflow_step
`
type ExpireStaleQueuedTasksParams struct {
@@ -3224,6 +3253,7 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -3242,7 +3272,7 @@ WHERE id = $1
AND runtime_id = $2
AND status IN ('dispatched', 'waiting_local_directory')
AND started_at IS NULL
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type ExtendAgentTaskPrepareLeaseParams struct {
@@ -3318,6 +3348,7 @@ func (q *Queries) ExtendAgentTaskPrepareLease(ctx context.Context, arg ExtendAge
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -3336,7 +3367,7 @@ SET status = 'failed',
retired_session_id = COALESCE($9, retired_session_id),
prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type FailAgentTaskParams struct {
@@ -3439,6 +3470,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -3485,7 +3517,7 @@ WHERE retry.id = victims.id
AND COALESCE(runtime.last_seen_at, runtime.updated_at) >=
now() - make_interval(secs => $2::double precision)
)
-RETURNING retry.id, retry.agent_id, retry.issue_id, retry.status, retry.priority, retry.dispatched_at, retry.started_at, retry.completed_at, retry.result, retry.error, retry.created_at, retry.context, retry.runtime_id, retry.session_id, retry.work_dir, retry.trigger_comment_id, retry.chat_session_id, retry.autopilot_run_id, retry.attempt, retry.max_attempts, retry.parent_task_id, retry.failure_reason, retry.trigger_summary, retry.force_fresh_session, retry.is_leader_task, retry.wait_reason, retry.initiator_user_id, retry.handoff_note, retry.prepare_lease_expires_at, retry.squad_id, retry.runtime_mcp_overlay, retry.escalation_for_task_id, retry.fire_at, retry.originator_user_id, retry.runtime_connected_apps, retry.coalesced_comment_ids, retry.delivered_comment_ids, retry.chat_input_task_id, retry.chat_finalize_deferred_at, retry.originator_source, retry.delegated_from_task_id, retry.retry_of_task_id, retry.rerun_of_task_id, retry.rule_version_id, retry.trigger_evidence_kind, retry.trigger_evidence_ref_id, retry.accountable_user_id, retry.session_rollout_missing, retry.retired_session_id, retry.quick_actions_disabled, retry.regenerate_quick_actions_for, retry.branch_name, retry.durable_work_dir, retry.channel_context_revision, retry.comment_thread_id, retry.cancelled_by_type, retry.cancelled_by_id, retry.cancelled_by_name, retry.issue_snapshot
+RETURNING retry.id, retry.agent_id, retry.issue_id, retry.status, retry.priority, retry.dispatched_at, retry.started_at, retry.completed_at, retry.result, retry.error, retry.created_at, retry.context, retry.runtime_id, retry.session_id, retry.work_dir, retry.trigger_comment_id, retry.chat_session_id, retry.autopilot_run_id, retry.attempt, retry.max_attempts, retry.parent_task_id, retry.failure_reason, retry.trigger_summary, retry.force_fresh_session, retry.is_leader_task, retry.wait_reason, retry.initiator_user_id, retry.handoff_note, retry.prepare_lease_expires_at, retry.squad_id, retry.runtime_mcp_overlay, retry.escalation_for_task_id, retry.fire_at, retry.originator_user_id, retry.runtime_connected_apps, retry.coalesced_comment_ids, retry.delivered_comment_ids, retry.chat_input_task_id, retry.chat_finalize_deferred_at, retry.originator_source, retry.delegated_from_task_id, retry.retry_of_task_id, retry.rerun_of_task_id, retry.rule_version_id, retry.trigger_evidence_kind, retry.trigger_evidence_ref_id, retry.accountable_user_id, retry.session_rollout_missing, retry.retired_session_id, retry.quick_actions_disabled, retry.regenerate_quick_actions_for, retry.branch_name, retry.durable_work_dir, retry.channel_context_revision, retry.comment_thread_id, retry.cancelled_by_type, retry.cancelled_by_id, retry.cancelled_by_name, retry.issue_snapshot, retry.workflow_step
`
type FailExpiredRuntimeReconnectRetriesParams struct {
@@ -3570,6 +3602,7 @@ func (q *Queries) FailExpiredRuntimeReconnectRetries(ctx context.Context, arg Fa
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -3624,7 +3657,7 @@ WHERE (
)
)
)
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type FailStaleTasksParams struct {
@@ -3740,6 +3773,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -3981,7 +4015,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, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot 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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue
WHERE id = $1
`
@@ -4048,12 +4082,13 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
const getAgentTaskForDelegatedFailureUpdate = `-- name: GetAgentTaskForDelegatedFailureUpdate :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, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot 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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue
WHERE id = $1
FOR UPDATE
`
@@ -4124,12 +4159,13 @@ func (q *Queries) GetAgentTaskForDelegatedFailureUpdate(ctx context.Context, id
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
const getAgentTaskInWorkspace = `-- name: GetAgentTaskInWorkspace :one
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE atq.id = $1 AND a.workspace_id = $2
`
@@ -4209,6 +4245,7 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -5032,7 +5069,7 @@ func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtim
}
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, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot 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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
ORDER BY created_at DESC
`
@@ -5111,6 +5148,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -5225,7 +5263,7 @@ func (q *Queries) ListActiveTasksByIssueFamily(ctx context.Context, arg ListActi
}
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, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot 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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue
WHERE agent_id = $1
-- Apply visibility before LIMIT so hidden fallbacks cannot end a page early.
-- Keep this predicate in sync with handler.visibleTaskHistory.
@@ -5317,6 +5355,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, arg ListAgentTasksParams)
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -5507,7 +5546,7 @@ func (q *Queries) ListAllAgentsAnyKind(ctx context.Context, workspaceID pgtype.U
}
const listChatFinalizeDeferredExpired = `-- name: ListChatFinalizeDeferredExpired :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, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot 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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue
WHERE chat_finalize_deferred_at IS NOT NULL
AND chat_finalize_deferred_at < now() - make_interval(secs => $1::double precision)
ORDER BY chat_finalize_deferred_at
@@ -5591,6 +5630,7 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -5734,7 +5774,7 @@ func (q *Queries) ListPendingDelegatedFailureRecoveries(ctx context.Context, max
}
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, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot 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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue
WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')
ORDER BY priority DESC, created_at ASC
`
@@ -5808,6 +5848,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -5820,7 +5861,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
}
const listQueuedClaimCandidatesByRuntime = `-- name: ListQueuedClaimCandidatesByRuntime :many
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step FROM agent_task_queue atq
WHERE atq.runtime_id = $1
AND atq.status = 'queued'
AND (atq.context->>'wakeup_id' IS NULL OR EXISTS (SELECT 1 FROM issue_wakeup w WHERE w.id=(atq.context->>'wakeup_id')::uuid AND w.disabled_at IS NULL AND w.revision=(atq.context->>'wakeup_revision')::bigint))
@@ -5916,6 +5957,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -5928,7 +5970,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
}
const listQueuedClaimCandidatesByRuntimes = `-- name: ListQueuedClaimCandidatesByRuntimes :many
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step FROM agent_task_queue atq
WHERE atq.runtime_id = ANY($1::uuid[])
AND atq.status = 'queued'
AND (atq.context->>'wakeup_id' IS NULL OR EXISTS (SELECT 1 FROM issue_wakeup w WHERE w.id=(atq.context->>'wakeup_id')::uuid AND w.disabled_at IS NULL AND w.revision=(atq.context->>'wakeup_revision')::bigint))
@@ -6026,6 +6068,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -6038,7 +6081,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti
}
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, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot 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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue
WHERE issue_id = $1
ORDER BY created_at DESC
`
@@ -6112,6 +6155,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -6219,7 +6263,7 @@ func (q *Queries) ListUserAgentsByRuntimeForUpdate(ctx context.Context, runtimeI
}
const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshot :many
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
AND (atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
@@ -6227,9 +6271,9 @@ WHERE a.workspace_id = $1
UNION ALL
-SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing, latest.retired_session_id, latest.quick_actions_disabled, latest.regenerate_quick_actions_for, latest.branch_name, latest.durable_work_dir, latest.channel_context_revision, latest.comment_thread_id, latest.cancelled_by_type, latest.cancelled_by_id, latest.cancelled_by_name, latest.issue_snapshot FROM agent a
+SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing, latest.retired_session_id, latest.quick_actions_disabled, latest.regenerate_quick_actions_for, latest.branch_name, latest.durable_work_dir, latest.channel_context_revision, latest.comment_thread_id, latest.cancelled_by_type, latest.cancelled_by_id, latest.cancelled_by_name, latest.issue_snapshot, latest.workflow_step FROM agent a
JOIN LATERAL (
- SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot
+ SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step
FROM agent_task_queue atq
WHERE atq.agent_id = a.id
AND atq.status IN ('completed', 'failed')
@@ -6333,6 +6377,7 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -6578,7 +6623,7 @@ func (q *Queries) LockAgentForAutopilotAssignment(ctx context.Context, arg LockA
}
const lockAgentTaskStartClaim = `-- name: LockAgentTaskStartClaim :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, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot 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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue
WHERE id = $1 AND runtime_id = $2 AND dispatched_at = $3
AND status IN ('dispatched', 'waiting_local_directory', 'running')
FOR UPDATE
@@ -6655,6 +6700,7 @@ func (q *Queries) LockAgentTaskStartClaim(ctx context.Context, arg LockAgentTask
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -6665,7 +6711,7 @@ SET status = 'waiting_local_directory',
wait_reason = $2,
prepare_lease_expires_at = now() + make_interval(secs => $3::double precision)
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, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type MarkAgentTaskWaitingLocalDirectoryParams struct {
@@ -6746,6 +6792,7 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -6754,7 +6801,7 @@ const markChatFinalizeDeferred = `-- name: MarkChatFinalizeDeferred :one
UPDATE agent_task_queue
SET chat_finalize_deferred_at = now()
WHERE id = $1
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
// Arms the deferred chat-finalize marker for a cancelled chat task whose
@@ -6822,6 +6869,7 @@ func (q *Queries) MarkChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -6984,7 +7032,7 @@ WHERE id = (
ORDER BY t.created_at DESC
LIMIT 1
)
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type MergeDelegatedFailureCommentIntoPendingTaskParams struct {
@@ -7068,6 +7116,7 @@ func (q *Queries) MergeDelegatedFailureCommentIntoPendingTask(ctx context.Contex
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -7124,7 +7173,7 @@ const promoteDeferredChannelIssueTask = `-- name: PromoteDeferredChannelIssueTas
UPDATE agent_task_queue
SET status = 'queued', fire_at = NULL
WHERE id = $1 AND issue_id IS NOT NULL AND status = 'deferred'
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
// Early promotion is idempotent at the service layer: a task already promoted
@@ -7192,6 +7241,7 @@ func (q *Queries) PromoteDeferredChannelIssueTask(ctx context.Context, id pgtype
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -7230,7 +7280,7 @@ WITH due AS (
UPDATE agent_task_queue
SET status = 'queued'
WHERE id IN (SELECT id FROM due WHERE issue_id IS NULL OR rn = 1)
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type PromoteDueDeferredTasksForRuntimeParams struct {
@@ -7322,6 +7372,7 @@ func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, arg Pro
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -7367,7 +7418,7 @@ WITH due AS (
UPDATE agent_task_queue
SET status = 'queued'
WHERE id IN (SELECT id FROM due WHERE issue_id IS NULL OR rn = 1)
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type PromoteDueDeferredTasksForRuntimesParams struct {
@@ -7447,6 +7498,7 @@ func (q *Queries) PromoteDueDeferredTasksForRuntimes(ctx context.Context, arg Pr
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -7571,7 +7623,7 @@ WHERE id = (
LIMIT 1
FOR 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, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type ReclaimStaleDispatchedTaskForRuntimeParams struct {
@@ -7654,6 +7706,7 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -7696,7 +7749,7 @@ WHERE id IN (
LIMIT $5::int
FOR 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, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type ReclaimStaleDispatchedTasksForRuntimesParams struct {
@@ -7789,6 +7842,7 @@ func (q *Queries) ReclaimStaleDispatchedTasksForRuntimes(ctx context.Context, ar
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -7809,7 +7863,7 @@ SET status = 'failed',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE runtime_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
// Called by the daemon at startup. Atomically fails any dispatched/running/
@@ -7887,6 +7941,7 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -8040,7 +8095,7 @@ WHERE id = $1
AND status = 'dispatched'
AND started_at IS NULL
AND dispatched_at = $3
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type RequeueAgentTaskAfterClaimFailureParams struct {
@@ -8117,6 +8172,7 @@ func (q *Queries) RequeueAgentTaskAfterClaimFailure(ctx context.Context, arg Req
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -8353,6 +8409,22 @@ func (q *Queries) SetTaskIssueSnapshot(ctx context.Context, arg SetTaskIssueSnap
return err
}
+const setTaskWorkflowStep = `-- name: SetTaskWorkflowStep :exec
+UPDATE agent_task_queue SET workflow_step = $1 WHERE id = $2
+`
+
+type SetTaskWorkflowStepParams struct {
+ WorkflowStep pgtype.Text `json:"workflow_step"`
+ ID pgtype.UUID `json:"id"`
+}
+
+// Moves a run's workflow step along with a status change the run itself made
+// (MUL-7420). See migration 557.
+func (q *Queries) SetTaskWorkflowStep(ctx context.Context, arg SetTaskWorkflowStepParams) error {
+ _, err := q.db.Exec(ctx, setTaskWorkflowStep, arg.WorkflowStep, arg.ID)
+ return err
+}
+
const settleDelegatedFailureRecoveriesForTask = `-- name: SettleDelegatedFailureRecoveriesForTask :execrows
UPDATE comment recovery
SET recovery_settled_at = now()
@@ -8424,7 +8496,7 @@ SET status = 'running',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE agent_task_queue.id = $1 AND agent_task_queue.status IN ('dispatched', 'waiting_local_directory')
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
// Legacy single-winner transition; generation-aware callers lock the claim first.
@@ -8497,6 +8569,7 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index 20ff04b4a8..3e192dda5f 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -300,7 +300,7 @@ SELECT
$11,
COALESCE($12::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, NULL, $2)
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type CreateAutopilotTaskParams struct {
@@ -413,6 +413,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -938,7 +939,7 @@ func (q *Queries) GetAutopilotRunByWebhookDelivery(ctx context.Context, webhookD
}
const getAutopilotTaskByRun = `-- name: GetAutopilotTaskByRun :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, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot 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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue
WHERE autopilot_run_id = $1
ORDER BY created_at
LIMIT 1
@@ -1009,6 +1010,7 @@ func (q *Queries) GetAutopilotTaskByRun(ctx context.Context, autopilotRunID pgty
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 05f8710e1d..e1d467afc1 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -394,7 +394,7 @@ SELECT
$15::bigint,
COALESCE($16::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, NULL, $2)
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type CreateChatTaskParams struct {
@@ -503,6 +503,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -583,7 +584,7 @@ FROM (
WHERE task.id = $1
AND pending.max_until IS NOT NULL
AND (task.fire_at IS NULL OR task.fire_at < pending.max_until)
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step
`
// Closes the enqueue-vs-append race: under READ COMMITTED a media message can
@@ -655,6 +656,7 @@ func (q *Queries) DeferChatTaskForSealedPendingMedia(ctx context.Context, taskID
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -2987,7 +2989,7 @@ WHERE task.chat_session_id = $1
AND message.role = 'user'
AND message.channel_media_pending_until > now()
)
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step
`
// Media completion may race with the 3s run batcher. Promote every original
@@ -3065,6 +3067,7 @@ func (q *Queries) PromoteChannelChatTasksIfMediaReady(ctx context.Context, chatS
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -3496,7 +3499,7 @@ const setChatTaskInputOwnerSelf = `-- name: SetChatTaskInputOwnerSelf :one
UPDATE agent_task_queue
SET chat_input_task_id = id
WHERE id = $1
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
// Stamps a freshly-created direct-chat task as the owner of its own input batch
@@ -3569,6 +3572,7 @@ func (q *Queries) SetChatTaskInputOwnerSelf(ctx context.Context, id pgtype.UUID)
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
diff --git a/server/pkg/db/generated/issue_workflow.sql.go b/server/pkg/db/generated/issue_workflow.sql.go
new file mode 100644
index 0000000000..84996997bc
--- /dev/null
+++ b/server/pkg/db/generated/issue_workflow.sql.go
@@ -0,0 +1,649 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: issue_workflow.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const countProjectIssuesByStatus = `-- name: CountProjectIssuesByStatus :many
+SELECT status, COUNT(*)::bigint AS issue_count
+FROM issue
+WHERE workspace_id = $1::uuid
+ AND project_id = ANY($2::uuid[])
+GROUP BY status
+ORDER BY status
+`
+
+type CountProjectIssuesByStatusParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ProjectIds []pgtype.UUID `json:"project_ids"`
+}
+
+type CountProjectIssuesByStatusRow struct {
+ Status string `json:"status"`
+ IssueCount int64 `json:"issue_count"`
+}
+
+// Status census for a workflow switch or step removal, including terminal
+// issues: every issue of the project must end on a status its workflow lists.
+func (q *Queries) CountProjectIssuesByStatus(ctx context.Context, arg CountProjectIssuesByStatusParams) ([]CountProjectIssuesByStatusRow, error) {
+ rows, err := q.db.Query(ctx, countProjectIssuesByStatus, arg.WorkspaceID, arg.ProjectIds)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []CountProjectIssuesByStatusRow{}
+ for rows.Next() {
+ var i CountProjectIssuesByStatusRow
+ if err := rows.Scan(&i.Status, &i.IssueCount); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const createDefaultIssueWorkflow = `-- name: CreateDefaultIssueWorkflow :many
+INSERT INTO issue_workflow (workspace_id, name, description, initial_status_key, steps, is_default)
+VALUES (
+ $1::uuid,
+ 'Default',
+ '',
+ 'todo',
+ $2::jsonb,
+ true
+)
+ON CONFLICT (workspace_id) WHERE is_default DO NOTHING
+RETURNING id, workspace_id, name, description, initial_status_key, steps, created_at, updated_at, is_default
+`
+
+type CreateDefaultIssueWorkflowParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Steps []byte `json:"steps"`
+}
+
+// Returns no row when another request created the Default first.
+func (q *Queries) CreateDefaultIssueWorkflow(ctx context.Context, arg CreateDefaultIssueWorkflowParams) ([]IssueWorkflow, error) {
+ rows, err := q.db.Query(ctx, createDefaultIssueWorkflow, arg.WorkspaceID, arg.Steps)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []IssueWorkflow{}
+ for rows.Next() {
+ var i IssueWorkflow
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Description,
+ &i.InitialStatusKey,
+ &i.Steps,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.IsDefault,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const createIssueWorkflow = `-- name: CreateIssueWorkflow :one
+INSERT INTO issue_workflow (workspace_id, name, description, initial_status_key, steps)
+VALUES (
+ $1::uuid,
+ $2::text,
+ $3::text,
+ $4::text,
+ $5::jsonb
+)
+RETURNING id, workspace_id, name, description, initial_status_key, steps, created_at, updated_at, is_default
+`
+
+type CreateIssueWorkflowParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ InitialStatusKey string `json:"initial_status_key"`
+ Steps []byte `json:"steps"`
+}
+
+func (q *Queries) CreateIssueWorkflow(ctx context.Context, arg CreateIssueWorkflowParams) (IssueWorkflow, error) {
+ row := q.db.QueryRow(ctx, createIssueWorkflow,
+ arg.WorkspaceID,
+ arg.Name,
+ arg.Description,
+ arg.InitialStatusKey,
+ arg.Steps,
+ )
+ var i IssueWorkflow
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Description,
+ &i.InitialStatusKey,
+ &i.Steps,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.IsDefault,
+ )
+ return i, err
+}
+
+const deleteIssueWorkflow = `-- name: DeleteIssueWorkflow :execrows
+DELETE FROM issue_workflow
+WHERE id = $1::uuid
+ AND workspace_id = $2::uuid
+ AND NOT is_default
+`
+
+type DeleteIssueWorkflowParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) DeleteIssueWorkflow(ctx context.Context, arg DeleteIssueWorkflowParams) (int64, error) {
+ result, err := q.db.Exec(ctx, deleteIssueWorkflow, arg.ID, arg.WorkspaceID)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const deleteIssueWorkflowsForWorkspace = `-- name: DeleteIssueWorkflowsForWorkspace :exec
+DELETE FROM issue_workflow WHERE workspace_id = $1::uuid
+`
+
+// No foreign keys by project rule, so workspace teardown cleans up here.
+func (q *Queries) DeleteIssueWorkflowsForWorkspace(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteIssueWorkflowsForWorkspace, workspaceID)
+ return err
+}
+
+const getDefaultIssueWorkflow = `-- name: GetDefaultIssueWorkflow :one
+SELECT id, workspace_id, name, description, initial_status_key, steps, created_at, updated_at, is_default FROM issue_workflow
+WHERE workspace_id = $1::uuid
+ AND is_default
+`
+
+func (q *Queries) GetDefaultIssueWorkflow(ctx context.Context, workspaceID pgtype.UUID) (IssueWorkflow, error) {
+ row := q.db.QueryRow(ctx, getDefaultIssueWorkflow, workspaceID)
+ var i IssueWorkflow
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Description,
+ &i.InitialStatusKey,
+ &i.Steps,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.IsDefault,
+ )
+ return i, err
+}
+
+const getIssueWorkflow = `-- name: GetIssueWorkflow :one
+SELECT id, workspace_id, name, description, initial_status_key, steps, created_at, updated_at, is_default FROM issue_workflow
+WHERE id = $1::uuid
+ AND workspace_id = $2::uuid
+`
+
+type GetIssueWorkflowParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) GetIssueWorkflow(ctx context.Context, arg GetIssueWorkflowParams) (IssueWorkflow, error) {
+ row := q.db.QueryRow(ctx, getIssueWorkflow, arg.ID, arg.WorkspaceID)
+ var i IssueWorkflow
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Description,
+ &i.InitialStatusKey,
+ &i.Steps,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.IsDefault,
+ )
+ return i, err
+}
+
+const listIssueWorkflowNamesUsingStatusKey = `-- name: ListIssueWorkflowNamesUsingStatusKey :many
+SELECT name FROM issue_workflow
+WHERE workspace_id = $1::uuid
+ AND NOT is_default
+ AND steps @> jsonb_build_array(jsonb_build_object('status_key', $2::text))
+ORDER BY lower(name)
+`
+
+type ListIssueWorkflowNamesUsingStatusKeyParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ StatusKey string `json:"status_key"`
+}
+
+// Archive guard for the status catalog: a status a workflow still lists cannot
+// be retired, or that workflow's projects would lose a column.
+func (q *Queries) ListIssueWorkflowNamesUsingStatusKey(ctx context.Context, arg ListIssueWorkflowNamesUsingStatusKeyParams) ([]string, error) {
+ rows, err := q.db.Query(ctx, listIssueWorkflowNamesUsingStatusKey, arg.WorkspaceID, arg.StatusKey)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []string{}
+ for rows.Next() {
+ var name string
+ if err := rows.Scan(&name); err != nil {
+ return nil, err
+ }
+ items = append(items, name)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listIssueWorkflows = `-- name: ListIssueWorkflows :many
+
+SELECT id, workspace_id, name, description, initial_status_key, steps, created_at, updated_at, is_default FROM issue_workflow
+WHERE workspace_id = $1::uuid
+ORDER BY is_default DESC, lower(name), created_at, id
+`
+
+// Project workflows (MUL-7420). A workflow selects and orders statuses from
+// the workspace's issue_status catalog. Projects opt in through
+// project.workflow_id; a project without one uses the workspace's Default
+// workflow row. Each step also stores who an issue entering it is handed to.
+func (q *Queries) ListIssueWorkflows(ctx context.Context, workspaceID pgtype.UUID) ([]IssueWorkflow, error) {
+ rows, err := q.db.Query(ctx, listIssueWorkflows, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []IssueWorkflow{}
+ for rows.Next() {
+ var i IssueWorkflow
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Description,
+ &i.InitialStatusKey,
+ &i.Steps,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.IsDefault,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listNamedIssueWorkflowSteps = `-- name: ListNamedIssueWorkflowSteps :many
+SELECT steps FROM issue_workflow
+WHERE workspace_id = $1::uuid
+ AND NOT is_default
+`
+
+// The steps of every workflow except Default, for the Default snapshot.
+func (q *Queries) ListNamedIssueWorkflowSteps(ctx context.Context, workspaceID pgtype.UUID) ([][]byte, error) {
+ rows, err := q.db.Query(ctx, listNamedIssueWorkflowSteps, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := [][]byte{}
+ for rows.Next() {
+ var steps []byte
+ if err := rows.Scan(&steps); err != nil {
+ return nil, err
+ }
+ items = append(items, steps)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listProjectsUsingDefaultIssueWorkflow = `-- name: ListProjectsUsingDefaultIssueWorkflow :many
+SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id FROM project
+WHERE workspace_id = $1::uuid
+ AND workflow_id IS NULL
+ORDER BY created_at, id
+`
+
+func (q *Queries) ListProjectsUsingDefaultIssueWorkflow(ctx context.Context, workspaceID pgtype.UUID) ([]Project, error) {
+ rows, err := q.db.Query(ctx, listProjectsUsingDefaultIssueWorkflow, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Project{}
+ for rows.Next() {
+ var i Project
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Description,
+ &i.Icon,
+ &i.Status,
+ &i.LeadType,
+ &i.LeadID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Priority,
+ &i.StartDate,
+ &i.DueDate,
+ &i.WorkflowID,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listProjectsUsingIssueWorkflow = `-- name: ListProjectsUsingIssueWorkflow :many
+SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id FROM project
+WHERE workspace_id = $1::uuid
+ AND workflow_id = $2::uuid
+ORDER BY created_at, id
+`
+
+type ListProjectsUsingIssueWorkflowParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ WorkflowID pgtype.UUID `json:"workflow_id"`
+}
+
+func (q *Queries) ListProjectsUsingIssueWorkflow(ctx context.Context, arg ListProjectsUsingIssueWorkflowParams) ([]Project, error) {
+ rows, err := q.db.Query(ctx, listProjectsUsingIssueWorkflow, arg.WorkspaceID, arg.WorkflowID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Project{}
+ for rows.Next() {
+ var i Project
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Description,
+ &i.Icon,
+ &i.Status,
+ &i.LeadType,
+ &i.LeadID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Priority,
+ &i.StartDate,
+ &i.DueDate,
+ &i.WorkflowID,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const lockProjectForWorkflowChange = `-- name: LockProjectForWorkflowChange :one
+SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id FROM project
+WHERE id = $1::uuid
+ AND workspace_id = $2::uuid
+FOR UPDATE
+`
+
+type LockProjectForWorkflowChangeParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Serializes concurrent workflow switches of one project.
+func (q *Queries) LockProjectForWorkflowChange(ctx context.Context, arg LockProjectForWorkflowChangeParams) (Project, error) {
+ row := q.db.QueryRow(ctx, lockProjectForWorkflowChange, arg.ID, arg.WorkspaceID)
+ var i Project
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Description,
+ &i.Icon,
+ &i.Status,
+ &i.LeadType,
+ &i.LeadID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Priority,
+ &i.StartDate,
+ &i.DueDate,
+ &i.WorkflowID,
+ )
+ return i, err
+}
+
+const remapProjectIssueStatus = `-- name: RemapProjectIssueStatus :many
+UPDATE issue AS i SET
+ status = $1::text,
+ duplicate_of_issue_id = NULL,
+ position = (
+ SELECT COALESCE(MIN(target.position), 0) - 1
+ FROM issue AS target
+ WHERE target.workspace_id = i.workspace_id
+ AND target.status = $1::text
+ ),
+ revision = i.revision + 1,
+ last_activity_at = GREATEST(COALESCE(i.last_activity_at, i.updated_at), now()),
+ updated_at = now()
+WHERE i.workspace_id = $2::uuid
+ AND i.project_id = ANY($3::uuid[])
+ AND i.status = $4::text
+ AND i.status <> $1::text
+RETURNING i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state, i.duplicate_of_issue_id
+`
+
+type RemapProjectIssueStatusParams struct {
+ ToStatus string `json:"to_status"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ProjectIds []pgtype.UUID `json:"project_ids"`
+ FromStatus string `json:"from_status"`
+}
+
+// Moves every issue of the given projects from one status to another as part
+// of an administrative workflow change. Mirrors UpdateIssueStatus: the issue
+// is re-ranked to the top of its new column, the revision advances, and a
+// duplicate mark only survives cancelled -> cancelled (never the case here,
+// because from and to differ). It deliberately touches nothing else, so it
+// never hands an issue off or starts a run.
+func (q *Queries) RemapProjectIssueStatus(ctx context.Context, arg RemapProjectIssueStatusParams) ([]Issue, error) {
+ rows, err := q.db.Query(ctx, remapProjectIssueStatus,
+ arg.ToStatus,
+ arg.WorkspaceID,
+ arg.ProjectIds,
+ arg.FromStatus,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Issue{}
+ for rows.Next() {
+ var i Issue
+ if err := rows.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,
+ &i.FirstExecutedAt,
+ &i.StartDate,
+ &i.Metadata,
+ &i.Stage,
+ &i.Properties,
+ &i.Revision,
+ &i.LastActivityAt,
+ &i.TriageState,
+ &i.DuplicateOfIssueID,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const removeStatusFromDefaultIssueWorkflow = `-- name: RemoveStatusFromDefaultIssueWorkflow :exec
+UPDATE issue_workflow SET
+ steps = COALESCE((
+ SELECT jsonb_agg(step ORDER BY ord)
+ FROM jsonb_array_elements(steps) WITH ORDINALITY AS s(step, ord)
+ WHERE step->>'status_key' <> $1::text
+ ), '[]'::jsonb),
+ updated_at = now()
+WHERE workspace_id = $2::uuid
+ AND is_default
+ AND steps @> jsonb_build_array(jsonb_build_object('status_key', $1::text))
+`
+
+type RemoveStatusFromDefaultIssueWorkflowParams struct {
+ StatusKey string `json:"status_key"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// An archived status leaves Default with it; Default never blocks an archive.
+func (q *Queries) RemoveStatusFromDefaultIssueWorkflow(ctx context.Context, arg RemoveStatusFromDefaultIssueWorkflowParams) error {
+ _, err := q.db.Exec(ctx, removeStatusFromDefaultIssueWorkflow, arg.StatusKey, arg.WorkspaceID)
+ return err
+}
+
+const setProjectWorkflow = `-- name: SetProjectWorkflow :one
+UPDATE project SET
+ workflow_id = $1::uuid,
+ updated_at = now()
+WHERE id = $2::uuid
+ AND workspace_id = $3::uuid
+RETURNING id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id
+`
+
+type SetProjectWorkflowParams struct {
+ WorkflowID pgtype.UUID `json:"workflow_id"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) SetProjectWorkflow(ctx context.Context, arg SetProjectWorkflowParams) (Project, error) {
+ row := q.db.QueryRow(ctx, setProjectWorkflow, arg.WorkflowID, arg.ID, arg.WorkspaceID)
+ var i Project
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Description,
+ &i.Icon,
+ &i.Status,
+ &i.LeadType,
+ &i.LeadID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Priority,
+ &i.StartDate,
+ &i.DueDate,
+ &i.WorkflowID,
+ )
+ return i, err
+}
+
+const updateIssueWorkflow = `-- name: UpdateIssueWorkflow :one
+UPDATE issue_workflow SET
+ name = $1::text,
+ description = $2::text,
+ initial_status_key = $3::text,
+ steps = $4::jsonb,
+ updated_at = now()
+WHERE id = $5::uuid
+ AND workspace_id = $6::uuid
+RETURNING id, workspace_id, name, description, initial_status_key, steps, created_at, updated_at, is_default
+`
+
+type UpdateIssueWorkflowParams struct {
+ Name string `json:"name"`
+ Description string `json:"description"`
+ InitialStatusKey string `json:"initial_status_key"`
+ Steps []byte `json:"steps"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) UpdateIssueWorkflow(ctx context.Context, arg UpdateIssueWorkflowParams) (IssueWorkflow, error) {
+ row := q.db.QueryRow(ctx, updateIssueWorkflow,
+ arg.Name,
+ arg.Description,
+ arg.InitialStatusKey,
+ arg.Steps,
+ arg.ID,
+ arg.WorkspaceID,
+ )
+ var i IssueWorkflow
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Description,
+ &i.InitialStatusKey,
+ &i.Steps,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.IsDefault,
+ )
+ return i, err
+}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 87a89e51a5..13398e129a 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -178,6 +178,7 @@ type AgentTaskQueue struct {
CancelledByID pgtype.UUID `json:"cancelled_by_id"`
CancelledByName pgtype.Text `json:"cancelled_by_name"`
IssueSnapshot []byte `json:"issue_snapshot"`
+ WorkflowStep pgtype.Text `json:"workflow_step"`
}
type AgentToLabel struct {
@@ -1078,6 +1079,18 @@ type IssueWakeupReceipt struct {
CoalesceKey pgtype.Text `json:"coalesce_key"`
}
+type IssueWorkflow struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ InitialStatusKey string `json:"initial_status_key"`
+ Steps []byte `json:"steps"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ IsDefault bool `json:"is_default"`
+}
+
type LarkBindingToken struct {
TokenHash string `json:"token_hash"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
@@ -1333,6 +1346,7 @@ type Project struct {
Priority string `json:"priority"`
StartDate pgtype.Date `json:"start_date"`
DueDate pgtype.Date `json:"due_date"`
+ WorkflowID pgtype.UUID `json:"workflow_id"`
}
type ProjectResource struct {
diff --git a/server/pkg/db/generated/project.sql.go b/server/pkg/db/generated/project.sql.go
index cde98b6f8f..526fd18850 100644
--- a/server/pkg/db/generated/project.sql.go
+++ b/server/pkg/db/generated/project.sql.go
@@ -26,10 +26,10 @@ func (q *Queries) CountIssuesByProject(ctx context.Context, projectID pgtype.UUI
const createProject = `-- name: CreateProject :one
INSERT INTO project (
workspace_id, title, description, icon, status,
- lead_type, lead_id, priority, start_date, due_date
+ lead_type, lead_id, priority, start_date, due_date, workflow_id
) VALUES (
- $1, $2, $3, $4, $5, $6, $7, $8, $9, $10
-) RETURNING id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date
+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11
+) RETURNING id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id
`
type CreateProjectParams struct {
@@ -43,6 +43,7 @@ type CreateProjectParams struct {
Priority string `json:"priority"`
StartDate pgtype.Date `json:"start_date"`
DueDate pgtype.Date `json:"due_date"`
+ WorkflowID pgtype.UUID `json:"workflow_id"`
}
func (q *Queries) CreateProject(ctx context.Context, arg CreateProjectParams) (Project, error) {
@@ -57,6 +58,7 @@ func (q *Queries) CreateProject(ctx context.Context, arg CreateProjectParams) (P
arg.Priority,
arg.StartDate,
arg.DueDate,
+ arg.WorkflowID,
)
var i Project
err := row.Scan(
@@ -73,6 +75,7 @@ func (q *Queries) CreateProject(ctx context.Context, arg CreateProjectParams) (P
&i.Priority,
&i.StartDate,
&i.DueDate,
+ &i.WorkflowID,
)
return i, err
}
@@ -93,7 +96,7 @@ func (q *Queries) DeleteProject(ctx context.Context, arg DeleteProjectParams) er
}
const getProjectInWorkspace = `-- name: GetProjectInWorkspace :one
-SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date FROM project
+SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id FROM project
WHERE id = $1 AND workspace_id = $2
`
@@ -119,6 +122,7 @@ func (q *Queries) GetProjectInWorkspace(ctx context.Context, arg GetProjectInWor
&i.Priority,
&i.StartDate,
&i.DueDate,
+ &i.WorkflowID,
)
return i, err
}
@@ -166,7 +170,7 @@ func (q *Queries) GetProjectIssueStats(ctx context.Context, arg GetProjectIssueS
}
const listProjects = `-- name: ListProjects :many
-SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date FROM project
+SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id FROM project
WHERE workspace_id = $1
AND ($2::text IS NULL OR status = $2)
AND ($3::text IS NULL OR priority = $3)
@@ -202,6 +206,7 @@ func (q *Queries) ListProjects(ctx context.Context, arg ListProjectsParams) ([]P
&i.Priority,
&i.StartDate,
&i.DueDate,
+ &i.WorkflowID,
); err != nil {
return nil, err
}
@@ -266,7 +271,7 @@ UPDATE project SET
due_date = CASE WHEN $15::boolean THEN $16 ELSE due_date END,
updated_at = now()
WHERE id = $1
-RETURNING id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date
+RETURNING id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id
`
type UpdateProjectParams struct {
@@ -322,6 +327,7 @@ func (q *Queries) UpdateProject(ctx context.Context, arg UpdateProjectParams) (P
&i.Priority,
&i.StartDate,
&i.DueDate,
+ &i.WorkflowID,
)
return i, err
}
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index 361a2f5cc6..b0d972774e 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -17,7 +17,7 @@ SET status = 'cancelled', completed_at = now(),
cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULL
WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type CancelAgentTasksByRuntimeOrAgentParams struct {
@@ -116,6 +116,7 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -218,7 +219,7 @@ SET status = 'failed', completed_at = now(), error = 'runtime went offline',
FROM victims
WHERE task.id = victims.id
AND task.status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step
`
type FailTasksForOfflineRuntimesParams struct {
@@ -303,6 +304,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context, arg FailTasks
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/search_index.sql.go b/server/pkg/db/generated/search_index.sql.go
index ac7e999a34..dfeb4df22a 100644
--- a/server/pkg/db/generated/search_index.sql.go
+++ b/server/pkg/db/generated/search_index.sql.go
@@ -360,7 +360,7 @@ func (q *Queries) ListSearchIndexIssuesPage(ctx context.Context, arg ListSearchI
}
const listSearchIndexProjects = `-- name: ListSearchIndexProjects :many
-SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date FROM project
+SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id FROM project
WHERE workspace_id = $1
ORDER BY id
`
@@ -388,6 +388,7 @@ func (q *Queries) ListSearchIndexProjects(ctx context.Context, workspaceID pgtyp
&i.Priority,
&i.StartDate,
&i.DueDate,
+ &i.WorkflowID,
); err != nil {
return nil, err
}
@@ -400,7 +401,7 @@ func (q *Queries) ListSearchIndexProjects(ctx context.Context, workspaceID pgtyp
}
const listSearchIndexProjectsByIDs = `-- name: ListSearchIndexProjectsByIDs :many
-SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date FROM project
+SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id FROM project
WHERE workspace_id = $1 AND id = ANY($2::uuid[])
`
@@ -432,6 +433,7 @@ func (q *Queries) ListSearchIndexProjectsByIDs(ctx context.Context, arg ListSear
&i.Priority,
&i.StartDate,
&i.DueDate,
+ &i.WorkflowID,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/supplement.sql.go b/server/pkg/db/generated/supplement.sql.go
index 5ebd1c864e..5e6d1bd80e 100644
--- a/server/pkg/db/generated/supplement.sql.go
+++ b/server/pkg/db/generated/supplement.sql.go
@@ -751,7 +751,7 @@ WHERE t.id = candidate.id
-- Reference the data-modifying CTE explicitly: capability persistence and
-- the returned running row are one indivisible statement.
AND (SELECT count(*) FROM capability) >= 0
-RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision, t.comment_thread_id, t.cancelled_by_type, t.cancelled_by_id, t.cancelled_by_name, t.issue_snapshot
+RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision, t.comment_thread_id, t.cancelled_by_type, t.cancelled_by_id, t.cancelled_by_name, t.issue_snapshot, t.workflow_step
`
type StartAgentTaskWithSupplementParams struct {
@@ -825,6 +825,7 @@ func (q *Queries) StartAgentTaskWithSupplement(ctx context.Context, arg StartAge
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
diff --git a/server/pkg/db/generated/wakeup.sql.go b/server/pkg/db/generated/wakeup.sql.go
index dc5e5503d1..40282ae666 100644
--- a/server/pkg/db/generated/wakeup.sql.go
+++ b/server/pkg/db/generated/wakeup.sql.go
@@ -37,7 +37,7 @@ func (q *Queries) AdvanceIssueWakeup(ctx context.Context, arg AdvanceIssueWakeup
const cancelUnstartedIssueWakeupTasks = `-- name: CancelUnstartedIssueWakeupTasks :many
UPDATE agent_task_queue SET status='cancelled',completed_at=now(),error='Issue closed; wakeup disabled'
-WHERE issue_id= $1 AND context->>'wakeup_id' IS NOT NULL AND status IN ('queued','deferred') AND started_at IS NULL 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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+WHERE issue_id= $1 AND context->>'wakeup_id' IS NOT NULL AND status IN ('queued','deferred') AND started_at IS NULL 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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
func (q *Queries) CancelUnstartedIssueWakeupTasks(ctx context.Context, issueID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -109,6 +109,7 @@ func (q *Queries) CancelUnstartedIssueWakeupTasks(ctx context.Context, issueID p
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -122,7 +123,7 @@ func (q *Queries) CancelUnstartedIssueWakeupTasks(ctx context.Context, issueID p
const cancelUnstartedWakeupTasks = `-- name: CancelUnstartedWakeupTasks :many
UPDATE agent_task_queue SET status='cancelled',completed_at=now(),error='Wakeup disabled or updated'
-WHERE context->>'wakeup_id'= $1::text AND status IN ('queued','deferred') AND started_at IS NULL 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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+WHERE context->>'wakeup_id'= $1::text AND status IN ('queued','deferred') AND started_at IS NULL 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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
func (q *Queries) CancelUnstartedWakeupTasks(ctx context.Context, wakeupID string) ([]AgentTaskQueue, error) {
@@ -194,6 +195,7 @@ func (q *Queries) CancelUnstartedWakeupTasks(ctx context.Context, wakeupID strin
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
); err != nil {
return nil, err
}
@@ -373,7 +375,7 @@ INSERT INTO agent_task_queue (
coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,
squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id, trigger_evidence_kind, trigger_evidence_ref_id,
- id
+ workflow_step, id
)
SELECT
$1, $2, $3, 'queued', $4, $5,
@@ -398,9 +400,17 @@ SELECT
$21,
$22,
$23,
+ -- The workflow step this run works on (MUL-7420). A wakeup continues the
+ -- run that registered it, so it keeps that run's step: a status change it
+ -- makes after someone else moved the issue is refused like the run's own
+ -- would be. A wakeup a member registered starts from the issue's status.
+ COALESCE(
+ (SELECT s.workflow_step FROM agent_task_queue s WHERE s.id = $19 AND s.issue_id = $3),
+ (SELECT i.status FROM issue i WHERE i.id = $3)
+ ),
COALESCE($24::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
-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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type CreateWakeupTaskParams struct {
@@ -536,6 +546,7 @@ func (q *Queries) CreateWakeupTask(ctx context.Context, arg CreateWakeupTaskPara
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -605,7 +616,7 @@ func (q *Queries) DiscardWakeupReceipts(ctx context.Context, id pgtype.UUID) err
}
const findPendingWakeupTask = `-- name: FindPendingWakeupTask :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, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot FROM agent_task_queue WHERE context->>'wakeup_id'= $1::text AND status IN ('queued','dispatched') ORDER BY created_at LIMIT 1 FOR UPDATE
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue WHERE context->>'wakeup_id'= $1::text AND status IN ('queued','dispatched') ORDER BY created_at LIMIT 1 FOR UPDATE
`
func (q *Queries) FindPendingWakeupTask(ctx context.Context, wakeupID string) (AgentTaskQueue, error) {
@@ -671,6 +682,7 @@ func (q *Queries) FindPendingWakeupTask(ctx context.Context, wakeupID string) (A
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -1531,7 +1543,7 @@ func (q *Queries) LockWakeupIssue(ctx context.Context, id pgtype.UUID) (Issue, e
}
const lockWakeupSourceTask = `-- name: LockWakeupSourceTask :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, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot FROM agent_task_queue WHERE id= $1 AND issue_id= $2 FOR UPDATE NOWAIT
+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue WHERE id= $1 AND issue_id= $2 FOR UPDATE NOWAIT
`
type LockWakeupSourceTaskParams struct {
@@ -1602,6 +1614,7 @@ func (q *Queries) LockWakeupSourceTask(ctx context.Context, arg LockWakeupSource
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -1751,7 +1764,7 @@ func (q *Queries) ReleaseWakeupReceipts(ctx context.Context, ids []pgtype.UUID)
}
const replaceWakeupEvidence = `-- name: ReplaceWakeupEvidence :one
-UPDATE agent_task_queue SET handoff_note=$1, context=COALESCE(context,'{}'::jsonb) || jsonb_build_object('wakeup_evidence', $2::jsonb) WHERE id= $3 AND status='queued' 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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+UPDATE agent_task_queue SET handoff_note=$1, context=COALESCE(context,'{}'::jsonb) || jsonb_build_object('wakeup_evidence', $2::jsonb) WHERE id= $3 AND status='queued' 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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type ReplaceWakeupEvidenceParams struct {
@@ -1823,6 +1836,7 @@ func (q *Queries) ReplaceWakeupEvidence(ctx context.Context, arg ReplaceWakeupEv
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
@@ -1845,7 +1859,7 @@ func (q *Queries) ReserveWakeupReceipts(ctx context.Context, arg ReserveWakeupRe
const setClaimedTaskContext = `-- name: SetClaimedTaskContext :one
UPDATE agent_task_queue SET context= $1::jsonb
-WHERE id= $2 AND status='dispatched' AND dispatched_at= $3 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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
+WHERE id= $2 AND status='dispatched' AND dispatched_at= $3 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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type SetClaimedTaskContextParams struct {
@@ -1918,6 +1932,7 @@ func (q *Queries) SetClaimedTaskContext(ctx context.Context, arg SetClaimedTaskC
&i.CancelledByID,
&i.CancelledByName,
&i.IssueSnapshot,
+ &i.WorkflowStep,
)
return i, err
}
diff --git a/server/pkg/db/queries/activity.sql b/server/pkg/db/queries/activity.sql
index 6a1dde26c7..5a3d48adb3 100644
--- a/server/pkg/db/queries/activity.sql
+++ b/server/pkg/db/queries/activity.sql
@@ -58,3 +58,11 @@ WHERE workspace_id = $1
AND details->>'to_type' IS NOT NULL
AND details->>'to_id' IS NOT NULL
GROUP BY details->>'to_type', details->>'to_id';
+
+-- name: GetLastIssueStatusChange :one
+-- Who last changed an issue's status, and to what: names the mover when an
+-- agent's status change is refused because the issue left its step (MUL-7420).
+SELECT actor_type, actor_id FROM activity_log
+WHERE issue_id = @issue_id AND action = 'status_changed'
+ORDER BY created_at DESC, id DESC
+LIMIT 1;
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 79efac26af..c0bf634d04 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -320,7 +320,7 @@ INSERT INTO agent_task_queue (
coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,
squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id, trigger_evidence_kind, trigger_evidence_ref_id,
- id
+ workflow_step, id
)
SELECT
$1, $2, $3, 'queued', $4, sqlc.narg(trigger_comment_id),
@@ -345,6 +345,8 @@ SELECT
sqlc.narg(rerun_of_task_id),
sqlc.narg(trigger_evidence_kind),
sqlc.narg(trigger_evidence_ref_id),
+ -- The issue's status as this task is queued: the workflow step it works on (MUL-7420).
+ (SELECT i.status FROM issue i WHERE i.id = $3),
COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
RETURNING *;
@@ -363,7 +365,7 @@ INSERT INTO agent_task_queue (
squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id,
trigger_evidence_kind, trigger_evidence_ref_id, fire_at,
- id
+ workflow_step, id
)
SELECT
$1, $2, $3, 'deferred', $4, sqlc.narg(trigger_comment_id),
@@ -388,6 +390,8 @@ SELECT
sqlc.narg(trigger_evidence_kind),
sqlc.narg(trigger_evidence_ref_id),
@fire_at,
+ -- The issue's status as this task is queued: the workflow step it works on (MUL-7420).
+ (SELECT i.status FROM issue i WHERE i.id = $3),
COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
RETURNING *;
@@ -484,7 +488,7 @@ INSERT INTO agent_task_queue (
originator_source, delegated_from_task_id, rule_version_id,
trigger_evidence_kind, trigger_evidence_ref_id, retry_of_task_id,
chat_input_task_id, fire_at,
- channel_context_revision, handoff_note, id
+ channel_context_revision, handoff_note, workflow_step, id
)
SELECT
p.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,
@@ -505,7 +509,11 @@ SELECT
p.trigger_evidence_kind, p.trigger_evidence_ref_id, p.id,
p.chat_input_task_id, sqlc.narg(fire_at),
p.channel_context_revision,
- CASE WHEN p.context->>'wakeup_id' IS NOT NULL THEN p.handoff_note END,
+ -- Carried for a wakeup's prompt and a workflow handoff's brief (MUL-7420);
+ -- rows from before workflow_step existed may hold a retired assignment note.
+ CASE WHEN p.context->>'wakeup_id' IS NOT NULL OR p.workflow_step IS NOT NULL THEN p.handoff_note END,
+ -- A retry continues its parent's work, so it keeps the parent's step (MUL-7420).
+ p.workflow_step,
-- Named new_task_id, not id: $1 above is the PARENT task's id.
COALESCE(sqlc.narg('new_task_id')::uuid, gen_random_uuid())
FROM agent_task_queue p
@@ -516,6 +524,11 @@ ON CONFLICT (issue_id, agent_id, (COALESCE(comment_thread_id, '00000000-0000-000
DO NOTHING
RETURNING *;
+-- name: SetTaskWorkflowStep :exec
+-- Moves a run's workflow step along with a status change the run itself made
+-- (MUL-7420). See migration 557.
+UPDATE agent_task_queue SET workflow_step = @workflow_step WHERE id = @id;
+
-- name: CreateManualQuickCreateRetryTask :one
-- A human retry of an issue-less quick-create is a new direct_human run, not
-- an automatic retry. It preserves the immutable quick-create context JSON
diff --git a/server/pkg/db/queries/issue_workflow.sql b/server/pkg/db/queries/issue_workflow.sql
new file mode 100644
index 0000000000..b1bd34b05f
--- /dev/null
+++ b/server/pkg/db/queries/issue_workflow.sql
@@ -0,0 +1,155 @@
+-- Project workflows (MUL-7420). A workflow selects and orders statuses from
+-- the workspace's issue_status catalog. Projects opt in through
+-- project.workflow_id; a project without one uses the workspace's Default
+-- workflow row. Each step also stores who an issue entering it is handed to.
+
+-- name: ListIssueWorkflows :many
+SELECT * FROM issue_workflow
+WHERE workspace_id = sqlc.arg('workspace_id')::uuid
+ORDER BY is_default DESC, lower(name), created_at, id;
+
+-- name: GetDefaultIssueWorkflow :one
+SELECT * FROM issue_workflow
+WHERE workspace_id = sqlc.arg('workspace_id')::uuid
+ AND is_default;
+
+-- name: CreateDefaultIssueWorkflow :many
+-- Returns no row when another request created the Default first.
+INSERT INTO issue_workflow (workspace_id, name, description, initial_status_key, steps, is_default)
+VALUES (
+ sqlc.arg('workspace_id')::uuid,
+ 'Default',
+ '',
+ 'todo',
+ sqlc.arg('steps')::jsonb,
+ true
+)
+ON CONFLICT (workspace_id) WHERE is_default DO NOTHING
+RETURNING *;
+
+-- name: ListNamedIssueWorkflowSteps :many
+-- The steps of every workflow except Default, for the Default snapshot.
+SELECT steps FROM issue_workflow
+WHERE workspace_id = sqlc.arg('workspace_id')::uuid
+ AND NOT is_default;
+
+-- name: RemoveStatusFromDefaultIssueWorkflow :exec
+-- An archived status leaves Default with it; Default never blocks an archive.
+UPDATE issue_workflow SET
+ steps = COALESCE((
+ SELECT jsonb_agg(step ORDER BY ord)
+ FROM jsonb_array_elements(steps) WITH ORDINALITY AS s(step, ord)
+ WHERE step->>'status_key' <> sqlc.arg('status_key')::text
+ ), '[]'::jsonb),
+ updated_at = now()
+WHERE workspace_id = sqlc.arg('workspace_id')::uuid
+ AND is_default
+ AND steps @> jsonb_build_array(jsonb_build_object('status_key', sqlc.arg('status_key')::text));
+
+-- name: ListProjectsUsingDefaultIssueWorkflow :many
+SELECT * FROM project
+WHERE workspace_id = sqlc.arg('workspace_id')::uuid
+ AND workflow_id IS NULL
+ORDER BY created_at, id;
+
+-- name: GetIssueWorkflow :one
+SELECT * FROM issue_workflow
+WHERE id = sqlc.arg('id')::uuid
+ AND workspace_id = sqlc.arg('workspace_id')::uuid;
+
+-- name: CreateIssueWorkflow :one
+INSERT INTO issue_workflow (workspace_id, name, description, initial_status_key, steps)
+VALUES (
+ sqlc.arg('workspace_id')::uuid,
+ sqlc.arg('name')::text,
+ sqlc.arg('description')::text,
+ sqlc.arg('initial_status_key')::text,
+ sqlc.arg('steps')::jsonb
+)
+RETURNING *;
+
+-- name: UpdateIssueWorkflow :one
+UPDATE issue_workflow SET
+ name = sqlc.arg('name')::text,
+ description = sqlc.arg('description')::text,
+ initial_status_key = sqlc.arg('initial_status_key')::text,
+ steps = sqlc.arg('steps')::jsonb,
+ updated_at = now()
+WHERE id = sqlc.arg('id')::uuid
+ AND workspace_id = sqlc.arg('workspace_id')::uuid
+RETURNING *;
+
+-- name: DeleteIssueWorkflow :execrows
+DELETE FROM issue_workflow
+WHERE id = sqlc.arg('id')::uuid
+ AND workspace_id = sqlc.arg('workspace_id')::uuid
+ AND NOT is_default;
+
+-- name: DeleteIssueWorkflowsForWorkspace :exec
+-- No foreign keys by project rule, so workspace teardown cleans up here.
+DELETE FROM issue_workflow WHERE workspace_id = sqlc.arg('workspace_id')::uuid;
+
+-- name: ListIssueWorkflowNamesUsingStatusKey :many
+-- Archive guard for the status catalog: a status a workflow still lists cannot
+-- be retired, or that workflow's projects would lose a column.
+SELECT name FROM issue_workflow
+WHERE workspace_id = sqlc.arg('workspace_id')::uuid
+ AND NOT is_default
+ AND steps @> jsonb_build_array(jsonb_build_object('status_key', sqlc.arg('status_key')::text))
+ORDER BY lower(name);
+
+-- name: ListProjectsUsingIssueWorkflow :many
+SELECT * FROM project
+WHERE workspace_id = sqlc.arg('workspace_id')::uuid
+ AND workflow_id = sqlc.arg('workflow_id')::uuid
+ORDER BY created_at, id;
+
+-- name: CountProjectIssuesByStatus :many
+-- Status census for a workflow switch or step removal, including terminal
+-- issues: every issue of the project must end on a status its workflow lists.
+SELECT status, COUNT(*)::bigint AS issue_count
+FROM issue
+WHERE workspace_id = sqlc.arg('workspace_id')::uuid
+ AND project_id = ANY(sqlc.arg('project_ids')::uuid[])
+GROUP BY status
+ORDER BY status;
+
+-- name: RemapProjectIssueStatus :many
+-- Moves every issue of the given projects from one status to another as part
+-- of an administrative workflow change. Mirrors UpdateIssueStatus: the issue
+-- is re-ranked to the top of its new column, the revision advances, and a
+-- duplicate mark only survives cancelled -> cancelled (never the case here,
+-- because from and to differ). It deliberately touches nothing else, so it
+-- never hands an issue off or starts a run.
+UPDATE issue AS i SET
+ status = sqlc.arg('to_status')::text,
+ duplicate_of_issue_id = NULL,
+ position = (
+ SELECT COALESCE(MIN(target.position), 0) - 1
+ FROM issue AS target
+ WHERE target.workspace_id = i.workspace_id
+ AND target.status = sqlc.arg('to_status')::text
+ ),
+ revision = i.revision + 1,
+ last_activity_at = GREATEST(COALESCE(i.last_activity_at, i.updated_at), now()),
+ updated_at = now()
+WHERE i.workspace_id = sqlc.arg('workspace_id')::uuid
+ AND i.project_id = ANY(sqlc.arg('project_ids')::uuid[])
+ AND i.status = sqlc.arg('from_status')::text
+ AND i.status <> sqlc.arg('to_status')::text
+RETURNING i.*;
+
+-- name: LockProjectForWorkflowChange :one
+-- Serializes concurrent workflow switches of one project.
+SELECT * FROM project
+WHERE id = sqlc.arg('id')::uuid
+ AND workspace_id = sqlc.arg('workspace_id')::uuid
+FOR UPDATE;
+
+-- name: SetProjectWorkflow :one
+UPDATE project SET
+ workflow_id = sqlc.narg('workflow_id')::uuid,
+ updated_at = now()
+WHERE id = sqlc.arg('id')::uuid
+ AND workspace_id = sqlc.arg('workspace_id')::uuid
+RETURNING *;
diff --git a/server/pkg/db/queries/project.sql b/server/pkg/db/queries/project.sql
index cdb5a46bba..5236ed26a9 100644
--- a/server/pkg/db/queries/project.sql
+++ b/server/pkg/db/queries/project.sql
@@ -26,9 +26,9 @@ FOR UPDATE;
-- name: CreateProject :one
INSERT INTO project (
workspace_id, title, description, icon, status,
- lead_type, lead_id, priority, start_date, due_date
+ lead_type, lead_id, priority, start_date, due_date, workflow_id
) VALUES (
- $1, $2, $3, $4, $5, $6, $7, $8, $9, $10
+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11
) RETURNING *;
-- name: UpdateProject :one
diff --git a/server/pkg/db/queries/wakeup.sql b/server/pkg/db/queries/wakeup.sql
index 80048c0c5d..42ad9f7492 100644
--- a/server/pkg/db/queries/wakeup.sql
+++ b/server/pkg/db/queries/wakeup.sql
@@ -177,7 +177,7 @@ INSERT INTO agent_task_queue (
coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,
squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id, trigger_evidence_kind, trigger_evidence_ref_id,
- id
+ workflow_step, id
)
SELECT
$1, $2, $3, 'queued', $4, sqlc.narg(trigger_comment_id),
@@ -202,6 +202,14 @@ SELECT
sqlc.narg(rerun_of_task_id),
sqlc.narg(trigger_evidence_kind),
sqlc.narg(trigger_evidence_ref_id),
+ -- The workflow step this run works on (MUL-7420). A wakeup continues the
+ -- run that registered it, so it keeps that run's step: a status change it
+ -- makes after someone else moved the issue is refused like the run's own
+ -- would be. A wakeup a member registered starts from the issue's status.
+ COALESCE(
+ (SELECT s.workflow_step FROM agent_task_queue s WHERE s.id = sqlc.narg(delegated_from_task_id) AND s.issue_id = $3),
+ (SELECT i.status FROM issue i WHERE i.id = $3)
+ ),
COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
RETURNING *;
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index ca215896c0..03ee83f0cb 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -119,6 +119,12 @@ const (
// self-describing); nothing routes on it.
EventIssueStatusChanged = "issue_status:changed"
+ // Project workflow events (MUL-7420). Same shape as the status catalog
+ // event: workflows are read as one list, so every write answers the same
+ // way — re-read it. A project switching workflows publishes
+ // project:updated instead.
+ EventIssueWorkflowChanged = "issue_workflow:changed"
+
// Pin events
EventPinCreated = "pin:created"
EventPinDeleted = "pin:deleted"