Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8250: feat(issues): statuses follow the issue's workflow, Default included (#9540)
Jiayuan Zhang5a2cc891ac33
diff --git a/packages/core/issue-workflows/index.ts b/packages/core/issue-workflows/index.tsindex e47d60d56c..c1efc485bf 100644--- a/packages/core/issue-workflows/index.ts+++ b/packages/core/issue-workflows/index.ts@@ -2,6 +2,7 @@ export {issueWorkflowKeys,issueWorkflowListOptions,resolveProjectWorkflow,+ issueStatusWorkflow,sharedWorkflowStatusKeys,defaultWorkflow,isFixedWorkflowStatus,diff --git a/packages/core/issue-workflows/queries.test.ts b/packages/core/issue-workflows/queries.test.tsindex 3702a5db80..0e8361199a 100644--- a/packages/core/issue-workflows/queries.test.ts+++ b/packages/core/issue-workflows/queries.test.ts@@ -2,8 +2,10 @@import { describe, expect, it } from "vitest";import type { IssueWorkflow, IssueWorkflowStep } from "../types";import {+ issueStatusWorkflow,projectMoveMayHandOff,resolveProjectWorkflow,+ sharedWorkflowStatusKeys,stepHandsOff,statusAcceptsHandoff,workflowAllowsStatus,@@ -64,10 +66,36 @@ describe("project workflow resolution (MUL-7420)", () => {});});+describe("issue status workflow (MUL-8250)", () => {+ const projects = [+ { id: "p-content", workflow_id: "wf-content" },+ { id: "p-default", workflow_id: null },+ ];++ it("uses Default outside a project and the project's workflow inside one", () => {+ const workflows = [defaultWorkflow, content];+ expect(issueStatusWorkflow(workflows, projects, { project_id: null })?.id).toBe("wf-default");+ expect(issueStatusWorkflow(workflows, projects, { project_id: "p-content" })?.id).toBe("wf-content");+ expect(issueStatusWorkflow(workflows, projects, { project_id: "p-default" })?.id).toBe("wf-default");+ expect(issueStatusWorkflow(workflows, undefined, { project_id: "p-content" })).toBeNull();+ expect(issueStatusWorkflow(undefined, projects, { project_id: null })).toBeNull();+ });++ it("limits a batch to the statuses every issue's workflow lists, Default included", () => {+ const workflows = [defaultWorkflow, content];+ const outside = sharedWorkflowStatusKeys(workflows, projects, [{ project_id: null }]);+ expect(outside && [...outside]).toEqual(["backlog", "todo", "in_progress", "in_review", "blocked", "done", "cancelled"]);+ const mixed = sharedWorkflowStatusKeys(workflows, projects, [{ project_id: null }, { project_id: "p-content" }]);+ expect(mixed && [...mixed]).toEqual(["backlog", "todo", "blocked", "done", "cancelled"]);+ expect(sharedWorkflowStatusKeys(undefined, projects, [{ project_id: null }])).toBeNull();+ });+});+describe("workflow helpers (MUL-7420)", () => {- it("allows any status under Default and only listed ones under a named workflow", () => {+ it("allows only the statuses a workflow lists, Default included", () => {expect(workflowAllowsStatus(null, "drafting")).toBe(true);- expect(workflowAllowsStatus(defaultWorkflow, "drafting")).toBe(true);+ expect(workflowAllowsStatus(defaultWorkflow, "drafting")).toBe(false);+ expect(workflowAllowsStatus(defaultWorkflow, "in_review")).toBe(true);expect(workflowAllowsStatus(content, "drafting")).toBe(true);expect(workflowAllowsStatus(content, "in_progress")).toBe(false);});@@ -110,4 +138,10 @@ describe("projectMoveMayHandOff", () => {it("never asks without a workflow", () => {expect(projectMoveMayHandOff(null, "todo")).toBe(false);});++ it("keeps the issue's status on a move into Default, listed or not", () => {+ const reviewing = { ...defaultWorkflow, steps: defaultWorkflow.steps.map((s) => (s.status_key === "in_review" ? lead : s)) };+ expect(projectMoveMayHandOff(reviewing, "drafting")).toBe(false);+ expect(projectMoveMayHandOff(reviewing, "in_review")).toBe(true);+ });});diff --git a/packages/core/issue-workflows/queries.ts b/packages/core/issue-workflows/queries.tsindex 418f742f25..dc92578e75 100644--- a/packages/core/issue-workflows/queries.ts+++ b/packages/core/issue-workflows/queries.ts@@ -105,11 +105,26 @@ export function resolveProjectWorkflow(return named ?? defaultWorkflow(workflows);}+/**+ * The workflow whose statuses an issue may take: its project's, or Default+ * for an issue outside any project. Only for statuses — outside a project+ * nothing hands off, so handoffs still come from `resolveProjectWorkflow`.+ * Null while workflows or the issue's project are unknown. (MUL-8250)+ */+export function issueStatusWorkflow(+ workflows: readonly IssueWorkflow[] | undefined,+ projects: readonly Pick<Project, "id" | "workflow_id">[] | undefined,+ issue: { project_id: string | null },+): IssueWorkflow | null {+ if (!issue.project_id) return defaultWorkflow(workflows);+ return resolveProjectWorkflow(workflows, projects?.find((p) => p.id === issue.project_id));+}+/*** 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.+ * Each issue takes its workflow's statuses, Default's outside a project, as+ * the server enforces. A batch status change offers this set, so it never+ * shows a status the server would skip.*/export function sharedWorkflowStatusKeys(workflows: readonly IssueWorkflow[] | undefined,@@ -118,9 +133,8 @@ export function sharedWorkflowStatusKeys(): 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 workflow = issueStatusWorkflow(workflows, projects, issue);+ if (!workflow) continue;const keys = new Set(workflow.steps.map((s) => s.status_key));shared = shared ? new Set([...shared].filter((key) => keys.has(key))) : keys;}@@ -140,15 +154,16 @@ export function stepHandsOff(step: IssueWorkflowStep | undefined): boolean {}/**- * 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.+ * Whether issues on `workflow` may enter a status: the ones it lists, Default+ * included (MUL-8250). An issue already on a status its workflow no longer+ * lists keeps it, so callers exempt the issue's current status. Null —+ * workflows still loading — allows every status.*/export function workflowAllowsStatus(workflow: IssueWorkflow | null | undefined,statusKey: string,): boolean {- if (!workflow || workflow.is_default) return true;+ if (!workflow) return true;return workflow.steps.some((s) => s.status_key === statusKey);}@@ -160,7 +175,10 @@ export function workflowAllowsStatus(*/export function projectMoveMayHandOff(workflow: IssueWorkflow | null | undefined, statusKey: string): boolean {if (!workflow) return false;- if (workflowAllowsStatus(workflow, statusKey)) return stepHandsOff(workflowStep(workflow, statusKey));+ // A move into a Default project keeps the issue's status, listed or not.+ if (workflow.is_default || workflowAllowsStatus(workflow, statusKey)) {+ return stepHandsOff(workflowStep(workflow, statusKey));+ }return workflow.steps.some(stepHandsOff);}diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 0e7ad896f5..660359c837 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -893,6 +893,9 @@ export function useRealtimeSync(const wsId = getCurrentWsId();if (wsId) {qc.invalidateQueries({ queryKey: issueStatusKeys.all(wsId) });+ // Creating or archiving a status also adds it to, or drops it from,+ // the stored Default workflow.+ qc.invalidateQueries({ queryKey: issueWorkflowKeys.all(wsId) });// Status-group order is server-owned and depends on catalog positions.// Rows/facets and unrelated groupings do not change on catalog edits.qc.invalidateQueries({diff --git a/packages/views/issues/components/batch-action-toolbar.test.tsx b/packages/views/issues/components/batch-action-toolbar.test.tsxindex 5dc079b49d..dd95a9e06d 100644--- a/packages/views/issues/components/batch-action-toolbar.test.tsx+++ b/packages/views/issues/components/batch-action-toolbar.test.tsx@@ -184,13 +184,13 @@ describe("BatchActionToolbar picker wiring", () => {expect(screen.getByTestId("status-picker")).toHaveAttribute("data-allowed", "done,todo");});- it("offers every status when no selected issue has a named workflow", () => {+ it("offers Default's statuses for issues on Default or outside any project (MUL-8250)", () => {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__");+ expect(screen.getByTestId("status-picker")).toHaveAttribute("data-allowed", "done,in_progress,todo");});it("renders nothing when nothing is selected", () => {diff --git a/packages/views/issues/components/board-view.tsx b/packages/views/issues/components/board-view.tsxindex 5e0346a928..47877f5cc2 100644--- a/packages/views/issues/components/board-view.tsx+++ b/packages/views/issues/components/board-view.tsx@@ -33,6 +33,7 @@ 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 {+ issueStatusWorkflow,resolveProjectWorkflow,stepHandsOff,useIssueWorkflows,@@ -503,8 +504,15 @@ function BoardViewImpl({},[workflows, workspaceProjects],);+ // Which statuses a card may move to: its project's workflow, or Default+ // outside a project, where nothing hands off. (MUL-8250)+ const statusWorkflowOfIssue = useCallback(+ (issue: Issue | null | undefined) => (issue ? issueStatusWorkflow(workflows, workspaceProjects, issue) : null),+ [workflows, workspaceProjects],+ );const scopeProject = projectId ? workspaceProjects?.find((p) => p.id === projectId) ?? null : null;const activeWorkflow = workflowOfIssue(activeIssue);+ const activeStatusWorkflow = statusWorkflowOfIssue(activeIssue);const activeProject = activeIssue?.project_id? workspaceProjects?.find((p) => p.id === activeIssue.project_id) ?? null: null;@@ -514,8 +522,8 @@ function BoardViewImpl({scopeWorkflow: resolveProjectWorkflow(workflows, scopeProject),scopeProject,dropBlockedReason: (status) =>- activeWorkflow && activeIssue?.status !== status && !workflowAllowsStatus(activeWorkflow, status)- ? t(($) => $.workflows.not_in_workflow, { name: activeWorkflow.name })+ activeStatusWorkflow && activeIssue?.status !== status && !workflowAllowsStatus(activeStatusWorkflow, status)+ ? t(($) => $.workflows.not_in_workflow, { name: activeStatusWorkflow.name }): null,dropHint: (status) => {if (!activeWorkflow || activeIssue?.status === status) return null;@@ -526,7 +534,7 @@ function BoardViewImpl({return { name, actor, run: actor ? actor.type !== "member" : step.handler.type === "creator" };},}),- [activeHandlerLabel, activeIssue?.status, activeProject, activeWorkflow, scopeProject, t, workflows],+ [activeHandlerLabel, activeIssue?.status, activeProject, activeStatusWorkflow, 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@@ -604,7 +612,12 @@ 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)) {+ const dragged = issueMapRef.current.get(activeId);+ if (+ targetStatus &&+ dragged?.status !== targetStatus &&+ !workflowAllowsStatus(statusWorkflowOfIssue(dragged), targetStatus)+ ) {return prev;}@@ -619,7 +632,7 @@ function BoardViewImpl({return { ...prev, [activeCol]: oldIds, [overCol]: newIds };});},- [groupIds, groups, catalog, sortBy, recentlyMovedRef, setColumns, workflowOfIssue],+ [groupIds, groups, catalog, sortBy, recentlyMovedRef, setColumns, statusWorkflowOfIssue],);const handleDragEnd = useCallback(@@ -679,17 +692,18 @@ function BoardViewImpl({return;}const movingWorkflow = workflowOfIssue(map.get(activeId));+ const movingStatusWorkflow = statusWorkflowOfIssue(map.get(activeId));if (finalGroup.status &&- movingWorkflow &&+ movingStatusWorkflow &&map.get(activeId)?.status !== finalGroup.status &&- !workflowAllowsStatus(movingWorkflow, finalGroup.status)+ !workflowAllowsStatus(movingStatusWorkflow, finalGroup.status)) {resetColumns();toast.info(t(($) => $.workflows.drop_blocked, {status: labelOf(finalGroup.status),- name: movingWorkflow.name,+ name: movingStatusWorkflow.name,}),);return;@@ -798,7 +812,7 @@ function BoardViewImpl({);applyPropertyGroupValue(finalGroup, activeId);},- [groupedIssues, groups, grouping, groupingOptionIds, onMoveIssue, groupIds, groupMap, sortBy, beginSettle, columnsRef, isDraggingRef, setColumns, applyPropertyGroupValue, catalog, labelOf, t, workflowOfIssue],+ [groupedIssues, groups, grouping, groupingOptionIds, onMoveIssue, groupIds, groupMap, sortBy, beginSettle, columnsRef, isDraggingRef, setColumns, applyPropertyGroupValue, catalog, labelOf, t, workflowOfIssue, statusWorkflowOfIssue],);// An aborted drag (pointercancel, window resize, tab hide, Escape) firesdiff --git a/packages/views/issues/components/pickers/status-picker.test.tsx b/packages/views/issues/components/pickers/status-picker.test.tsxindex d3faae2fa7..a1ae78da36 100644--- a/packages/views/issues/components/pickers/status-picker.test.tsx+++ b/packages/views/issues/components/pickers/status-picker.test.tsx@@ -282,17 +282,20 @@ describe("StatusPicker on an issue outside any project (MUL-8121)", () => {expect(checkOf("Todo")?.getAttribute("class")).toContain("invisible");});- it("still reaches every status through search", () => {+ it("searches only the Default workflow's statuses", () => {catalogEntries = [TODO, IN_REVIEW, QA, MERGED, DONE];workspaceDefault = DEFAULT;const onUpdate = vi.fn();renderWithI18n(<StatusPicker status="todo" projectId={null} onUpdate={onUpdate} open onOpenChange={() => {}} />,);- fireEvent.change(screen.getByPlaceholderText("Search status..."), { target: { value: "merg" } });- expect(rows()).toEqual(["Merged"]);- fireEvent.click(optionRow("Merged"));- expect(onUpdate).toHaveBeenCalledWith({ status: "merged" });+ const search = screen.getByPlaceholderText("Search status...");+ fireEvent.change(search, { target: { value: "merg" } });+ expect(rows()).toEqual([]);+ fireEvent.change(search, { target: { value: "rev" } });+ expect(rows()).toEqual(["In Review"]);+ fireEvent.click(optionRow("In Review"));+ expect(onUpdate).toHaveBeenCalledWith({ status: "in_review" });});it("offers the whole catalog when the surface spans projects", () => {diff --git a/packages/views/issues/components/pickers/status-picker.tsx b/packages/views/issues/components/pickers/status-picker.tsxindex f1c0e1b02b..050cba805e 100644--- a/packages/views/issues/components/pickers/status-picker.tsx+++ b/packages/views/issues/components/pickers/status-picker.tsx@@ -62,8 +62,8 @@ export function StatusPicker({* 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. (MUL-7420) `null` is an issue outside any project: it offers- * the Default workflow's statuses, and search still reaches every status.- * (MUL-8121) Omit (`undefined`) when the surface spans projects.+ * only the Default workflow's statuses, search included. (MUL-8121,+ * MUL-8250) Omit (`undefined`) when the surface spans projects.*/projectId?: string | null;/**@@ -97,7 +97,6 @@ export function StatusPicker({workflow,project,defaultScope,- catalog,} = useIssueStatusOptions(wsId, projectId, status);const allOptions = useMemo(() => (allowedStatuses ? projectOptions.filter((o) => allowedStatuses.has(o.key)) : projectOptions),@@ -107,11 +106,8 @@ export function StatusPicker({const options = useMemo(() => {const q = query.trim().toLowerCase();if (!q) return allOptions;- // Outside a project only the list is narrowed to Default, not what the- // issue may take: search reaches every status. (MUL-8121)- const pool = defaultScope ? catalog : allOptions;- return pool.filter((o) => o.label.toLowerCase().includes(q));- }, [allOptions, catalog, defaultScope, query]);+ return allOptions.filter((o) => o.label.toLowerCase().includes(q));+ }, [allOptions, query]);const searchable = !!workflow || !!defaultScope || allOptions.length > SEARCH_THRESHOLD;const [pendingStatus, setPendingStatus] = useState<IssueStatus | null>(null);diff --git a/packages/views/issues/utils/status-options.ts b/packages/views/issues/utils/status-options.tsindex 753a7f2b0b..fb3839756f 100644--- a/packages/views/issues/utils/status-options.ts+++ b/packages/views/issues/utils/status-options.ts@@ -96,14 +96,15 @@ const CATEGORY_RANK = new Map<IssueStatusCategory, number>(ALL_STATUSES.map((c,* `projectId` is three-valued:* - a project id: that project's workflow;* - `null`: an issue outside any project. It offers the workspace Default- * workflow's statuses, as a project on Default does, so statuses another- * project's workflow added stay out of its list. Default has no handoffs+ * workflow's statuses and nothing else, as a project on Default does and+ * as the server enforces. (MUL-8121, MUL-8250) Default has no handoffs* here — the server applies none outside a project — so `workflow` stays- * null and `defaultScope` names the Default instead. The server still- * accepts any status, so `catalog` keeps the full set reachable by search,- * and `currentStatus` stays listed even when Default leaves it out.- * (MUL-8121)+ * null and `defaultScope` names the Default instead.* - `undefined`: a surface spanning projects; the whole catalog.+ *+ * On Default, `currentStatus` stays listed even when Default leaves it out+ * (the issue left a project whose workflow added it, or Default dropped it),+ * so it can still be seen and moved off.*/export function useIssueStatusOptions(wsId: string,@@ -114,7 +115,6 @@ export function useIssueStatusOptions(workflow: IssueWorkflow | null;project: Project | null;defaultScope: IssueWorkflow | null;- catalog: StatusOption[];} {const catalogOptions = useStatusOptions(wsId);const { categoryOf, colorOf, iconOf } = useIssueStatuses(wsId);@@ -134,15 +134,14 @@ export function useIssueStatusOptions(icon: iconOf(key),};const steps = listed.steps.map((step) => optionOf(step.status_key));- if (!defaultScope || !currentStatus || steps.some((o) => o.key === currentStatus)) return steps;- // The current status is outside Default (e.g. the issue left a project- // whose workflow added it): keep it visible and checked, after the last- // step of its category, so it can still be seen and moved off.+ if (!listed.is_default || !currentStatus || steps.some((o) => o.key === currentStatus)) return steps;+ // Keep a current status Default leaves out visible and checked, after the+ // last step of its category.const current = optionOf(currentStatus);const rank = CATEGORY_RANK.get(current.category) ?? ALL_STATUSES.length;let at = steps.length;while (at > 0 && (CATEGORY_RANK.get(steps[at - 1]!.category) ?? 0) > rank) at -= 1;return [...steps.slice(0, at), current, ...steps.slice(at)];}, [catalogOptions, categoryOf, colorOf, currentStatus, defaultScope, iconOf, labelOf, workflow]);- return { options, workflow, project, defaultScope, catalog: catalogOptions };+ return { options, workflow, project, defaultScope };}diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsxindex 1e1c2b2b96..623616b41c 100644--- a/packages/views/modals/create-issue.tsx+++ b/packages/views/modals/create-issue.tsx@@ -64,7 +64,7 @@ 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 { useProjectWithWorkflow, 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";@@ -415,9 +415,11 @@ export function ManualCreatePanel({setParentIssueId(id);setStage(null);};- // 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);+ // An issue only takes its workflow's columns — its project's, or Default's+ // outside a project: a status it does not list moves to todo, which every+ // workflow keeps. (MUL-7420, MUL-8250)+ const { workflow: projectWorkflow, defaultWorkflow: workspaceDefault } = useProjectWithWorkflow(wsId, projectId);+ const createWorkflow = projectId ? projectWorkflow : workspaceDefault;useEffect(() => {if (createWorkflow && !workflowAllowsStatus(createWorkflow, status)) {setStatus("todo");diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 8229e80823..9f89191cf9 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -3305,6 +3305,19 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to resolve project workflow")return}+ // Outside any project the issue takes the Default's statuses. (MUL-8250)+ if !workflowProjectID.Valid {+ outside, err := issueworkflow.OutsideProject(r.Context(), h.Queries, wsUUID)+ if err != nil {+ slog.Error("create issue: resolve default workflow", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to resolve project workflow")+ return+ }+ if err := issueworkflow.CheckStatusOutsideProject(outside, status); err != nil {+ writeIssueWorkflowError(w, err)+ return+ }+ }if createWorkflow != nil {if err := issueworkflow.CheckStatus(createWorkflow, status); err != nil {writeIssueWorkflowError(w, err)diff --git a/server/internal/handler/issue_status.go b/server/internal/handler/issue_status.goindex f174fbc573..a8e4cd46b4 100644--- a/server/internal/handler/issue_status.go+++ b/server/internal/handler/issue_status.go@@ -13,6 +13,7 @@ import ("github.com/jackc/pgx/v5""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/logger""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -251,6 +252,11 @@ func (h *Handler) createIssueStatusEntry(ctx context.Context, workspaceID pgtypeif badRequest != "" || err != nil {return db.IssueStatus{}, badRequest, err}+ // A status created inside a workflow's editor goes through+ // createIssueStatusEntryLocked alone and stays out of Default.+ if err := issueworkflow.AddToDefault(ctx, qtx, workspaceID, entry.Key); err != nil {+ return db.IssueStatus{}, "", err+ }if err := tx.Commit(ctx); err != nil {return db.IssueStatus{}, "", err}diff --git a/server/internal/handler/issue_status_test.go b/server/internal/handler/issue_status_test.goindex 16fd24c426..2c9072265b 100644--- a/server/internal/handler/issue_status_test.go+++ b/server/internal/handler/issue_status_test.go@@ -15,6 +15,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/events""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/testutil"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -55,9 +56,27 @@ func createTestCustomStatus(t *testing.T, key, category string) db.IssueStatus {t.Cleanup(func() {testPool.Exec(context.Background(), `DELETE FROM issue_status WHERE id = $1`, entry.ID)})+ listInTestDefault(t, key)return entry}+// listInTestDefault does what CreateIssueStatus does for a status a test+// inserts directly: lists it in the stored Default, so issues outside a+// project may take it. Cleanup takes it out again.+func listInTestDefault(t *testing.T, key string) {+ t.Helper()+ ctx := context.Background()+ if err := issueworkflow.AddToDefault(ctx, testHandler.Queries, parseUUID(testWorkspaceID), key); err != nil {+ t.Fatalf("list %q in Default: %v", key, err)+ }+ t.Cleanup(func() {+ testHandler.Queries.RemoveStatusFromDefaultIssueWorkflow(ctx, db.RemoveStatusFromDefaultIssueWorkflowParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ StatusKey: key,+ })+ })+}+// TestEnsureIsIdempotent covers the rolling-deploy case: two pods can seed the// same workspace concurrently and the second must be a no-op, not an error.func TestEnsureIsIdempotent(t *testing.T) {@@ -1661,6 +1680,7 @@ func TestIssueResponseCarriesCustomStatusName(t *testing.T) {t.Cleanup(func() {testPool.Exec(context.Background(), `DELETE FROM issue_status WHERE id = $1`, entry.ID)})+ listInTestDefault(t, "in_review_8")var custom IssueResponsetestutil.Call(t, testHandler.CreateIssue,@@ -1911,6 +1931,7 @@ func TestCustomStatusPayloadsAgreeAcrossRenderings(t *testing.T) {t.Cleanup(func() {testPool.Exec(context.Background(), `DELETE FROM issue_status WHERE id = $1`, entry.ID)})+ listInTestDefault(t, "in_review_7")var fromHTTP IssueResponsetestutil.Call(t, testHandler.CreateIssue,diff --git a/server/internal/handler/issue_trigger_backlog_category_test.go b/server/internal/handler/issue_trigger_backlog_category_test.goindex 79b5bef7b1..356becb554 100644--- a/server/internal/handler/issue_trigger_backlog_category_test.go+++ b/server/internal/handler/issue_trigger_backlog_category_test.go@@ -29,6 +29,7 @@ func TestBacklogToCustomUnstartedStatusTriggers(t *testing.T) {t.Cleanup(func() {testPool.Exec(ctx, `DELETE FROM issue_status WHERE workspace_id = $1 AND key = $2`, testWorkspaceID, parkedKey)})+ listInTestDefault(t, parkedKey)req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Parked issue",diff --git a/server/internal/handler/issue_workflow_entry.go b/server/internal/handler/issue_workflow_entry.goindex 9c199cfbb1..5682d7660f 100644--- a/server/internal/handler/issue_workflow_entry.go+++ b/server/internal/handler/issue_workflow_entry.go@@ -47,9 +47,22 @@ type workflowHandoff struct {// 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 {+ if err != nil {return nil, err}+ // Keeping the current status is never a rejected write, even when the+ // workflow no longer lists it.+ statusChanging := params.Status.Valid && params.Status.String != prev.Status+ if def == nil {+ if !statusChanging {+ return nil, nil+ }+ outside, err := issueworkflow.OutsideProject(ctx, h.Queries, prev.WorkspaceID)+ if err != nil {+ return nil, err+ }+ return nil, issueworkflow.CheckStatusOutsideProject(outside, params.Status.String)+ }projectMoving := params.ProjectID != prev.ProjectIDif projectMoving && !statusExplicit && !def.IsDefault && !def.Has(prev.Status) {target := issueworkflow.MoveTarget(*def, prev.Status, func(key string) string {@@ -57,7 +70,9 @@ func (h *Handler) applyIssueWorkflow(ctx context.Context, prev db.Issue, params})params.Status = pgtype.Text{String: target, Valid: true}}- if params.Status.Valid {+ // A move into a Default project keeps the issue's status, as it is never+ // mapped; a named workflow must list the status the issue lands on.+ if params.Status.Valid && (statusChanging || (projectMoving && !def.IsDefault)) {if err := issueworkflow.CheckStatus(def, params.Status.String); err != nil {return nil, err}diff --git a/server/internal/handler/issue_workflow_test.go b/server/internal/handler/issue_workflow_test.goindex b7bf343767..2deb93c70c 100644--- a/server/internal/handler/issue_workflow_test.go+++ b/server/internal/handler/issue_workflow_test.go@@ -307,7 +307,7 @@ func TestDefaultWorkflowIsEditableButNotDeletable(t *testing.T) {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.+ // Editing Default maps no issue: one on a status it dropped keeps it.if status, _, _ := issueStatusAndAssignee(t, issueID); status != "in_review" {t.Fatalf("editing Default moved an issue to %q", status)}@@ -387,6 +387,69 @@ func TestUpdateIssueRejectsStatusOutsideNamedWorkflow(t *testing.T) {updateIssueForTest(t, issueID, map[string]any{"status": "blocked"}).Want(http.StatusOK)}+// A stored Default limits statuses on its projects and on issues outside any+// project; an issue already on another status keeps it. (MUL-8250)+func TestDefaultLimitsStatusesInAndOutsideProjects(t *testing.T) {+ seedTestCatalog(t)+ resetDefaultWorkflow(t)+ testutil.Call(t, testHandler.ListIssueWorkflows, workflowRequest("GET", "/api/issue-workflows", nil)).Want(http.StatusOK)+ statusName := "Ship " + workflowTestSuffix()[10:]+ var wf IssueWorkflowResponse+ testutil.Call(t, testHandler.CreateIssueWorkflow, workflowRequest("POST", "/api/issue-workflows", map[string]any{+ "name": "Ship " + workflowTestSuffix(),+ "steps": []map[string]any{{"new_status": map[string]any{"name": statusName, "category": "started"}}},+ })).Want(http.StatusCreated).JSON(&wf)+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue_workflow WHERE id = $1`, wf.ID)+ testPool.Exec(context.Background(), `DELETE FROM issue_status WHERE workspace_id = $1 AND name = $2`, testWorkspaceID, statusName)+ })+ shipKey := ""+ for _, s := range wf.Steps {+ if lookupStatusName(t, s.StatusKey) == statusName {+ shipKey = s.StatusKey+ }+ }+ if shipKey == "" {+ t.Fatalf("workflow steps %+v lack the new status", wf.Steps)+ }++ outside := dbfx.Issue(t, "outside a project", testutil.Cols{"status": "todo"})+ body := updateIssueForTest(t, outside, map[string]any{"status": shipKey}).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, "issues outside a project") {+ t.Fatalf("error %q should say the issue is outside a project", msg)+ }+ updateIssueForTest(t, outside, map[string]any{"status": "in_progress"}).Want(http.StatusOK)++ projectID := createWorkflowTestProject(t, "Default limit project")+ onDefault := dbfx.Issue(t, "on a Default project", testutil.Cols{"project_id": projectID, "status": "todo"})+ updateIssueForTest(t, onDefault, map[string]any{"status": shipKey}).Want(http.StatusBadRequest)++ kept := dbfx.Issue(t, "already shipped", testutil.Cols{"status": shipKey})+ updateIssueForTest(t, kept, map[string]any{"title": "still shipped"}).Want(http.StatusOK)+ updateIssueForTest(t, kept, map[string]any{"status": shipKey}).Want(http.StatusOK)+ if status, _, _ := issueStatusAndAssignee(t, kept); status != shipKey {+ t.Fatalf("an issue already on %q moved to %q", shipKey, status)+ }++ testutil.Call(t, testHandler.CreateIssue, newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": "created outside Default", "status": shipKey,+ })).Want(http.StatusBadRequest)++ // A status created in Settings belongs to no workflow, so it joins Default.+ var settingsStatus IssueStatusResponse+ testutil.Call(t, testHandler.CreateIssueStatus, newRequest(http.MethodPost, "/api/issue-statuses", map[string]any{+ "name": "Parked " + workflowTestSuffix()[10:], "category": "unstarted", "color": "#123456",+ })).Want(http.StatusCreated).JSON(&settingsStatus)+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue_status WHERE id = $1`, parseUUID(settingsStatus.ID))+ })+ updateIssueForTest(t, outside, map[string]any{"status": settingsStatus.Key}).Want(http.StatusOK)+ updateIssueForTest(t, onDefault, map[string]any{"status": settingsStatus.Key}).Want(http.StatusOK)+}+func TestStatusChangeHandsOffOnDefaultProject(t *testing.T) {seedTestCatalog(t)agentID := seededReadyAgentID(t)diff --git a/server/internal/issueworkflow/default.go b/server/internal/issueworkflow/default.goindex 6ceb317e7b..499c12a0bc 100644--- a/server/internal/issueworkflow/default.go+++ b/server/internal/issueworkflow/default.go@@ -49,6 +49,47 @@ func EnsureDefault(ctx context.Context, q DefaultStore, workspaceID pgtype.UUID)return q.GetDefaultIssueWorkflow(ctx, workspaceID)}+// DefaultUpdater is what adding a status to a stored Default needs.+type DefaultUpdater interface {+ GetDefaultIssueWorkflow(ctx context.Context, workspaceID pgtype.UUID) (db.IssueWorkflow, error)+ UpdateIssueWorkflow(ctx context.Context, arg db.UpdateIssueWorkflowParams) (db.IssueWorkflow, error)+}++// AddToDefault lists a status created outside any workflow in the stored+// Default, the way the first snapshot takes every status no workflow lists. A+// workspace that has not stored Default yet picks it up in that snapshot.+func AddToDefault(ctx context.Context, q DefaultUpdater, workspaceID pgtype.UUID, key string) error {+ row, err := q.GetDefaultIssueWorkflow(ctx, workspaceID)+ if errors.Is(err, pgx.ErrNoRows) {+ return nil+ }+ if err != nil {+ return err+ }+ steps, err := DecodeSteps(row.Steps)+ if err != nil {+ return err+ }+ for _, s := range steps {+ if s.StatusKey == key {+ return nil+ }+ }+ raw, err := EncodeSteps(Arrange(append(steps, Step{StatusKey: key, Handler: Handler{Type: HandlerNone}})))+ if err != nil {+ return err+ }+ _, err = q.UpdateIssueWorkflow(ctx, db.UpdateIssueWorkflowParams{+ ID: row.ID,+ WorkspaceID: workspaceID,+ Name: row.Name,+ Description: row.Description,+ InitialStatusKey: row.InitialStatusKey,+ Steps: raw,+ })+ return err+}+// 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.diff --git a/server/internal/issueworkflow/issueworkflow.go b/server/internal/issueworkflow/issueworkflow.goindex 414387fff4..e9b823a55d 100644--- a/server/internal/issueworkflow/issueworkflow.go+++ b/server/internal/issueworkflow/issueworkflow.go@@ -14,8 +14,9 @@//// 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.+// Once stored, Default limits status writes like any workflow, on its+// projects and on issues outside any project alike (MUL-8250). Issues already+// on statuses Default does not list keep them until someone moves them.package issueworkflowimport (@@ -268,6 +269,14 @@ func stepsFor(keys []string) []Step {return steps}+// Limits reports whether the workflow restricts the statuses its issues may+// enter. Only a Default the workspace has not stored yet does not: it stands+// for "the built-in statuses" before the workspace ever used workflows, and+// limiting by it would strand custom statuses that workspace already uses.+func (d Definition) Limits() bool {+ return !d.IsDefault || d.ID.Valid+}+// Has reports whether the workflow lists the status key.func (d Definition) Has(key string) bool {_, ok := d.Step(key)@@ -561,6 +570,25 @@ func ForProject(ctx context.Context, q Querier, workspaceID, projectID pgtype.UUreturn def, project, err}+// OutsideProject loads the workflow that limits the statuses of an issue+// outside any project: the workspace's stored Default, or nil before the+// workspace stores one. Nothing hands off outside a project, so it is only+// for checking statuses; ForProject stays nil there. (MUL-8250)+func OutsideProject(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 nil, nil+ }+ return nil, err+ }+ def, err := Decode(row)+ if err != nil {+ return nil, err+ }+ return &def, nil+}+// 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) {@@ -631,9 +659,16 @@ type NotInWorkflowError struct {StatusKey stringWorkflowName stringAllowed []string+ // OutsideProject marks an issue outside any project, which takes the+ // statuses of the workspace Default.+ OutsideProject bool}func (e *NotInWorkflowError) Error() string {+ if e.OutsideProject {+ return fmt.Sprintf("status %q is not part of the workflow %q that issues outside a project use; use one of: %s",+ e.StatusKey, e.WorkflowName, strings.Join(e.Allowed, ", "))+ }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, ", "))}@@ -670,16 +705,27 @@ func statusLabel(name, key string) string {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.+// CheckStatus rejects a status the workflow does not list. Callers skip it+// when a write keeps the issue's current status, so an issue already on a+// status its workflow no longer lists keeps working.func CheckStatus(def *Definition, key string) error {- if def == nil || def.IsDefault || def.Has(key) {+ if def == nil || !def.Limits() || def.Has(key) {return nil}return &NotInWorkflowError{StatusKey: key, WorkflowName: def.Name, Allowed: def.StatusKeys()}}+// CheckStatusOutsideProject is CheckStatus for an issue outside any project,+// against OutsideProject's workflow.+func CheckStatusOutsideProject(def *Definition, key string) error {+ err := CheckStatus(def, key)+ var notIn *NotInWorkflowError+ if errors.As(err, ¬In) {+ notIn.OutsideProject = true+ }+ return err+}+// BriefInput carries what the handoff brief names.type BriefInput struct {Workflow Definitiondiff --git a/server/internal/issueworkflow/issueworkflow_test.go b/server/internal/issueworkflow/issueworkflow_test.goindex 6ae627f832..d30b4f11e7 100644--- a/server/internal/issueworkflow/issueworkflow_test.go+++ b/server/internal/issueworkflow/issueworkflow_test.go@@ -228,9 +228,21 @@ func TestCheckStatusListsAllowedKeys(t *testing.T) {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)+ t.Fatalf("a Default the workspace never stored accepts any status, got %v", err)}- err := CheckStatus(&def, "in_review")+ stored := Definition{ID: pgtype.UUID{Bytes: [16]byte{1}, Valid: true}, Name: DefaultName, IsDefault: true, Steps: stepsFor(BuiltInDefaultKeys())}+ if err := CheckStatus(&stored, "in_review"); err != nil {+ t.Fatalf("stored Default rejected a status it lists: %v", err)+ }+ err := CheckStatusOutsideProject(&stored, "code_review")+ var outside *NotInWorkflowError+ if !errors.As(err, &outside) || !outside.OutsideProject {+ t.Fatalf("CheckStatusOutsideProject = %v, want NotInWorkflowError outside a project", err)+ }+ if !strings.Contains(err.Error(), "issues outside a project") {+ t.Fatalf("error %q should say the issue is outside a project", err)+ }+ err = CheckStatus(&def, "in_review")var notIn *NotInWorkflowErrorif !errors.As(err, ¬In) {t.Fatalf("CheckStatus = %v, want NotInWorkflowError", err)diff --git a/server/internal/service/issue.go b/server/internal/service/issue.goindex 2328422bf8..63fc76f113 100644--- a/server/internal/service/issue.go+++ b/server/internal/service/issue.go@@ -274,15 +274,16 @@ 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.+ // Project workflow (MUL-7420): an issue created with a status its+ // workflow does not list — the project's, or the stored Default outside+ // any project (MUL-8250) — 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) {+ } else if def != nil && def.Limits() && !def.Has(p.Status) {p.Status = issueworkflow.StartStatus}@@ -846,8 +847,9 @@ func classifyOrigin(issue db.Issue, opts IssueCreateOpts) (source, taskID, autop}}-// createWorkflow resolves the workflow of the project a new issue lands in:-// its own project, or its parent's when it names none.+// createWorkflow resolves the workflow whose statuses a new issue may take:+// its own project's, its parent's project's when it names none, or the+// stored Default when neither has a project.func (s *IssueService) createWorkflow(ctx context.Context, qtx *db.Queries, p IssueCreateParams) (*issueworkflow.Definition, error) {projectID := p.ProjectIDif !projectID.Valid && p.ParentIssueID.Valid {@@ -858,6 +860,9 @@ func (s *IssueService) createWorkflow(ctx context.Context, qtx *db.Queries, p Is}projectID = parent.ProjectID}+ if !projectID.Valid {+ return issueworkflow.OutsideProject(ctx, qtx, p.WorkspaceID)+ }def, _, err := issueworkflow.ForProject(ctx, qtx, p.WorkspaceID, projectID)return def, err}