Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8118 fix(workflows): edit a new status step before saving (#9385)
Multica Eve3c65b18c9998
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 7fb289d620..82678362e6 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -1590,8 +1590,7 @@"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."+ "no_handoff_step": "This step doesn't hand off: issues entering it keep their assignee and start no run."},"mapping": {"title": "Move issues into {{name}}",diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex df4e37ae88..d78c872f78 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -1590,8 +1590,7 @@"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."+ "no_handoff_step": "Cette étape ne relaie pas : le responsable ne change pas et aucune exécution ne démarre."},"mapping": {"title": "Déplacer les tâches vers {{name}}",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 27bd7c8981..7809876e46 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -1534,8 +1534,7 @@"step_off": "オフ:このワークフローはこのステータスを使いません。左のリストでオンにすると使えます。","status_new_hint": "新しいステータスです。保存時にステータスライブラリに追加されます。","no_other_status": "すべてのステータスがすでにステップです。",- "no_handoff_step": "このステップは引き継ぎません。入っても担当者は変わらず、実行も始まりません。",- "new_step_handoff": "先にワークフローを保存してください。保存後に新しいステータスの引き継ぎを設定できます。"+ "no_handoff_step": "このステップは引き継ぎません。入っても担当者は変わらず、実行も始まりません。"},"mapping": {"title": "タスクを「{{name}}」に移動",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex 1f1f3b9504..12ca619b1b 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -1534,8 +1534,7 @@"step_off": "꺼짐: 이 워크플로는 이 상태를 쓰지 않습니다. 왼쪽 목록에서 켜면 사용할 수 있습니다.","status_new_hint": "새 상태입니다. 저장할 때 상태 라이브러리에 추가됩니다.","no_other_status": "모든 상태가 이미 단계입니다.",- "no_handoff_step": "이 단계는 인계하지 않습니다. 들어와도 담당자는 그대로이고 실행도 시작되지 않습니다.",- "new_step_handoff": "먼저 워크플로를 저장하세요. 저장한 뒤 새 상태의 인계를 설정할 수 있습니다."+ "no_handoff_step": "이 단계는 인계하지 않습니다. 들어와도 담당자는 그대로이고 실행도 시작되지 않습니다."},"mapping": {"title": "{{name}}(으)로 태스크 이동",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex 14411a42e1..d0f36f71f2 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -1534,8 +1534,7 @@"step_off": "已关闭:这个工作流不使用这个状态。在左侧列表打开开关即可使用。","status_new_hint": "新状态,保存时加入状态库。","no_other_status": "所有状态都已经是步骤了。",- "no_handoff_step": "这一步不交接:任务进入时负责人不变,也不会启动运行。",- "new_step_handoff": "先保存工作流,新状态保存后就可以设置交接。"+ "no_handoff_step": "这一步不交接:任务进入时负责人不变,也不会启动运行。"},"mapping": {"title": "将任务移入「{{name}}」",diff --git a/packages/views/workflows/handoff-form.tsx b/packages/views/workflows/handoff-form.tsxindex f9815dd5ed..87f18591ed 100644--- a/packages/views/workflows/handoff-form.tsx+++ b/packages/views/workflows/handoff-form.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useMemo, useState } from "react";+import { useEffect, useId, useMemo, useState } from "react";import { useQuery } from "@tanstack/react-query";import { toast } from "sonner";import { api, clientErrorMessage } from "@multica/core/api";@@ -276,16 +276,29 @@ export function HandoffFields({canEdit,onPatch,onPreview,+ defaultNextLabel,}: {step: IssueWorkflowStep;+ /** The statuses next and back may name. */workflow: Pick<IssueWorkflow, "steps">;canEdit: boolean;onPatch: (patch: Partial<IssueWorkflowStep>) => void;onPreview?: () => void;+ /**+ * The default next status's label ("" for none), when it is resolved+ * against more columns than `workflow` lists — the editor's unsaved ones.+ */+ defaultNextLabel?: string;}) {const { t } = useT("issues");+ const wsId = useWorkspaceId();+ const labelOf = useStatusLabel(wsId);const mode = modeOf(step.handler);+ // Not derived from the status key: a step for a status still to be created+ // goes by a draft id that need not be a valid element id.+ const instructionsId = useId();const nextDefault = workflowNextStatus({ steps: workflow.steps.map((s) => ({ ...s, next_status_key: undefined })) }, step.status_key);+ const nextDefaultLabel = defaultNextLabel ?? (nextDefault ? labelOf(nextDefault) : "");const choose = (m: HandoffMode) => {if (m === mode) return;onPatch({ handler: m === "none" ? { type: "none" } : { type: m } });@@ -348,10 +361,10 @@ export function HandoffFields({<Fieldlabel={t(($) => $.workflows.handoff.instructions)}hint={t(($) => $.workflows.editor.instructions_hint)}- htmlFor={`workflow-handoff-instructions-${step.status_key}`}+ htmlFor={instructionsId}><Textarea- id={`workflow-handoff-instructions-${step.status_key}`}+ id={instructionsId}rows={4}maxLength={8000}readOnly={!canEdit}@@ -364,7 +377,7 @@ export function HandoffFields({step={step}workflow={workflow}canEdit={canEdit}- nextDefault={nextDefault}+ nextDefaultLabel={nextDefaultLabel}onPatch={onPatch}onPreview={onPreview}/>@@ -474,14 +487,15 @@ function NextBackFields({step,workflow,canEdit,- nextDefault,+ nextDefaultLabel,onPatch,onPreview,}: {step: IssueWorkflowStep;workflow: Pick<IssueWorkflow, "steps">;canEdit: boolean;- nextDefault: string | null;+ /** The default next status's label; empty when there is none. */+ nextDefaultLabel: string;onPatch: (patch: Partial<IssueWorkflowStep>) => void;onPreview?: () => void;}) {@@ -507,8 +521,8 @@ function NextBackFields({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) })+ kind === "next" && nextDefaultLabel+ ? t(($) => $.workflows.handoff.next_default, { status: nextDefaultLabel }): t(($) => $.workflows.editor.none_option);const options = [{ value: NOT_SET, label: unsetLabel }, ...others.map((key) => ({ value: key, label: labelOf(key) }))];return (diff --git a/packages/views/workflows/workflow-editor-page.test.tsx b/packages/views/workflows/workflow-editor-page.test.tsxnew file mode 100644index 0000000000..d07af522b2--- /dev/null+++ b/packages/views/workflows/workflow-editor-page.test.tsx@@ -0,0 +1,113 @@+// @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 { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";+import { projectListOptions } from "@multica/core/projects/queries";+import { renderWithI18n } from "../test/i18n";+import { WorkflowEditorPage } from "./workflow-editor-page";++const { createWorkflow } = vi.hoisted(() => ({ createWorkflow: vi.fn() }));++vi.mock("@multica/core/api", () => ({ api: {}, ApiError: class extends Error {}, clientErrorMessage: () => null }));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("@multica/core/paths", () => ({ useCurrentWorkspace: () => ({ id: "ws-1", name: "Acme" }) }));+vi.mock("@multica/core/issue-statuses/hooks", () => ({ useIssueStatuses: () => buildIssueStatusCatalog([]) }));+vi.mock("@multica/core/workspace/hooks", () => ({ useActorName: () => ({ getActorName: () => "Builder" }) }));+vi.mock("@multica/core/issue-workflows", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/issue-workflows")>()),+ useIssueWorkflows: () => ({ workflows: [], isLoaded: true }),+ useCreateIssueWorkflow: () => ({ mutateAsync: createWorkflow, isPending: false }),+ useUpdateIssueWorkflow: () => ({ mutateAsync: vi.fn(), isPending: false }),+ useDeleteIssueWorkflow: () => ({ mutateAsync: vi.fn(), isPending: false }),+}));+vi.mock("../common/actor-avatar", () => ({+ ActorAvatar: ({ actorId }: { actorId: string }) => <span data-testid={`avatar-${actorId}`} />,+}));++function renderEditor() {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ qc.setQueryData(projectListOptions("ws-1").queryKey, [] as never);+ qc.setQueryData(agentListOptions("ws-1").queryKey, [{ id: "agent-1", name: "Builder", archived_at: null }] as never);+ qc.setQueryData(memberListOptions("ws-1").queryKey, [] as never);+ renderWithI18n(+ <QueryClientProvider client={qc}>+ <WorkflowEditorPage workflowId={null} seed={null} canEdit onBack={vi.fn()} onOpen={vi.fn()} />+ </QueryClientProvider>,+ );+}++afterEach(() => {+ cleanup();+ createWorkflow.mockReset();+});++describe("WorkflowEditorPage", () => {+ it("edits a new status step's handoff before the save (MUL-8118)", async () => {+ createWorkflow.mockResolvedValue({ id: "wf-1" });+ renderEditor();++ fireEvent.click(screen.getByRole("button", { name: /Add step/ }));+ fireEvent.click(await screen.findByRole("menuitem", { name: /New status/ }));+ const input = screen.getByPlaceholderText("Status name");+ fireEvent.change(input, { target: { value: "Deploy" } });+ fireEvent.keyDown(input, { key: "Enter" });++ // The new step is selected, and its handoff can be edited right away.+ expect(screen.getByRole("heading", { name: "Deploy" })).toBeTruthy();+ const agent = screen.getByRole("radio", { name: /Hand to an agent/ });+ expect((agent as HTMLButtonElement).disabled).toBe(false);+ fireEvent.click(agent);+ fireEvent.click(screen.getByRole("button", { name: "Choose an agent" }));+ fireEvent.click(await screen.findByText("Builder"));++ fireEvent.change(screen.getByRole("textbox", { name: "Name" }), { target: { value: "Release" } });+ fireEvent.click(screen.getByRole("button", { name: "Create" }));++ await waitFor(() => expect(createWorkflow).toHaveBeenCalled());+ const steps = createWorkflow.mock.calls[0]![0].steps as unknown[];+ expect(steps).toContainEqual({+ new_status: { name: "Deploy" },+ handler: { type: "agent", id: "agent-1" },+ instructions: "",+ });+ });++ it("resolves a default next over the unsaved steps, as the save will", async () => {+ renderEditor();+ await addNewStatus("QA");+ await addNewStatus("Deploy");++ // QA is followed by Deploy on the board, so that is where its agent goes+ // next — not Done, the next status that exists before the save.+ fireEvent.click(stepCard("QA"));+ 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"));++ expect(screen.getByRole("combobox", { name: "When done, move to" }).textContent).toContain("Next column (Deploy)");+ expect(stepCard("QA").textContent).toContain("then → Deploy");+ // The explicit choices still list only statuses that exist before the save.+ fireEvent.click(screen.getByRole("combobox", { name: "When done, move to" }));+ expect(screen.queryByRole("option", { name: "Deploy" })).toBeNull();+ });+});++/** A step in the list (the detail panel's status picker shares its name). */+function stepCard(name: string) {+ const card = screen+ .getAllByRole("button", { name: new RegExp(`^${name}`) })+ .find((b) => b.hasAttribute("aria-pressed"));+ if (!card) throw new Error(`no step card ${name}`);+ return card;+}++async function addNewStatus(name: string) {+ fireEvent.click(screen.getByRole("button", { name: /Add step/ }));+ fireEvent.click(await screen.findByRole("menuitem", { name: /New status/ }));+ const input = screen.getByPlaceholderText("Status name");+ fireEvent.change(input, { target: { value: name } });+ fireEvent.keyDown(input, { key: "Enter" });+}diff --git a/packages/views/workflows/workflow-editor-page.tsx b/packages/views/workflows/workflow-editor-page.tsxindex e252b26457..45f3488446 100644--- a/packages/views/workflows/workflow-editor-page.tsx+++ b/packages/views/workflows/workflow-editor-page.tsx@@ -103,6 +103,14 @@ interface Draft {handoffs: Record<string, Handoff>;}+/**+ * The key a column goes by in the editor: its status, or — for a status the+ * save creates — its draft id, so its handoff can be edited before the save.+ */+function columnKey(column: DraftColumn): string {+ return "status_key" in column ? column.status_key : column.id;+}+function hasHandoff(h: Handoff | undefined): h is Handoff {return !!h && (h.handler.type !== "none" || !!h.next_status_key || !!h.back_status_key);}@@ -240,6 +248,14 @@ export function WorkflowEditorPage({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 })) };+ // The default next follows the whole draft, unsaved columns included —+ // the order the server resolves it in once the draft is saved.+ const draftFlow = { steps: columns.map((c) => ({ status_key: columnKey(c), ...NO_HANDOFF })) };+ const columnLabel = (key: string) => {+ if (!key) return "";+ const column = draft.middle.find((c) => c.id === key && "new_name" in c);+ return column && "new_name" in column ? column.new_name : labelOf(key);+ };const selectedId = selected ?? "todo";const selectedColumn = columns.find((c) => c.id === selectedId && "status_key" in c && statusAcceptsHandoff(c.status_key));const selectedStep: IssueWorkflowStep | null =@@ -261,7 +277,9 @@ export function WorkflowEditorPage({const addNew = () => {const name = newName?.trim();if (!name) return;- setDraft((d) => ({ ...d, middle: [...d.middle, { id: `new:${name}:${Date.now()}`, new_name: name }] }));+ const id = `new:${name}:${Date.now()}`;+ setDraft((d) => ({ ...d, middle: [...d.middle, { id, new_name: name }] }));+ setSelected(id);setNewName(null);};@@ -341,7 +359,8 @@ export function WorkflowEditorPage({{ 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 nextOf = (column: DraftColumn, h: Handoff | undefined) =>+ h?.next_status_key ?? workflowNextStatus(draftFlow, columnKey(column));const card = (column: DraftColumn) => {const key = "status_key" in column ? column.status_key : null;const optional = key === "backlog" || key === "blocked";@@ -351,7 +370,7 @@ export function WorkflowEditorPage({off,start: key === "todo",handoff: off ? undefined : draft.handoffs[column.id],- next: key && !off ? nextOf(key, draft.handoffs[column.id]) : undefined,+ nextLabel: off ? undefined : columnLabel(nextOf(column, draft.handoffs[column.id])) || undefined,selected: current.id === column.id,onSelect: () => setSelected(column.id),toggle: optional@@ -543,8 +562,9 @@ export function WorkflowEditorPage({off={isOff(current)}handoff={draft.handoffs[current.id]}flow={flow}+ defaultNextLabel={columnLabel(workflowNextStatus(draftFlow, columnKey(current)))}canEdit={canEdit}- statusOptions={middleIds.has(current.id) && "status_key" in current ? addable : null}+ statusOptions={middleIds.has(current.id) ? addable : null}onReplaceStatus={(key) => replaceStatus(current, key)}onRemove={canEdit && middleIds.has(current.id) ? () => removeColumn(current) : undefined}onPatch={(patch) => patchHandoff(current.id, patch)}@@ -603,8 +623,8 @@ interface StepCardProps {/** The step new issues start on. */start: boolean;handoff: Handoff | undefined;- /** Where the handler is told to move the issue next. */- next: string | undefined;+ /** Where the handler is told to move the issue next, by label. */+ nextLabel: string | undefined;selected: boolean;onSelect: () => void;toggle?: { checked: boolean; disabled: boolean; onChange: (on: boolean) => void };@@ -637,7 +657,7 @@ function StepCard({off,start,handoff,- next,+ nextLabel,selected,onSelect,toggle,@@ -657,7 +677,7 @@ function StepCard({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 step = handoff ? { status_key: columnKey(column), ...handoff } : undefined;const who = handlerLabel(step);const actor = stepHandlerActor(step, null);@@ -715,8 +735,8 @@ function StepCard({<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>+ {handoff?.handler.type === "agent" && nextLabel && (+ <span className="shrink-0 truncate">· {t(($) => $.workflows.editor.card_then, { status: nextLabel })}</span>)}</>) : (@@ -759,6 +779,7 @@ function StepDetail({onRemove,onPatch,onPreview,+ defaultNextLabel,}: {column: DraftColumn;off: boolean;@@ -771,6 +792,8 @@ function StepDetail({onRemove?: () => void;onPatch: (patch: Partial<Handoff>) => void;onPreview?: () => void;+ /** The default next status's label, resolved over the whole draft. */+ defaultNextLabel: string;}) {const { t } = useT("issues");const wsId = useWorkspaceId();@@ -853,18 +876,19 @@ function StepDetail({<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) ? (+ ) : !key || statusAcceptsHandoff(key) ? (+ // A new status is a middle column, so it always takes a handoff;+ // the save creates the status and keeps the handoff on it.<HandoffFields- step={{ status_key: key, ...(handoff ?? NO_HANDOFF) }}+ step={{ status_key: columnKey(column), ...(handoff ?? NO_HANDOFF) }}workflow={flow}canEdit={canEdit}onPatch={onPatch}onPreview={onPreview}+ defaultNextLabel={defaultNextLabel}/>) : (- <p className="text-caption leading-5 text-muted-foreground">- {key ? t(($) => $.workflows.editor.no_handoff_step) : t(($) => $.workflows.editor.new_step_handoff)}- </p>+ <p className="text-caption leading-5 text-muted-foreground">{t(($) => $.workflows.editor.no_handoff_step)}</p>)}</DetailField></div>