feat(web): warn about workflow replay cycles (#1720)
This commit is contained in:
@@ -1,20 +1,18 @@
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import {
|
||||
createWorkflowAction,
|
||||
createWorkflowStepAction,
|
||||
deleteWorkflowStepAction,
|
||||
getWorkflowTaskCount,
|
||||
getStepTaskCount,
|
||||
listWorkflowStepsAction,
|
||||
reorderWorkflowStepsAction,
|
||||
updateWorkflowStepAction,
|
||||
} from "@/app/actions/workspaces";
|
||||
import type { OnTurnCompleteAction } from "@/lib/types/workflow-actions";
|
||||
import type { Workflow, WorkflowStep } from "@/lib/types/http";
|
||||
import {
|
||||
useWorkflowDeleteHandlers,
|
||||
useWorkflowSaveActions,
|
||||
useWorkflowStepActions,
|
||||
} from "./workflow-card-actions";
|
||||
import { useWorkflowSaveActions, useWorkflowStepActions } from "./workflow-card-actions";
|
||||
import { useWorkflowMutationGuard } from "./workflow-mutation-guard";
|
||||
|
||||
vi.mock("@/app/actions/workspaces", () => ({
|
||||
createWorkflowAction: vi.fn(),
|
||||
@@ -29,6 +27,18 @@ vi.mock("@/app/actions/workspaces", () => ({
|
||||
bulkMoveTasks: vi.fn(),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(createWorkflowStepAction).mockImplementation(async (payload) =>
|
||||
step(`created-${payload.position}`, payload.name, payload.position, false),
|
||||
);
|
||||
vi.mocked(updateWorkflowStepAction).mockImplementation(async (stepId, updates) => ({
|
||||
...step(stepId, stepId, updates.position ?? 0, updates.is_start_step ?? false),
|
||||
...updates,
|
||||
}));
|
||||
vi.mocked(reorderWorkflowStepsAction).mockResolvedValue({ steps: [], total: 0 });
|
||||
});
|
||||
|
||||
const workflow = {
|
||||
id: "wf-1",
|
||||
workspace_id: "ws-1",
|
||||
@@ -37,7 +47,13 @@ const workflow = {
|
||||
updated_at: "",
|
||||
} as Workflow;
|
||||
|
||||
function step(id: string, name: string, position: number, isStartStep: boolean): WorkflowStep {
|
||||
function step(
|
||||
id: string,
|
||||
name: string,
|
||||
position: number,
|
||||
isStartStep: boolean,
|
||||
options: { autoStart?: boolean; onTurnComplete?: OnTurnCompleteAction[] } = {},
|
||||
): WorkflowStep {
|
||||
return {
|
||||
id,
|
||||
workflow_id: workflow.id,
|
||||
@@ -46,6 +62,10 @@ function step(id: string, name: string, position: number, isStartStep: boolean):
|
||||
color: "bg-slate-500",
|
||||
allow_manual_move: true,
|
||||
is_start_step: isStartStep,
|
||||
events: {
|
||||
on_enter: options.autoStart ? [{ type: "auto_start_agent" }] : [],
|
||||
on_turn_complete: options.onTurnComplete,
|
||||
},
|
||||
created_at: "",
|
||||
updated_at: "",
|
||||
};
|
||||
@@ -58,214 +78,587 @@ function renderNewWorkflowStepActions(initialSteps: WorkflowStep[]) {
|
||||
steps = typeof updater === "function" ? updater(steps) : updater;
|
||||
},
|
||||
);
|
||||
const view = renderHook(() =>
|
||||
useWorkflowStepActions({
|
||||
const view = renderHook(() => {
|
||||
const mutationGuard = useWorkflowMutationGuard(steps);
|
||||
return useWorkflowStepActions({
|
||||
workflow,
|
||||
isNewWorkflow: true,
|
||||
workflowSteps: steps,
|
||||
setWorkflowSteps,
|
||||
refreshWorkflowSteps: vi.fn(),
|
||||
setStepToDelete: vi.fn(),
|
||||
setStepTaskCount: vi.fn(),
|
||||
setTargetStepForMigration: vi.fn(),
|
||||
setStepDeleteOpen: vi.fn(),
|
||||
toast: vi.fn(),
|
||||
}),
|
||||
);
|
||||
mutationGuard,
|
||||
});
|
||||
});
|
||||
return { ...view, getSteps: () => steps };
|
||||
}
|
||||
|
||||
function renderReadOnlyWorkflowStepActions(initialSteps: WorkflowStep[]) {
|
||||
let steps = initialSteps;
|
||||
function renderPersistedWorkflowStepActions(steps: WorkflowStep[]) {
|
||||
let currentSteps = steps;
|
||||
const setWorkflowSteps = vi.fn(
|
||||
(updater: ((prev: WorkflowStep[]) => WorkflowStep[]) | WorkflowStep[]) => {
|
||||
steps = typeof updater === "function" ? updater(steps) : updater;
|
||||
currentSteps = typeof updater === "function" ? updater(currentSteps) : updater;
|
||||
},
|
||||
);
|
||||
const refreshWorkflowSteps = vi.fn();
|
||||
const view = renderHook(() =>
|
||||
useWorkflowStepActions({
|
||||
const setStepDeleteOpen = vi.fn();
|
||||
const view = renderHook(() => {
|
||||
const mutationGuard = useWorkflowMutationGuard(steps);
|
||||
const actions = useWorkflowStepActions({
|
||||
workflow,
|
||||
isNewWorkflow: false,
|
||||
readOnly: true,
|
||||
workflowSteps: steps,
|
||||
setWorkflowSteps,
|
||||
refreshWorkflowSteps,
|
||||
setStepToDelete: vi.fn(),
|
||||
setStepTaskCount: vi.fn(),
|
||||
setTargetStepForMigration: vi.fn(),
|
||||
setStepDeleteOpen,
|
||||
toast: vi.fn(),
|
||||
mutationGuard,
|
||||
});
|
||||
return { actions, mutationGuard };
|
||||
});
|
||||
return {
|
||||
...view,
|
||||
setWorkflowSteps,
|
||||
setStepDeleteOpen,
|
||||
getSteps: () => currentSteps,
|
||||
};
|
||||
}
|
||||
|
||||
function deferredPromise<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((resolvePromise) => {
|
||||
resolve = resolvePromise;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
it("keeps one start step while editing a new workflow locally", async () => {
|
||||
const { result, getSteps } = renderNewWorkflowStepActions([
|
||||
step("step-1", "Todo", 0, true),
|
||||
step("step-2", "Plan", 1, false),
|
||||
]);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleUpdateWorkflowStep("step-2", { is_start_step: true });
|
||||
});
|
||||
|
||||
expect(
|
||||
getSteps()
|
||||
.filter((s) => s.is_start_step)
|
||||
.map((s) => s.id),
|
||||
).toEqual(["step-2"]);
|
||||
});
|
||||
|
||||
it("does not update a persisted step when the proposal introduces a blocking cycle", async () => {
|
||||
const steps = [
|
||||
step("build", "Build", 0, true, {
|
||||
autoStart: true,
|
||||
onTurnComplete: [{ type: "move_to_next" }],
|
||||
}),
|
||||
step("review", "Review", 1, false, { autoStart: true }),
|
||||
];
|
||||
const { result } = renderHook(() => {
|
||||
const mutationGuard = useWorkflowMutationGuard(steps);
|
||||
return useWorkflowStepActions({
|
||||
workflow,
|
||||
isNewWorkflow: false,
|
||||
workflowSteps: steps,
|
||||
setWorkflowSteps: vi.fn(),
|
||||
setStepToDelete: vi.fn(),
|
||||
setStepTaskCount: vi.fn(),
|
||||
setTargetStepForMigration: vi.fn(),
|
||||
setStepDeleteOpen: vi.fn(),
|
||||
toast: vi.fn(),
|
||||
mutationGuard,
|
||||
});
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleUpdateWorkflowStep("review", {
|
||||
events: {
|
||||
...steps[1].events,
|
||||
on_turn_complete: [{ type: "move_to_previous" }],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
expect(updateWorkflowStepAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not persist a second topology edit before the first mutation completes", async () => {
|
||||
const steps = [
|
||||
step("work", "Work", 0, true, { autoStart: true }),
|
||||
step("review", "Review", 1, false),
|
||||
];
|
||||
const update = deferredPromise<WorkflowStep>();
|
||||
vi.mocked(updateWorkflowStepAction).mockReturnValueOnce(update.promise);
|
||||
const { result } = renderPersistedWorkflowStepActions(steps);
|
||||
|
||||
let firstEdit!: Promise<void>;
|
||||
await act(async () => {
|
||||
firstEdit = result.current.actions.handleUpdateWorkflowStep("work", {
|
||||
events: { on_turn_complete: [{ type: "move_to_next" }] },
|
||||
});
|
||||
await vi.waitFor(() => expect(updateWorkflowStepAction).toHaveBeenCalledTimes(1));
|
||||
await result.current.actions.handleUpdateWorkflowStep("review", {
|
||||
events: { on_turn_complete: [{ type: "move_to_previous" }] },
|
||||
});
|
||||
});
|
||||
|
||||
expect(updateWorkflowStepAction).toHaveBeenCalledTimes(1);
|
||||
expect(result.current.mutationGuard.isMutationPending).toBe(true);
|
||||
|
||||
update.resolve({
|
||||
...steps[0],
|
||||
events: { on_turn_complete: [{ type: "move_to_next" }] },
|
||||
});
|
||||
await act(async () => {
|
||||
await firstEdit;
|
||||
});
|
||||
expect(result.current.mutationGuard.isMutationPending).toBe(false);
|
||||
});
|
||||
|
||||
it("does not replace a pending warning proposal with a second edit", async () => {
|
||||
const steps = [
|
||||
step("work", "Work", 0, true, {
|
||||
autoStart: true,
|
||||
onTurnComplete: [{ type: "move_to_next" }],
|
||||
}),
|
||||
);
|
||||
return { ...view, getSteps: () => steps, refreshWorkflowSteps, setWorkflowSteps };
|
||||
}
|
||||
step("review", "Review", 1, false),
|
||||
];
|
||||
const { result } = renderPersistedWorkflowStepActions(steps);
|
||||
|
||||
describe("useWorkflowStepActions", () => {
|
||||
it("keeps one start step while editing a new workflow locally", async () => {
|
||||
const { result, getSteps } = renderNewWorkflowStepActions([
|
||||
step("step-1", "Todo", 0, true),
|
||||
step("step-2", "Plan", 1, false),
|
||||
await act(async () => {
|
||||
await result.current.actions.handleUpdateWorkflowStep("review", {
|
||||
events: {
|
||||
...steps[1].events,
|
||||
on_turn_complete: [{ type: "move_to_previous" }],
|
||||
},
|
||||
});
|
||||
});
|
||||
const proposal = result.current.mutationGuard.proposal;
|
||||
|
||||
await act(async () => {
|
||||
await result.current.actions.handleUpdateWorkflowStep("work", { name: "Building" });
|
||||
});
|
||||
|
||||
expect(result.current.mutationGuard.proposal).toBe(proposal);
|
||||
expect(updateWorkflowStepAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not replace a pending blocking proposal with a second edit", async () => {
|
||||
const steps = [
|
||||
step("build", "Build", 0, true, {
|
||||
autoStart: true,
|
||||
onTurnComplete: [{ type: "move_to_next" }],
|
||||
}),
|
||||
step("review", "Review", 1, false, { autoStart: true }),
|
||||
];
|
||||
const { result } = renderPersistedWorkflowStepActions(steps);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.actions.handleUpdateWorkflowStep("review", {
|
||||
events: { on_turn_complete: [{ type: "move_to_previous" }] },
|
||||
});
|
||||
});
|
||||
const proposal = result.current.mutationGuard.proposal;
|
||||
|
||||
await act(async () => {
|
||||
await result.current.actions.handleUpdateWorkflowStep("build", { name: "Building" });
|
||||
});
|
||||
|
||||
expect(result.current.mutationGuard.proposal).toBe(proposal);
|
||||
expect(updateWorkflowStepAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("releases a blocking proposal if confirmation is invoked defensively", async () => {
|
||||
const steps = [
|
||||
step("build", "Build", 0, true, {
|
||||
autoStart: true,
|
||||
onTurnComplete: [{ type: "move_to_next" }],
|
||||
}),
|
||||
step("review", "Review", 1, false, { autoStart: true }),
|
||||
];
|
||||
const { result } = renderPersistedWorkflowStepActions(steps);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.actions.handleUpdateWorkflowStep("review", {
|
||||
events: {
|
||||
...steps[1].events,
|
||||
on_turn_complete: [{ type: "move_to_previous" }],
|
||||
},
|
||||
});
|
||||
});
|
||||
expect(result.current.mutationGuard.proposal?.severity).toBe("blocking");
|
||||
|
||||
await act(async () => {
|
||||
await result.current.mutationGuard.confirmProposal();
|
||||
});
|
||||
|
||||
expect(result.current.mutationGuard.proposal).toBeNull();
|
||||
expect(result.current.mutationGuard.isMutationPending).toBe(false);
|
||||
expect(updateWorkflowStepAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("holds a warning update until confirmation and executes it exactly once", async () => {
|
||||
const steps = [
|
||||
step("work", "Work", 0, true, {
|
||||
autoStart: true,
|
||||
onTurnComplete: [{ type: "move_to_next" }],
|
||||
}),
|
||||
step("review", "Review", 1, false),
|
||||
];
|
||||
const { result } = renderPersistedWorkflowStepActions(steps);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.actions.handleUpdateWorkflowStep("review", {
|
||||
events: { on_turn_complete: [{ type: "move_to_previous" }] },
|
||||
});
|
||||
});
|
||||
|
||||
expect(updateWorkflowStepAction).not.toHaveBeenCalled();
|
||||
expect(result.current.mutationGuard.proposal).toMatchObject({
|
||||
intent: "apply",
|
||||
severity: "warning",
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.mutationGuard.confirmProposal();
|
||||
await result.current.mutationGuard.confirmProposal();
|
||||
});
|
||||
|
||||
expect(updateWorkflowStepAction).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("discards a warning update when confirmation is cancelled", async () => {
|
||||
const steps = [
|
||||
step("work", "Work", 0, true, {
|
||||
autoStart: true,
|
||||
onTurnComplete: [{ type: "move_to_next" }],
|
||||
}),
|
||||
step("review", "Review", 1, false),
|
||||
];
|
||||
const { result } = renderPersistedWorkflowStepActions(steps);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.actions.handleUpdateWorkflowStep("review", {
|
||||
events: { on_turn_complete: [{ type: "move_to_previous" }] },
|
||||
});
|
||||
result.current.mutationGuard.cancelProposal();
|
||||
});
|
||||
|
||||
expect(updateWorkflowStepAction).not.toHaveBeenCalled();
|
||||
expect(result.current.mutationGuard.proposal).toBeNull();
|
||||
});
|
||||
|
||||
it("does not gate an unchanged diagnostic identity or an edit that removes a cycle", async () => {
|
||||
const steps = [
|
||||
step("work", "Work", 0, true, {
|
||||
autoStart: true,
|
||||
onTurnComplete: [{ type: "move_to_next" }],
|
||||
}),
|
||||
step("review", "Review", 1, false, {
|
||||
onTurnComplete: [{ type: "move_to_previous" }],
|
||||
}),
|
||||
];
|
||||
const { result } = renderPersistedWorkflowStepActions(steps);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.actions.handleUpdateWorkflowStep("work", { prompt: "New prompt" });
|
||||
await result.current.actions.handleUpdateWorkflowStep("review", {
|
||||
events: { on_turn_complete: [] },
|
||||
});
|
||||
});
|
||||
|
||||
expect(updateWorkflowStepAction).toHaveBeenCalledTimes(2);
|
||||
expect(result.current.mutationGuard.proposal).toBeNull();
|
||||
});
|
||||
|
||||
it("preflights a delete shape before any side effect", async () => {
|
||||
const work = step("work", "Work", 0, true, {
|
||||
autoStart: true,
|
||||
onTurnComplete: [{ type: "move_to_next" }],
|
||||
});
|
||||
const middle = step("middle", "Middle", 1, false);
|
||||
const review = step("review", "Review", 2, false, {
|
||||
autoStart: true,
|
||||
onTurnComplete: [{ type: "move_to_previous" }],
|
||||
});
|
||||
const { result, setWorkflowSteps } = renderPersistedWorkflowStepActions([work, middle, review]);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.actions.handleRemoveWorkflowStep("middle");
|
||||
});
|
||||
|
||||
expect(getStepTaskCount).not.toHaveBeenCalled();
|
||||
expect(deleteWorkflowStepAction).not.toHaveBeenCalled();
|
||||
expect(setWorkflowSteps).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("preflights a reorder shape with an idle guard before any side effect", async () => {
|
||||
const work = step("work", "Work", 0, true, {
|
||||
autoStart: true,
|
||||
onTurnComplete: [{ type: "move_to_next" }],
|
||||
});
|
||||
const middle = step("middle", "Middle", 1, false);
|
||||
const review = step("review", "Review", 2, false, {
|
||||
autoStart: true,
|
||||
onTurnComplete: [{ type: "move_to_previous" }],
|
||||
});
|
||||
const { result, setWorkflowSteps } = renderPersistedWorkflowStepActions([work, middle, review]);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.actions.handleReorderWorkflowSteps([
|
||||
work,
|
||||
{ ...review, position: 1 },
|
||||
{ ...middle, position: 2 },
|
||||
]);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleUpdateWorkflowStep("step-2", { is_start_step: true });
|
||||
});
|
||||
|
||||
expect(
|
||||
getSteps()
|
||||
.filter((s) => s.is_start_step)
|
||||
.map((s) => s.id),
|
||||
).toEqual(["step-2"]);
|
||||
});
|
||||
|
||||
it("refuses to add, update, remove, or reorder steps when readOnly", async () => {
|
||||
const initialSteps = [step("step-1", "Todo", 0, true), step("step-2", "Plan", 1, false)];
|
||||
const { result, getSteps, refreshWorkflowSteps } =
|
||||
renderReadOnlyWorkflowStepActions(initialSteps);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleAddWorkflowStep();
|
||||
});
|
||||
await act(async () => {
|
||||
await result.current.handleUpdateWorkflowStep("step-2", { name: "Renamed" });
|
||||
});
|
||||
await act(async () => {
|
||||
await result.current.handleRemoveWorkflowStep("step-1");
|
||||
});
|
||||
await act(async () => {
|
||||
await result.current.handleReorderWorkflowSteps([initialSteps[1], initialSteps[0]]);
|
||||
});
|
||||
|
||||
expect(getSteps()).toEqual(initialSteps);
|
||||
expect(createWorkflowStepAction).not.toHaveBeenCalled();
|
||||
expect(updateWorkflowStepAction).not.toHaveBeenCalled();
|
||||
expect(deleteWorkflowStepAction).not.toHaveBeenCalled();
|
||||
expect(reorderWorkflowStepsAction).not.toHaveBeenCalled();
|
||||
expect(refreshWorkflowSteps).not.toHaveBeenCalled();
|
||||
});
|
||||
expect(result.current.mutationGuard.proposal?.severity).toBe("blocking");
|
||||
expect(reorderWorkflowStepsAction).not.toHaveBeenCalled();
|
||||
expect(setWorkflowSteps).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe("useWorkflowDeleteHandlers", () => {
|
||||
it("refuses to open the delete-workflow dialog when readOnly", async () => {
|
||||
const wfDel = {
|
||||
setDeleteOpen: vi.fn(),
|
||||
setWorkflowTaskCount: vi.fn(),
|
||||
setWorkflowDeleteLoading: vi.fn(),
|
||||
setTargetWorkflowId: vi.fn(),
|
||||
setTargetWorkflowSteps: vi.fn(),
|
||||
setTargetStepId: vi.fn(),
|
||||
targetWorkflowId: "",
|
||||
targetStepId: "",
|
||||
setMigrateLoading: vi.fn(),
|
||||
};
|
||||
const { result } = renderHook(() =>
|
||||
useWorkflowDeleteHandlers({
|
||||
workflow,
|
||||
isNewWorkflow: false,
|
||||
readOnly: true,
|
||||
otherWorkflows: [],
|
||||
wfDel,
|
||||
deleteWorkflowRun: vi.fn(),
|
||||
toast: vi.fn(),
|
||||
}),
|
||||
);
|
||||
it("reconciles a successful update from its authoritative response", async () => {
|
||||
const steps = [step("work", "Work", 0, true)];
|
||||
const updated = { ...steps[0], name: "Building" };
|
||||
vi.mocked(updateWorkflowStepAction).mockResolvedValue(updated);
|
||||
const { result, getSteps } = renderPersistedWorkflowStepActions(steps);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleDeleteWorkflowClick();
|
||||
});
|
||||
|
||||
expect(getWorkflowTaskCount).not.toHaveBeenCalled();
|
||||
expect(wfDel.setDeleteOpen).not.toHaveBeenCalled();
|
||||
await act(async () => {
|
||||
await result.current.actions.handleUpdateWorkflowStep("work", { name: "Building" });
|
||||
});
|
||||
|
||||
expect(getSteps()).toEqual([updated]);
|
||||
expect(listWorkflowStepsAction).not.toHaveBeenCalled();
|
||||
expect(result.current.mutationGuard.isMutationPending).toBe(false);
|
||||
});
|
||||
|
||||
describe("useWorkflowSaveActions", () => {
|
||||
it("remaps template workflow pull sources between backend-created and added steps", async () => {
|
||||
const createdWorkflowId = "wf-created" as Workflow["id"];
|
||||
const templateName = "Template Step";
|
||||
const addedName = "Added Step";
|
||||
const backendTemplateId = "backend-template";
|
||||
const backendAddedId = "backend-added";
|
||||
const draftTemplateId = "draft-template";
|
||||
it("appends a successful add from its authoritative response", async () => {
|
||||
const steps = [step("work", "Work", 0, true)];
|
||||
const created = step("created", "Server Step", 1, false);
|
||||
vi.mocked(createWorkflowStepAction).mockResolvedValue(created);
|
||||
const { result, getSteps } = renderPersistedWorkflowStepActions(steps);
|
||||
|
||||
vi.mocked(createWorkflowAction).mockResolvedValue({
|
||||
...workflow,
|
||||
id: createdWorkflowId,
|
||||
workflow_template_id: "template-1",
|
||||
});
|
||||
vi.mocked(listWorkflowStepsAction).mockResolvedValue({
|
||||
steps: [
|
||||
{
|
||||
...step(backendTemplateId, templateName, 0, true),
|
||||
id: backendTemplateId,
|
||||
workflow_id: createdWorkflowId,
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
});
|
||||
vi.mocked(createWorkflowStepAction).mockResolvedValue({
|
||||
...step(backendAddedId, addedName, 1, false),
|
||||
id: backendAddedId,
|
||||
workflow_id: createdWorkflowId,
|
||||
});
|
||||
vi.mocked(updateWorkflowStepAction).mockResolvedValue(
|
||||
step(backendAddedId, addedName, 1, false),
|
||||
);
|
||||
await act(async () => {
|
||||
await result.current.actions.handleAddWorkflowStep();
|
||||
});
|
||||
|
||||
const templateStep = {
|
||||
...step(draftTemplateId, templateName, 0, true),
|
||||
pull_from_step_id: "draft-added",
|
||||
};
|
||||
const addedStep = {
|
||||
...step("draft-added", addedName, 1, false),
|
||||
pull_from_step_id: draftTemplateId,
|
||||
};
|
||||
const { result } = renderHook(() =>
|
||||
useWorkflowSaveActions({
|
||||
workflow: { ...workflow, workflow_template_id: "template-1" },
|
||||
isNewWorkflow: true,
|
||||
workflowSteps: [templateStep, addedStep],
|
||||
templateStepCount: 1,
|
||||
onSaveWorkflow: vi.fn(),
|
||||
onWorkflowCreated: vi.fn(),
|
||||
toast: vi.fn(),
|
||||
}),
|
||||
);
|
||||
expect(getSteps()).toEqual([...steps, created]);
|
||||
expect(listWorkflowStepsAction).not.toHaveBeenCalled();
|
||||
expect(result.current.mutationGuard.isMutationPending).toBe(false);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleSaveWorkflow();
|
||||
});
|
||||
it("reconciles a successful reorder from its authoritative response", async () => {
|
||||
const work = step("work", "Work", 0, true);
|
||||
const review = step("review", "Review", 1, false);
|
||||
const reordered = [
|
||||
{ ...review, position: 0 },
|
||||
{ ...work, position: 1 },
|
||||
];
|
||||
vi.mocked(reorderWorkflowStepsAction).mockResolvedValue({ steps: reordered, total: 2 });
|
||||
const { result, getSteps } = renderPersistedWorkflowStepActions([work, review]);
|
||||
|
||||
expect(createWorkflowStepAction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ pull_from_step_id: "" }),
|
||||
);
|
||||
expect(updateWorkflowStepAction).toHaveBeenCalledWith(backendAddedId, {
|
||||
pull_from_step_id: backendTemplateId,
|
||||
});
|
||||
expect(updateWorkflowStepAction).toHaveBeenCalledWith(backendTemplateId, {
|
||||
pull_from_step_id: backendAddedId,
|
||||
await act(async () => {
|
||||
await result.current.actions.handleReorderWorkflowSteps([review, work]);
|
||||
});
|
||||
|
||||
expect(getSteps()).toEqual(reordered);
|
||||
expect(listWorkflowStepsAction).not.toHaveBeenCalled();
|
||||
expect(result.current.mutationGuard.isMutationPending).toBe(false);
|
||||
});
|
||||
|
||||
it("holds the task migration delete path until a warning is confirmed", async () => {
|
||||
vi.mocked(getStepTaskCount).mockResolvedValue({ task_count: 2 });
|
||||
const work = step("work", "Work", 0, true, {
|
||||
autoStart: true,
|
||||
onTurnComplete: [{ type: "move_to_next" }],
|
||||
});
|
||||
const middle = step("middle", "Middle", 1, false);
|
||||
const review = step("review", "Review", 2, false, {
|
||||
onTurnComplete: [{ type: "move_to_previous" }],
|
||||
});
|
||||
const { result, setStepDeleteOpen } = renderPersistedWorkflowStepActions([work, middle, review]);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.actions.handleRemoveWorkflowStep("middle");
|
||||
});
|
||||
expect(getStepTaskCount).not.toHaveBeenCalled();
|
||||
expect(result.current.mutationGuard.proposal?.severity).toBe("warning");
|
||||
|
||||
await act(async () => {
|
||||
await result.current.mutationGuard.confirmProposal();
|
||||
});
|
||||
|
||||
expect(getStepTaskCount).toHaveBeenCalledTimes(1);
|
||||
expect(setStepDeleteOpen).toHaveBeenCalledWith(true);
|
||||
expect(deleteWorkflowStepAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("adds a step without reconfirming an existing diagnostic", async () => {
|
||||
const steps = [
|
||||
step("work", "Work", 0, true, {
|
||||
autoStart: true,
|
||||
onTurnComplete: [{ type: "move_to_step", config: { step_id: "work" } }],
|
||||
}),
|
||||
];
|
||||
const { result } = renderPersistedWorkflowStepActions(steps);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.actions.handleAddWorkflowStep();
|
||||
});
|
||||
|
||||
expect(createWorkflowStepAction).toHaveBeenCalledTimes(1);
|
||||
expect(result.current.mutationGuard.proposal).toBeNull();
|
||||
});
|
||||
|
||||
it("does not create a draft workflow with a blocking cycle", async () => {
|
||||
const draftSteps = [
|
||||
step("build", "Build", 0, true, {
|
||||
autoStart: true,
|
||||
onTurnComplete: [{ type: "move_to_next" }],
|
||||
}),
|
||||
step("review", "Review", 1, false, {
|
||||
autoStart: true,
|
||||
onTurnComplete: [{ type: "move_to_previous" }],
|
||||
}),
|
||||
];
|
||||
const { result } = renderHook(() => {
|
||||
const mutationGuard = useWorkflowMutationGuard(draftSteps);
|
||||
return useWorkflowSaveActions({
|
||||
workflow: { ...workflow, id: "temp-workflow" as Workflow["id"] },
|
||||
isNewWorkflow: true,
|
||||
workflowSteps: draftSteps,
|
||||
templateStepCount: 0,
|
||||
onSaveWorkflow: vi.fn(),
|
||||
toast: vi.fn(),
|
||||
mutationGuard,
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses to save changes to an existing workflow when readOnly", async () => {
|
||||
const onSaveWorkflow = vi.fn().mockResolvedValue(undefined);
|
||||
const { result } = renderHook(() =>
|
||||
useWorkflowSaveActions({
|
||||
workflow,
|
||||
isNewWorkflow: false,
|
||||
readOnly: true,
|
||||
workflowSteps: [],
|
||||
templateStepCount: 0,
|
||||
onSaveWorkflow,
|
||||
toast: vi.fn(),
|
||||
}),
|
||||
);
|
||||
await act(async () => {
|
||||
await result.current.handleSaveWorkflow();
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleSaveWorkflow();
|
||||
expect(createWorkflowAction).not.toHaveBeenCalled();
|
||||
expect(result.current.mutationGuard.proposal?.severity).toBe("blocking");
|
||||
});
|
||||
|
||||
it("cancels a warning draft with no requests and creates it once after confirmation", async () => {
|
||||
const createdWorkflow = { ...workflow, id: "created-workflow" as Workflow["id"] };
|
||||
vi.mocked(createWorkflowAction).mockResolvedValue(createdWorkflow);
|
||||
vi.mocked(createWorkflowStepAction).mockImplementation(async (payload) => ({
|
||||
...step(`created-${payload.position}`, payload.name, payload.position, false),
|
||||
workflow_id: createdWorkflow.id,
|
||||
}));
|
||||
const draftSteps = [
|
||||
step("work", "Work", 0, true, {
|
||||
autoStart: true,
|
||||
onTurnComplete: [{ type: "move_to_next" }],
|
||||
}),
|
||||
step("review", "Review", 1, false, {
|
||||
onTurnComplete: [{ type: "move_to_previous" }],
|
||||
}),
|
||||
];
|
||||
const { result } = renderHook(() => {
|
||||
const mutationGuard = useWorkflowMutationGuard(draftSteps);
|
||||
return useWorkflowSaveActions({
|
||||
workflow: { ...workflow, id: "temp-workflow" as Workflow["id"] },
|
||||
isNewWorkflow: true,
|
||||
workflowSteps: draftSteps,
|
||||
templateStepCount: 0,
|
||||
onSaveWorkflow: vi.fn(),
|
||||
toast: vi.fn(),
|
||||
mutationGuard,
|
||||
});
|
||||
});
|
||||
|
||||
expect(onSaveWorkflow).not.toHaveBeenCalled();
|
||||
await act(async () => {
|
||||
await result.current.handleSaveWorkflow();
|
||||
result.current.mutationGuard.cancelProposal();
|
||||
});
|
||||
expect(createWorkflowAction).not.toHaveBeenCalled();
|
||||
expect(createWorkflowStepAction).not.toHaveBeenCalled();
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleSaveWorkflow();
|
||||
await result.current.mutationGuard.confirmProposal();
|
||||
await result.current.mutationGuard.confirmProposal();
|
||||
});
|
||||
|
||||
expect(createWorkflowAction).toHaveBeenCalledTimes(1);
|
||||
expect(createWorkflowStepAction).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("remaps template workflow pull sources between backend-created and added steps", async () => {
|
||||
const createdWorkflowId = "wf-created" as Workflow["id"];
|
||||
const templateName = "Template Step";
|
||||
const addedName = "Added Step";
|
||||
const backendTemplateId = "backend-template";
|
||||
const backendAddedId = "backend-added";
|
||||
const draftTemplateId = "draft-template";
|
||||
|
||||
vi.mocked(createWorkflowAction).mockResolvedValue({
|
||||
...workflow,
|
||||
id: createdWorkflowId,
|
||||
workflow_template_id: "template-1",
|
||||
});
|
||||
vi.mocked(listWorkflowStepsAction).mockResolvedValue({
|
||||
steps: [
|
||||
{
|
||||
...step(backendTemplateId, templateName, 0, true),
|
||||
id: backendTemplateId,
|
||||
workflow_id: createdWorkflowId,
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
});
|
||||
vi.mocked(createWorkflowStepAction).mockResolvedValue({
|
||||
...step(backendAddedId, addedName, 1, false),
|
||||
id: backendAddedId,
|
||||
workflow_id: createdWorkflowId,
|
||||
});
|
||||
vi.mocked(updateWorkflowStepAction).mockResolvedValue(step(backendAddedId, addedName, 1, false));
|
||||
|
||||
const templateStep = {
|
||||
...step(draftTemplateId, templateName, 0, true),
|
||||
pull_from_step_id: "draft-added",
|
||||
};
|
||||
const addedStep = {
|
||||
...step("draft-added", addedName, 1, false),
|
||||
pull_from_step_id: draftTemplateId,
|
||||
};
|
||||
const workflowSteps = [templateStep, addedStep];
|
||||
const { result } = renderHook(() => {
|
||||
const mutationGuard = useWorkflowMutationGuard(workflowSteps);
|
||||
return useWorkflowSaveActions({
|
||||
workflow: { ...workflow, workflow_template_id: "template-1" },
|
||||
isNewWorkflow: true,
|
||||
workflowSteps,
|
||||
templateStepCount: 1,
|
||||
onSaveWorkflow: vi.fn(),
|
||||
onWorkflowCreated: vi.fn(),
|
||||
toast: vi.fn(),
|
||||
mutationGuard,
|
||||
});
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleSaveWorkflow();
|
||||
});
|
||||
|
||||
expect(createWorkflowStepAction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ pull_from_step_id: "" }),
|
||||
);
|
||||
expect(updateWorkflowStepAction).toHaveBeenCalledWith(backendAddedId, {
|
||||
pull_from_step_id: backendTemplateId,
|
||||
});
|
||||
expect(updateWorkflowStepAction).toHaveBeenCalledWith(backendTemplateId, {
|
||||
pull_from_step_id: backendAddedId,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,6 @@ import { useEffect } from "react";
|
||||
import type { Workflow, WorkflowStep } from "@/lib/types/http";
|
||||
import { useToast } from "@/components/toast-provider";
|
||||
import { useRequest } from "@/lib/http/use-request";
|
||||
import { generateUUID } from "@/lib/utils";
|
||||
import {
|
||||
createWorkflowAction,
|
||||
createWorkflowStepAction,
|
||||
@@ -17,33 +16,35 @@ import {
|
||||
exportWorkflowAction,
|
||||
bulkMoveTasks,
|
||||
} from "@/app/actions/workspaces";
|
||||
import type { WorkflowMutationGuardController } from "./workflow-mutation-guard";
|
||||
import {
|
||||
addLocalStep,
|
||||
addRemoteStep,
|
||||
applyWorkflowStepUpdates,
|
||||
newWorkflowStep,
|
||||
removeLocalStep,
|
||||
updateRemoteWorkflowStep,
|
||||
} from "./workflow-step-mutations";
|
||||
|
||||
const FALLBACK_ERROR_MESSAGE = "Request failed";
|
||||
|
||||
type WorkflowStepActionsParams = {
|
||||
workflow: Workflow;
|
||||
isNewWorkflow: boolean;
|
||||
/**
|
||||
* Workflows synced from GitHub (`workflow.source === "github"`) are
|
||||
* read-only in the UI; the backend also rejects step mutations with a 409.
|
||||
* Gating here is defense-in-depth in case a disabled control is somehow
|
||||
* still triggered.
|
||||
*/
|
||||
readOnly?: boolean;
|
||||
workflowSteps: WorkflowStep[];
|
||||
setWorkflowSteps: (updater: ((prev: WorkflowStep[]) => WorkflowStep[]) | WorkflowStep[]) => void;
|
||||
refreshWorkflowSteps: () => Promise<void>;
|
||||
setStepToDelete: (id: string | null) => void;
|
||||
setStepTaskCount: (count: number | null) => void;
|
||||
setTargetStepForMigration: (id: string) => void;
|
||||
setStepDeleteOpen: (open: boolean) => void;
|
||||
toast: ReturnType<typeof useToast>["toast"];
|
||||
mutationGuard: WorkflowMutationGuardController;
|
||||
};
|
||||
|
||||
type RemoveStepParams = {
|
||||
stepId: string;
|
||||
workflowSteps: WorkflowStep[];
|
||||
refreshWorkflowSteps: () => Promise<void>;
|
||||
setWorkflowSteps: (updater: (prev: WorkflowStep[]) => WorkflowStep[]) => void;
|
||||
setStepToDelete: (id: string | null) => void;
|
||||
setStepTaskCount: (count: number | null) => void;
|
||||
setTargetStepForMigration: (id: string) => void;
|
||||
@@ -54,7 +55,7 @@ type RemoveStepParams = {
|
||||
async function removeWorkflowStep({
|
||||
stepId,
|
||||
workflowSteps,
|
||||
refreshWorkflowSteps,
|
||||
setWorkflowSteps,
|
||||
setStepToDelete,
|
||||
setStepTaskCount,
|
||||
setTargetStepForMigration,
|
||||
@@ -65,7 +66,11 @@ async function removeWorkflowStep({
|
||||
const { task_count } = await getStepTaskCount(stepId);
|
||||
if (task_count === 0) {
|
||||
await deleteWorkflowStepAction(stepId);
|
||||
await refreshWorkflowSteps();
|
||||
setWorkflowSteps((previous) =>
|
||||
previous
|
||||
.filter((step) => step.id !== stepId)
|
||||
.map((step, position) => ({ ...step, position })),
|
||||
);
|
||||
return;
|
||||
}
|
||||
setStepToDelete(stepId);
|
||||
@@ -82,73 +87,18 @@ async function removeWorkflowStep({
|
||||
}
|
||||
}
|
||||
|
||||
const NEW_STEP_DEFAULTS = { name: "New Step", color: "bg-slate-500" } as const;
|
||||
|
||||
function addLocalStep(
|
||||
workflow: Workflow,
|
||||
setWorkflowSteps: WorkflowStepActionsParams["setWorkflowSteps"],
|
||||
) {
|
||||
setWorkflowSteps((prev) => [
|
||||
...prev,
|
||||
{
|
||||
id: `temp-step-${generateUUID()}`,
|
||||
workflow_id: workflow.id,
|
||||
...NEW_STEP_DEFAULTS,
|
||||
position: prev.length,
|
||||
allow_manual_move: true,
|
||||
created_at: "",
|
||||
updated_at: "",
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
async function addRemoteStep(
|
||||
workflow: Workflow,
|
||||
stepCount: number,
|
||||
refreshWorkflowSteps: () => Promise<void>,
|
||||
toast: WorkflowStepActionsParams["toast"],
|
||||
) {
|
||||
try {
|
||||
await createWorkflowStepAction({
|
||||
workflow_id: workflow.id,
|
||||
...NEW_STEP_DEFAULTS,
|
||||
position: stepCount,
|
||||
});
|
||||
await refreshWorkflowSteps();
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Failed to add workflow step",
|
||||
description: error instanceof Error ? error.message : FALLBACK_ERROR_MESSAGE,
|
||||
variant: "error",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function applyWorkflowStepUpdates(
|
||||
steps: WorkflowStep[],
|
||||
stepId: string,
|
||||
updates: Partial<WorkflowStep>,
|
||||
): WorkflowStep[] {
|
||||
const isSettingStartStep = updates.is_start_step === true;
|
||||
return steps.map((step) => {
|
||||
if (step.id === stepId) return { ...step, ...updates };
|
||||
if (isSettingStartStep) return { ...step, is_start_step: false };
|
||||
return step;
|
||||
});
|
||||
}
|
||||
|
||||
export function useWorkflowStepActions({
|
||||
workflow,
|
||||
isNewWorkflow,
|
||||
readOnly = false,
|
||||
workflowSteps,
|
||||
setWorkflowSteps,
|
||||
refreshWorkflowSteps,
|
||||
setStepToDelete,
|
||||
setStepTaskCount,
|
||||
setTargetStepForMigration,
|
||||
setStepDeleteOpen,
|
||||
toast,
|
||||
mutationGuard,
|
||||
}: WorkflowStepActionsParams) {
|
||||
const handleUpdateWorkflowStep = async (stepId: string, updates: Partial<WorkflowStep>) => {
|
||||
if (readOnly) return;
|
||||
@@ -156,66 +106,79 @@ export function useWorkflowStepActions({
|
||||
setWorkflowSteps((prev) => applyWorkflowStepUpdates(prev, stepId, updates));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await updateWorkflowStepAction(stepId, updates);
|
||||
await refreshWorkflowSteps();
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Failed to update workflow step",
|
||||
description: error instanceof Error ? error.message : FALLBACK_ERROR_MESSAGE,
|
||||
variant: "error",
|
||||
});
|
||||
}
|
||||
const proposedSteps = applyWorkflowStepUpdates(workflowSteps, stepId, updates);
|
||||
await mutationGuard.guardMutation({
|
||||
proposedSteps,
|
||||
operation: () => updateRemoteWorkflowStep({ stepId, updates, setWorkflowSteps, toast }),
|
||||
});
|
||||
};
|
||||
|
||||
const handleAddWorkflowStep = async () => {
|
||||
if (readOnly) return;
|
||||
if (isNewWorkflow) {
|
||||
addLocalStep(workflow, setWorkflowSteps);
|
||||
return;
|
||||
}
|
||||
await addRemoteStep(workflow, workflowSteps.length, refreshWorkflowSteps, toast);
|
||||
const proposedSteps = [
|
||||
...workflowSteps,
|
||||
newWorkflowStep(workflow, workflowSteps.length, `proposed-step-${workflow.id}`),
|
||||
];
|
||||
await mutationGuard.guardMutation({
|
||||
proposedSteps,
|
||||
operation: () => addRemoteStep(workflow, workflowSteps.length, setWorkflowSteps, toast),
|
||||
});
|
||||
};
|
||||
|
||||
const handleRemoveWorkflowStep = async (stepId: string) => {
|
||||
if (readOnly) return;
|
||||
if (isNewWorkflow) {
|
||||
setWorkflowSteps((prev) =>
|
||||
prev.filter((s) => s.id !== stepId).map((s, i) => ({ ...s, position: i })),
|
||||
);
|
||||
removeLocalStep(stepId, setWorkflowSteps);
|
||||
return;
|
||||
}
|
||||
await removeWorkflowStep({
|
||||
stepId,
|
||||
workflowSteps,
|
||||
refreshWorkflowSteps,
|
||||
setStepToDelete,
|
||||
setStepTaskCount,
|
||||
setTargetStepForMigration,
|
||||
setStepDeleteOpen,
|
||||
toast,
|
||||
const proposedSteps = workflowSteps
|
||||
.filter((step) => step.id !== stepId)
|
||||
.map((step, position) => ({ ...step, position }));
|
||||
await mutationGuard.guardMutation({
|
||||
proposedSteps,
|
||||
operation: () =>
|
||||
removeWorkflowStep({
|
||||
stepId,
|
||||
workflowSteps,
|
||||
setWorkflowSteps,
|
||||
setStepToDelete,
|
||||
setStepTaskCount,
|
||||
setTargetStepForMigration,
|
||||
setStepDeleteOpen,
|
||||
toast,
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
const handleReorderWorkflowSteps = async (reorderedSteps: WorkflowStep[]) => {
|
||||
if (readOnly) return;
|
||||
setWorkflowSteps(reorderedSteps);
|
||||
if (isNewWorkflow) return;
|
||||
try {
|
||||
await reorderWorkflowStepsAction(
|
||||
workflow.id,
|
||||
reorderedSteps.map((s) => s.id),
|
||||
);
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Failed to reorder workflow steps",
|
||||
description: error instanceof Error ? error.message : FALLBACK_ERROR_MESSAGE,
|
||||
variant: "error",
|
||||
});
|
||||
await refreshWorkflowSteps();
|
||||
const proposedSteps = reorderedSteps.map((step, position) => ({ ...step, position }));
|
||||
if (isNewWorkflow) {
|
||||
setWorkflowSteps(proposedSteps);
|
||||
return;
|
||||
}
|
||||
await mutationGuard.guardMutation({
|
||||
proposedSteps,
|
||||
operation: async () => {
|
||||
setWorkflowSteps(proposedSteps);
|
||||
try {
|
||||
const response = await reorderWorkflowStepsAction(
|
||||
workflow.id,
|
||||
proposedSteps.map((step) => step.id),
|
||||
);
|
||||
setWorkflowSteps(response.steps);
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Failed to reorder workflow steps",
|
||||
description: error instanceof Error ? error.message : FALLBACK_ERROR_MESSAGE,
|
||||
variant: "error",
|
||||
});
|
||||
setWorkflowSteps(workflowSteps);
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
handleUpdateWorkflowStep,
|
||||
handleAddWorkflowStep,
|
||||
@@ -227,7 +190,6 @@ export function useWorkflowStepActions({
|
||||
type WorkflowDeleteHandlersParams = {
|
||||
workflow: Workflow;
|
||||
isNewWorkflow: boolean;
|
||||
/** See `WorkflowStepActionsParams.readOnly` — defense-in-depth for synced workflows. */
|
||||
readOnly?: boolean;
|
||||
otherWorkflows: Workflow[];
|
||||
wfDel: {
|
||||
@@ -303,8 +265,6 @@ export function useWorkflowDeleteHandlers({
|
||||
};
|
||||
|
||||
const handleDeleteWorkflow = async () => {
|
||||
// A background sync can flip the workflow read-only while the delete
|
||||
// dialog is already open; re-check at confirm time.
|
||||
if (readOnly) return;
|
||||
try {
|
||||
await deleteWorkflowRun();
|
||||
@@ -343,7 +303,6 @@ export function useWorkflowDeleteHandlers({
|
||||
|
||||
return { handleDeleteWorkflowClick, handleDeleteWorkflow, handleMigrateAndDeleteWorkflow };
|
||||
}
|
||||
|
||||
type StepDeleteHandlersParams = {
|
||||
workflow: Workflow;
|
||||
stepDel: {
|
||||
@@ -353,28 +312,33 @@ type StepDeleteHandlersParams = {
|
||||
setStepDeleteOpen: (v: boolean) => void;
|
||||
setStepToDelete: (v: string | null) => void;
|
||||
};
|
||||
refreshWorkflowSteps: () => Promise<void>;
|
||||
setWorkflowSteps: (updater: (prev: WorkflowStep[]) => WorkflowStep[]) => void;
|
||||
toast: ReturnType<typeof useToast>["toast"];
|
||||
};
|
||||
|
||||
export function useStepDeleteHandlers({
|
||||
workflow,
|
||||
stepDel,
|
||||
refreshWorkflowSteps,
|
||||
setWorkflowSteps,
|
||||
toast,
|
||||
}: StepDeleteHandlersParams) {
|
||||
const handleMigrateAndDeleteStep = async () => {
|
||||
if (!stepDel.stepToDelete || !stepDel.targetStepForMigration) return;
|
||||
const stepId = stepDel.stepToDelete;
|
||||
stepDel.setStepMigrateLoading(true);
|
||||
try {
|
||||
await bulkMoveTasks({
|
||||
source_workflow_id: workflow.id,
|
||||
source_step_id: stepDel.stepToDelete,
|
||||
source_step_id: stepId,
|
||||
target_workflow_id: workflow.id,
|
||||
target_step_id: stepDel.targetStepForMigration,
|
||||
});
|
||||
await deleteWorkflowStepAction(stepDel.stepToDelete);
|
||||
await refreshWorkflowSteps();
|
||||
await deleteWorkflowStepAction(stepId);
|
||||
setWorkflowSteps((previous) =>
|
||||
previous
|
||||
.filter((step) => step.id !== stepId)
|
||||
.map((step, position) => ({ ...step, position })),
|
||||
);
|
||||
stepDel.setStepDeleteOpen(false);
|
||||
stepDel.setStepToDelete(null);
|
||||
} catch (error) {
|
||||
@@ -390,10 +354,15 @@ export function useStepDeleteHandlers({
|
||||
|
||||
const handleDeleteStepAndTasks = async () => {
|
||||
if (!stepDel.stepToDelete) return;
|
||||
const stepId = stepDel.stepToDelete;
|
||||
stepDel.setStepMigrateLoading(true);
|
||||
try {
|
||||
await deleteWorkflowStepAction(stepDel.stepToDelete);
|
||||
await refreshWorkflowSteps();
|
||||
await deleteWorkflowStepAction(stepId);
|
||||
setWorkflowSteps((previous) =>
|
||||
previous
|
||||
.filter((step) => step.id !== stepId)
|
||||
.map((step, position) => ({ ...step, position })),
|
||||
);
|
||||
stepDel.setStepDeleteOpen(false);
|
||||
stepDel.setStepToDelete(null);
|
||||
} catch (error) {
|
||||
@@ -525,13 +494,13 @@ async function reconcileTemplateSteps(
|
||||
type WorkflowSaveActionsParams = {
|
||||
workflow: Workflow;
|
||||
isNewWorkflow: boolean;
|
||||
/** See `WorkflowStepActionsParams.readOnly` — defense-in-depth for synced workflows. */
|
||||
readOnly?: boolean;
|
||||
workflowSteps: WorkflowStep[];
|
||||
templateStepCount: number;
|
||||
onSaveWorkflow: () => Promise<unknown>;
|
||||
onWorkflowCreated?: (created: Workflow) => void;
|
||||
toast: ReturnType<typeof useToast>["toast"];
|
||||
mutationGuard: WorkflowMutationGuardController;
|
||||
};
|
||||
|
||||
export function useWorkflowSaveActions({
|
||||
@@ -543,6 +512,7 @@ export function useWorkflowSaveActions({
|
||||
onSaveWorkflow,
|
||||
onWorkflowCreated,
|
||||
toast,
|
||||
mutationGuard,
|
||||
}: WorkflowSaveActionsParams) {
|
||||
const saveWorkflowRequest = useRequest(onSaveWorkflow);
|
||||
|
||||
@@ -567,8 +537,7 @@ export function useWorkflowSaveActions({
|
||||
|
||||
const activeSaveRequest = isNewWorkflow ? saveNewWorkflowRequest : saveWorkflowRequest;
|
||||
|
||||
const handleSaveWorkflow = async () => {
|
||||
if (readOnly) return;
|
||||
const runSaveWorkflow = async () => {
|
||||
try {
|
||||
if (isNewWorkflow) await saveNewWorkflowRequest.run();
|
||||
else await saveWorkflowRequest.run();
|
||||
@@ -581,7 +550,21 @@ export function useWorkflowSaveActions({
|
||||
}
|
||||
};
|
||||
|
||||
return { activeSaveRequest, handleSaveWorkflow };
|
||||
const handleSaveWorkflow = async () => {
|
||||
if (readOnly) return;
|
||||
if (!isNewWorkflow) {
|
||||
await runSaveWorkflow();
|
||||
return;
|
||||
}
|
||||
await mutationGuard.guardMutation({
|
||||
baselineSteps: [],
|
||||
proposedSteps: workflowSteps,
|
||||
intent: "create",
|
||||
operation: runSaveWorkflow,
|
||||
});
|
||||
};
|
||||
|
||||
return { activeSaveRequest, handleSaveWorkflow, mutationGuard };
|
||||
}
|
||||
|
||||
type WorkflowExportActionsParams = {
|
||||
|
||||
@@ -3,13 +3,14 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { IconDownload, IconTrash } from "@tabler/icons-react";
|
||||
import { Card, CardContent } from "@kandev/ui/card";
|
||||
import { Badge } from "@kandev/ui/badge";
|
||||
import { Button } from "@kandev/ui/button";
|
||||
import { Badge } from "@kandev/ui/badge";
|
||||
import { Input } from "@kandev/ui/input";
|
||||
import { Label } from "@kandev/ui/label";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
|
||||
import type { Workflow, WorkflowStep } from "@/lib/types/http";
|
||||
import type { WorkflowReplayCycleDiagnostic } from "@/lib/workflows/replay-cycle-analysis";
|
||||
import { useHealthyAgentProfiles } from "@/hooks/domains/settings/use-healthy-agent-profiles";
|
||||
import { useRequest } from "@/lib/http/use-request";
|
||||
import { useToast } from "@/components/toast-provider";
|
||||
@@ -26,6 +27,8 @@ import {
|
||||
useWorkflowSaveActions,
|
||||
handleExportWorkflow,
|
||||
} from "./workflow-card-actions";
|
||||
import { useWorkflowMutationGuard } from "./workflow-mutation-guard";
|
||||
import { WorkflowCycleGuardDialog } from "./workflow-cycle-diagnostic";
|
||||
|
||||
type WorkflowCardProps = {
|
||||
workflow: Workflow;
|
||||
@@ -76,16 +79,7 @@ function useWorkflowSteps(
|
||||
};
|
||||
}, [workflowId, initialSteps, isNewWorkflow, toast]);
|
||||
|
||||
const refreshWorkflowSteps = async () => {
|
||||
try {
|
||||
const res = await listWorkflowStepsAction(workflowId);
|
||||
setWorkflowSteps(res.steps ?? []);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
|
||||
return { workflowSteps, setWorkflowSteps, workflowLoading, refreshWorkflowSteps };
|
||||
return { workflowSteps, setWorkflowSteps, workflowLoading };
|
||||
}
|
||||
|
||||
type WorkflowDeleteState = {
|
||||
@@ -176,17 +170,13 @@ type WorkflowCardActionsProps = {
|
||||
};
|
||||
|
||||
const SYNCED_READ_ONLY_REASON =
|
||||
"Managed by workflow sync — edit or remove it in the synced repository";
|
||||
"Managed by workflow sync - edit or remove it in the synced repository";
|
||||
|
||||
function DeleteWorkflowButton({
|
||||
onDeleteClick,
|
||||
deleteDisabled,
|
||||
readOnly,
|
||||
}: {
|
||||
onDeleteClick: () => Promise<void>;
|
||||
deleteDisabled: boolean;
|
||||
readOnly: boolean;
|
||||
}) {
|
||||
}: Pick<WorkflowCardActionsProps, "onDeleteClick" | "deleteDisabled" | "readOnly">) {
|
||||
const button = (
|
||||
<Button
|
||||
type="button"
|
||||
@@ -202,7 +192,6 @@ function DeleteWorkflowButton({
|
||||
);
|
||||
|
||||
if (!readOnly) return button;
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
@@ -264,10 +253,12 @@ type WorkflowCardDialogsProps = {
|
||||
handleMigrateAndDeleteStep: () => Promise<void>;
|
||||
handleDeleteStepAndTasks: () => Promise<void>;
|
||||
};
|
||||
mutationGuard: ReturnType<typeof useWorkflowMutationGuard>;
|
||||
};
|
||||
|
||||
type WorkflowCardBodyProps = {
|
||||
workflow: Workflow;
|
||||
readOnly: boolean;
|
||||
isWorkflowDirty: boolean;
|
||||
onUpdateWorkflow: (updates: {
|
||||
name?: string;
|
||||
@@ -276,21 +267,18 @@ type WorkflowCardBodyProps = {
|
||||
}) => void;
|
||||
activeSaveRequest: { isLoading: boolean; status: "idle" | "loading" | "success" | "error" };
|
||||
handleSaveWorkflow: () => Promise<void>;
|
||||
mutationPending: boolean;
|
||||
workflowLoading: boolean;
|
||||
workflowSteps: WorkflowStep[];
|
||||
diagnostics: WorkflowReplayCycleDiagnostic[];
|
||||
stepActions: {
|
||||
handleUpdateWorkflowStep: (id: string, updates: Partial<WorkflowStep>) => Promise<void>;
|
||||
handleAddWorkflowStep: () => Promise<void>;
|
||||
handleRemoveWorkflowStep: (id: string) => Promise<void>;
|
||||
handleReorderWorkflowSteps: (steps: WorkflowStep[]) => Promise<void>;
|
||||
};
|
||||
readOnly: boolean;
|
||||
};
|
||||
|
||||
// SyncedBadge marks workflows managed by workflow sync (workflow.source ===
|
||||
// "github"). Hovering / focusing shows which repo-relative file it came from
|
||||
// so users don't accidentally edit a workflow that the next poll will
|
||||
// overwrite.
|
||||
function SyncedBadge({ sourcePath }: { sourcePath?: string }) {
|
||||
return (
|
||||
<Tooltip>
|
||||
@@ -305,7 +293,7 @@ function SyncedBadge({ sourcePath }: { sourcePath?: string }) {
|
||||
</Badge>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
Read-only — managed by workflow sync from {sourcePath || "a configured repository"}. Edit or
|
||||
Read-only - managed by workflow sync from {sourcePath || "a configured repository"}. Edit or
|
||||
remove it in the synced repository.
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
@@ -314,14 +302,16 @@ function SyncedBadge({ sourcePath }: { sourcePath?: string }) {
|
||||
|
||||
function WorkflowCardBody({
|
||||
workflow,
|
||||
readOnly,
|
||||
isWorkflowDirty,
|
||||
onUpdateWorkflow,
|
||||
activeSaveRequest,
|
||||
handleSaveWorkflow,
|
||||
mutationPending,
|
||||
workflowLoading,
|
||||
workflowSteps,
|
||||
diagnostics,
|
||||
stepActions,
|
||||
readOnly,
|
||||
}: WorkflowCardBodyProps) {
|
||||
const healthyProfiles = useHealthyAgentProfiles(workflow.agent_profile_id);
|
||||
|
||||
@@ -333,11 +323,6 @@ function WorkflowCardBody({
|
||||
<span>Workflow Name</span>
|
||||
{isWorkflowDirty && <UnsavedChangesBadge />}
|
||||
{readOnly && <SyncedBadge sourcePath={workflow.source_path} />}
|
||||
{readOnly && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Read-only — managed by workflow sync
|
||||
</span>
|
||||
)}
|
||||
</Label>
|
||||
<Input
|
||||
value={workflow.name}
|
||||
@@ -352,10 +337,10 @@ function WorkflowCardBody({
|
||||
</Label>
|
||||
<Select
|
||||
value={workflow.agent_profile_id || "none"}
|
||||
disabled={readOnly}
|
||||
onValueChange={(value) =>
|
||||
onUpdateWorkflow({ agent_profile_id: value === "none" ? "" : value })
|
||||
}
|
||||
disabled={readOnly}
|
||||
>
|
||||
<SelectTrigger
|
||||
className="w-full cursor-pointer"
|
||||
@@ -380,7 +365,7 @@ function WorkflowCardBody({
|
||||
isLoading={activeSaveRequest.isLoading}
|
||||
status={activeSaveRequest.status}
|
||||
onClick={handleSaveWorkflow}
|
||||
disabled={readOnly}
|
||||
disabled={mutationPending || readOnly}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
@@ -390,11 +375,12 @@ function WorkflowCardBody({
|
||||
) : (
|
||||
<WorkflowPipelineEditor
|
||||
steps={workflowSteps}
|
||||
diagnostics={diagnostics}
|
||||
onUpdateStep={stepActions.handleUpdateWorkflowStep}
|
||||
onAddStep={stepActions.handleAddWorkflowStep}
|
||||
onRemoveStep={stepActions.handleRemoveWorkflowStep}
|
||||
onReorderSteps={stepActions.handleReorderWorkflowSteps}
|
||||
readOnly={readOnly}
|
||||
readOnly={mutationPending || readOnly}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -413,6 +399,7 @@ function WorkflowCardDialogs({
|
||||
stepDel,
|
||||
stepsForStepMigration,
|
||||
stepDeleteHandlers,
|
||||
mutationGuard,
|
||||
}: WorkflowCardDialogsProps) {
|
||||
return (
|
||||
<>
|
||||
@@ -448,6 +435,11 @@ function WorkflowCardDialogs({
|
||||
onMigrateAndDelete={stepDeleteHandlers.handleMigrateAndDeleteStep}
|
||||
onDeleteAndTasks={stepDeleteHandlers.handleDeleteStepAndTasks}
|
||||
/>
|
||||
<WorkflowCycleGuardDialog
|
||||
proposal={mutationGuard.proposal}
|
||||
onCancel={mutationGuard.cancelProposal}
|
||||
onConfirm={mutationGuard.confirmProposal}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -461,25 +453,27 @@ function useWorkflowCardState(props: WorkflowCardProps) {
|
||||
const wfDel = useWorkflowDeleteState();
|
||||
const stepDel = useStepDeleteState();
|
||||
const isNewWorkflow = workflow.id.startsWith("temp-");
|
||||
// Workflows synced from a configured GitHub repo are read-only: the
|
||||
// backend rejects definition mutations with a 409, so the UI disables the
|
||||
// matching affordances (name/agent-profile/steps/delete) up front.
|
||||
const readOnly = workflow.source === "github";
|
||||
const deleteWorkflowRequest = useRequest(onDeleteWorkflow);
|
||||
const { workflowSteps, setWorkflowSteps, workflowLoading, refreshWorkflowSteps } =
|
||||
useWorkflowSteps(workflow.id, initialWorkflowSteps, isNewWorkflow, toast);
|
||||
const { workflowSteps, setWorkflowSteps, workflowLoading } = useWorkflowSteps(
|
||||
workflow.id,
|
||||
initialWorkflowSteps,
|
||||
isNewWorkflow,
|
||||
toast,
|
||||
);
|
||||
const mutationGuard = useWorkflowMutationGuard(workflowSteps);
|
||||
const stepActions = useWorkflowStepActions({
|
||||
workflow,
|
||||
isNewWorkflow,
|
||||
readOnly,
|
||||
workflowSteps,
|
||||
setWorkflowSteps,
|
||||
refreshWorkflowSteps,
|
||||
setStepToDelete: stepDel.setStepToDelete,
|
||||
setStepTaskCount: stepDel.setStepTaskCount,
|
||||
setTargetStepForMigration: stepDel.setTargetStepForMigration,
|
||||
setStepDeleteOpen: stepDel.setStepDeleteOpen,
|
||||
toast,
|
||||
mutationGuard,
|
||||
});
|
||||
const { activeSaveRequest, handleSaveWorkflow } = useWorkflowSaveActions({
|
||||
workflow,
|
||||
@@ -490,6 +484,7 @@ function useWorkflowCardState(props: WorkflowCardProps) {
|
||||
onSaveWorkflow,
|
||||
onWorkflowCreated,
|
||||
toast,
|
||||
mutationGuard,
|
||||
});
|
||||
const wfDeleteHandlers = useWorkflowDeleteHandlers({
|
||||
workflow,
|
||||
@@ -503,7 +498,7 @@ function useWorkflowCardState(props: WorkflowCardProps) {
|
||||
const stepDeleteHandlers = useStepDeleteHandlers({
|
||||
workflow,
|
||||
stepDel,
|
||||
refreshWorkflowSteps,
|
||||
setWorkflowSteps,
|
||||
toast,
|
||||
});
|
||||
const stepsForStepMigration = stepDel.stepToDelete
|
||||
@@ -522,6 +517,7 @@ function useWorkflowCardState(props: WorkflowCardProps) {
|
||||
deleteWorkflowRequest,
|
||||
workflowSteps,
|
||||
workflowLoading,
|
||||
mutationGuard,
|
||||
stepActions,
|
||||
activeSaveRequest,
|
||||
handleSaveWorkflow,
|
||||
@@ -544,14 +540,16 @@ export function WorkflowCard(props: WorkflowCardProps) {
|
||||
<div className="space-y-4">
|
||||
<WorkflowCardBody
|
||||
workflow={workflow}
|
||||
readOnly={s.readOnly}
|
||||
isWorkflowDirty={isWorkflowDirty}
|
||||
onUpdateWorkflow={onUpdateWorkflow}
|
||||
activeSaveRequest={s.activeSaveRequest}
|
||||
handleSaveWorkflow={s.handleSaveWorkflow}
|
||||
mutationPending={s.mutationGuard.isMutationPending}
|
||||
workflowLoading={s.workflowLoading}
|
||||
workflowSteps={s.workflowSteps}
|
||||
diagnostics={s.mutationGuard.diagnostics}
|
||||
stepActions={s.stepActions}
|
||||
readOnly={s.readOnly}
|
||||
/>
|
||||
<WorkflowCardActions
|
||||
isNewWorkflow={s.isNewWorkflow}
|
||||
@@ -561,7 +559,10 @@ export function WorkflowCard(props: WorkflowCardProps) {
|
||||
toast={s.toast}
|
||||
onDeleteClick={s.wfDeleteHandlers.handleDeleteWorkflowClick}
|
||||
deleteDisabled={
|
||||
s.deleteWorkflowRequest.isLoading || s.wfDel.workflowDeleteLoading || s.readOnly
|
||||
s.mutationGuard.isMutationPending ||
|
||||
s.deleteWorkflowRequest.isLoading ||
|
||||
s.wfDel.workflowDeleteLoading ||
|
||||
s.readOnly
|
||||
}
|
||||
readOnly={s.readOnly}
|
||||
/>
|
||||
@@ -578,6 +579,7 @@ export function WorkflowCard(props: WorkflowCardProps) {
|
||||
stepDel={s.stepDel}
|
||||
stepsForStepMigration={s.stepsForStepMigration}
|
||||
stepDeleteHandlers={s.stepDeleteHandlers}
|
||||
mutationGuard={s.mutationGuard}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import type { WorkflowStep } from "@/lib/types/http";
|
||||
import type { WorkflowReplayCycleDiagnostic } from "@/lib/workflows/replay-cycle-analysis";
|
||||
import { WorkflowPipelineEditor } from "./workflow-pipeline-editor";
|
||||
import { WorkflowCycleDiagnostic, WorkflowCycleGuardDialog } from "./workflow-cycle-diagnostic";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
const AUTO_START_STEP_NAME = "In Progress";
|
||||
|
||||
const diagnostic: WorkflowReplayCycleDiagnostic = {
|
||||
identity: "cycle-work-review",
|
||||
severity: "warning",
|
||||
autoStartStepId: "work",
|
||||
autoStartStepName: AUTO_START_STEP_NAME,
|
||||
affectedStepIds: ["work", "review", "done"],
|
||||
trace: [
|
||||
{
|
||||
sourceStepId: "work",
|
||||
sourceStepName: AUTO_START_STEP_NAME,
|
||||
trigger: "on_turn_complete",
|
||||
actionKind: "move_to_next",
|
||||
destinationStepId: "review",
|
||||
destinationStepName: "Review",
|
||||
requiresUserInvolvement: false,
|
||||
},
|
||||
{
|
||||
sourceStepId: "review",
|
||||
sourceStepName: "Review",
|
||||
trigger: "on_turn_start",
|
||||
actionKind: "move_to_step",
|
||||
destinationStepId: "done",
|
||||
destinationStepName: "Done",
|
||||
requiresUserInvolvement: true,
|
||||
},
|
||||
{
|
||||
sourceStepId: "done",
|
||||
sourceStepName: "Done",
|
||||
trigger: "on_turn_complete",
|
||||
actionKind: "move_to_previous",
|
||||
destinationStepId: "work",
|
||||
destinationStepName: AUTO_START_STEP_NAME,
|
||||
requiresUserInvolvement: true,
|
||||
},
|
||||
],
|
||||
promptSource: "task_description",
|
||||
};
|
||||
|
||||
function workflowStep(id: string, name: string, position: number): WorkflowStep {
|
||||
return {
|
||||
id,
|
||||
workflow_id: "workflow-1",
|
||||
name,
|
||||
position,
|
||||
color: "bg-slate-500",
|
||||
created_at: "2026-07-15T00:00:00.000Z",
|
||||
updated_at: "2026-07-15T00:00:00.000Z",
|
||||
} as WorkflowStep;
|
||||
}
|
||||
|
||||
describe("WorkflowCycleDiagnostic", () => {
|
||||
it("renders severity, the exact ordered trace, user-required hops, and prompt source", () => {
|
||||
render(<WorkflowCycleDiagnostic diagnostic={diagnostic} />);
|
||||
|
||||
expect(screen.getByText("Potential repeated agent run")).toBeTruthy();
|
||||
const hops = screen.getAllByRole("listitem");
|
||||
expect(hops).toHaveLength(3);
|
||||
expect(hops[0].textContent).toContain("In ProgressReviewOn turn completeMove to next step");
|
||||
expect(hops[1].textContent).toContain("ReviewDoneOn turn startMove to specific step");
|
||||
expect(hops[2].textContent).toContain("DoneIn ProgressOn turn completeMove to previous step");
|
||||
expect(within(hops[0]).queryByText("User action required")).toBeNull();
|
||||
expect(within(hops[1]).getByText("User action required")).toBeTruthy();
|
||||
expect(within(hops[2]).getByText("User action required")).toBeTruthy();
|
||||
expect(
|
||||
screen.getByText(/has no step prompt, so re-entering it sends the task description/i),
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"step_prompt_with_task_description" as const,
|
||||
/rendered step prompt including the task description/i,
|
||||
],
|
||||
["step_prompt" as const, /step prompt instead of the task description/i],
|
||||
])("explains the %s prompt source", (promptSource, expected) => {
|
||||
render(<WorkflowCycleDiagnostic diagnostic={{ ...diagnostic, promptSource }} />);
|
||||
expect(screen.getByText(expected)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("renders blocking severity separately from a warning", () => {
|
||||
render(<WorkflowCycleDiagnostic diagnostic={{ ...diagnostic, severity: "blocking" }} />);
|
||||
expect(screen.getByText("Automatic workflow cycle")).toBeTruthy();
|
||||
expect(screen.getByText(/without another user action/i)).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("WorkflowCycleGuardDialog", () => {
|
||||
it("offers no override for a blocking proposal", () => {
|
||||
const onCancel = vi.fn();
|
||||
render(
|
||||
<WorkflowCycleGuardDialog
|
||||
proposal={{
|
||||
diagnostics: [{ ...diagnostic, severity: "blocking" }],
|
||||
intent: "apply",
|
||||
severity: "blocking",
|
||||
}}
|
||||
onCancel={onCancel}
|
||||
onConfirm={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByRole("heading", { name: "Workflow cycle blocked" })).toBeTruthy();
|
||||
expect(screen.queryByRole("button", { name: /anyway/i })).toBeNull();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Return to workflow" }));
|
||||
expect(onCancel).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["apply" as const, "Apply anyway"],
|
||||
["create" as const, "Create anyway"],
|
||||
])("confirms a warning proposal with %s intent", (intent, actionLabel) => {
|
||||
const onConfirm = vi.fn();
|
||||
const onCancel = vi.fn();
|
||||
render(
|
||||
<WorkflowCycleGuardDialog
|
||||
proposal={{ diagnostics: [diagnostic], intent, severity: "warning" }}
|
||||
onCancel={onCancel}
|
||||
onConfirm={onConfirm}
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: actionLabel }));
|
||||
expect(onConfirm).toHaveBeenCalledOnce();
|
||||
expect(onCancel).not.toHaveBeenCalled();
|
||||
expect(
|
||||
screen.getByRole("button", { name: actionLabel }).hasAttribute("data-dialog-default-action"),
|
||||
).toBe(true);
|
||||
expect(screen.getByRole("button", { name: "Cancel" })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("uses the semantic dialog action for Enter confirmation", () => {
|
||||
const onConfirm = vi.fn();
|
||||
render(
|
||||
<WorkflowCycleGuardDialog
|
||||
proposal={{ diagnostics: [diagnostic], intent: "apply", severity: "warning" }}
|
||||
onCancel={vi.fn()}
|
||||
onConfirm={onConfirm}
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.keyDown(screen.getByTestId("workflow-cycle-guard-dialog"), { key: "Enter" });
|
||||
expect(onConfirm).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe("WorkflowPipelineEditor replay-cycle marker", () => {
|
||||
it("marks affected nodes with visible and accessible text", () => {
|
||||
render(
|
||||
<WorkflowPipelineEditor
|
||||
steps={[workflowStep("work", AUTO_START_STEP_NAME, 0), workflowStep("review", "Review", 1)]}
|
||||
diagnostics={[diagnostic]}
|
||||
onUpdateStep={() => {}}
|
||||
onAddStep={() => {}}
|
||||
onRemoveStep={() => {}}
|
||||
onReorderSteps={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByLabelText("In Progress is part of a replay cycle")).toBeTruthy();
|
||||
expect(screen.getByLabelText("Review is part of a replay cycle")).toBeTruthy();
|
||||
expect(screen.getAllByText("Cycle")).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
"use client";
|
||||
|
||||
import { useRef } from "react";
|
||||
import { IconAlertTriangle, IconArrowRight, IconUser } from "@tabler/icons-react";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@kandev/ui/alert";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@kandev/ui/alert-dialog";
|
||||
import type {
|
||||
WorkflowReplayCycleDiagnostic,
|
||||
WorkflowReplayCycleHop,
|
||||
} from "@/lib/workflows/replay-cycle-analysis";
|
||||
import type { WorkflowMutationProposal } from "./workflow-mutation-guard";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const PROMPT_SOURCE_TEXT = {
|
||||
task_description: (stepName: string) =>
|
||||
`"${stepName}" has no step prompt, so re-entering it sends the task description.`,
|
||||
step_prompt_with_task_description: (stepName: string) =>
|
||||
`Re-entering "${stepName}" sends its rendered step prompt including the task description.`,
|
||||
step_prompt: (stepName: string) =>
|
||||
`Re-entering "${stepName}" sends its step prompt instead of the task description.`,
|
||||
} as const;
|
||||
|
||||
const TRIGGER_LABELS = {
|
||||
on_turn_start: "On turn start",
|
||||
on_turn_complete: "On turn complete",
|
||||
} as const;
|
||||
|
||||
const ACTION_LABELS = {
|
||||
move_to_next: "Move to next step",
|
||||
move_to_previous: "Move to previous step",
|
||||
move_to_step: "Move to specific step",
|
||||
} as const;
|
||||
|
||||
function CycleHop({ hop, index }: { hop: WorkflowReplayCycleHop; index: number }) {
|
||||
return (
|
||||
<li className="min-w-0 rounded-md border bg-background/60 p-3">
|
||||
<div className="grid min-w-0 grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-2">
|
||||
<span className="min-w-0 break-words font-medium">{hop.sourceStepName}</span>
|
||||
<IconArrowRight className="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />
|
||||
<span className="min-w-0 break-words text-right font-medium">
|
||||
{hop.destinationStepName}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-2 flex min-w-0 flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<span className="whitespace-nowrap rounded bg-muted px-2 py-1">
|
||||
{TRIGGER_LABELS[hop.trigger]}
|
||||
</span>
|
||||
<span className="whitespace-nowrap rounded bg-muted px-2 py-1">
|
||||
{ACTION_LABELS[hop.actionKind]}
|
||||
</span>
|
||||
</div>
|
||||
{hop.requiresUserInvolvement && (
|
||||
<div className="mt-2 flex items-center gap-1.5 text-xs font-medium text-foreground">
|
||||
<IconUser className="size-3.5 shrink-0" aria-hidden="true" />
|
||||
<span>User action required</span>
|
||||
</div>
|
||||
)}
|
||||
<span className="sr-only">Hop {index + 1}</span>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
export function WorkflowCycleDiagnostic({
|
||||
diagnostic,
|
||||
}: {
|
||||
diagnostic: WorkflowReplayCycleDiagnostic;
|
||||
}) {
|
||||
const isBlocking = diagnostic.severity === "blocking";
|
||||
const promptText = PROMPT_SOURCE_TEXT[diagnostic.promptSource](diagnostic.autoStartStepName);
|
||||
|
||||
return (
|
||||
<Alert
|
||||
variant={isBlocking ? "destructive" : "default"}
|
||||
className={cn(
|
||||
"min-w-0 overflow-hidden p-3 text-sm",
|
||||
!isBlocking && "border-amber-500/60 bg-amber-500/5",
|
||||
)}
|
||||
data-testid={`workflow-cycle-diagnostic-${diagnostic.autoStartStepId}`}
|
||||
>
|
||||
<IconAlertTriangle className="mt-0.5 size-4" aria-hidden="true" />
|
||||
<AlertTitle className="text-sm">
|
||||
{isBlocking ? "Automatic workflow cycle" : "Potential repeated agent run"}
|
||||
</AlertTitle>
|
||||
<AlertDescription className="min-w-0 space-y-3 text-left text-sm text-pretty">
|
||||
<p>
|
||||
{isBlocking
|
||||
? `This path re-enters "${diagnostic.autoStartStepName}" and can start the agent again without another user action.`
|
||||
: `This path can re-enter "${diagnostic.autoStartStepName}" and start the agent again after a user action.`}
|
||||
</p>
|
||||
<ol
|
||||
aria-label={`Replay path for ${diagnostic.autoStartStepName}`}
|
||||
className="grid min-w-0 gap-2"
|
||||
>
|
||||
{diagnostic.trace.map((hop, index) => (
|
||||
<CycleHop
|
||||
key={`${diagnostic.identity}-${hop.sourceStepId}-${hop.trigger}-${index}`}
|
||||
hop={hop}
|
||||
index={index}
|
||||
/>
|
||||
))}
|
||||
</ol>
|
||||
<p className="break-words">{promptText}</p>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
type WorkflowCycleGuardDialogProps = {
|
||||
proposal: WorkflowMutationProposal | null;
|
||||
onCancel: () => void;
|
||||
onConfirm: () => void | Promise<void>;
|
||||
};
|
||||
|
||||
export function WorkflowCycleGuardDialog({
|
||||
proposal,
|
||||
onCancel,
|
||||
onConfirm,
|
||||
}: WorkflowCycleGuardDialogProps) {
|
||||
const isBlocking = proposal?.severity === "blocking";
|
||||
const actionLabel = proposal?.intent === "create" ? "Create anyway" : "Apply anyway";
|
||||
const confirming = useRef(false);
|
||||
|
||||
const handleConfirm = async () => {
|
||||
confirming.current = true;
|
||||
try {
|
||||
await onConfirm();
|
||||
} finally {
|
||||
confirming.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AlertDialog
|
||||
open={proposal !== null}
|
||||
onOpenChange={(open) => !open && !confirming.current && onCancel()}
|
||||
>
|
||||
<AlertDialogContent
|
||||
className="max-h-[calc(100dvh-2rem)] max-w-[calc(100vw-2rem)] grid-rows-[auto_minmax(0,1fr)_auto] gap-0 overflow-hidden p-0 sm:max-w-2xl"
|
||||
enterConfirms={!isBlocking}
|
||||
data-testid="workflow-cycle-guard-dialog"
|
||||
>
|
||||
<AlertDialogHeader className="place-items-start p-4 pb-3 text-left sm:p-6 sm:pb-4">
|
||||
<AlertDialogTitle className="text-lg">
|
||||
{isBlocking ? "Workflow cycle blocked" : "Confirm workflow cycle"}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription className="text-left text-sm">
|
||||
{isBlocking
|
||||
? "Change the workflow steps to remove the automatic cycle before continuing."
|
||||
: "Review the repeated agent run before continuing."}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div
|
||||
className="min-h-0 overflow-x-hidden overflow-y-auto px-4 pb-4 sm:px-6"
|
||||
data-testid="workflow-cycle-guard-scroll"
|
||||
>
|
||||
<div className="grid min-w-0 gap-3">
|
||||
{proposal?.diagnostics.map((diagnostic) => (
|
||||
<WorkflowCycleDiagnostic key={diagnostic.identity} diagnostic={diagnostic} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<AlertDialogFooter className="border-t bg-background p-4 sm:px-6">
|
||||
<AlertDialogCancel className="min-h-12 w-full cursor-pointer sm:w-auto">
|
||||
{isBlocking ? "Return to workflow" : "Cancel"}
|
||||
</AlertDialogCancel>
|
||||
{!isBlocking && (
|
||||
<AlertDialogAction
|
||||
data-dialog-default-action
|
||||
className="min-h-12 w-full cursor-pointer sm:w-auto"
|
||||
onClick={handleConfirm}
|
||||
>
|
||||
{actionLabel}
|
||||
</AlertDialogAction>
|
||||
)}
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import type { WorkflowStep } from "@/lib/types/http";
|
||||
import {
|
||||
analyzeIntroducedWorkflowReplayCycles,
|
||||
analyzeWorkflowReplayCycles,
|
||||
type WorkflowReplayCycleDiagnostic,
|
||||
type WorkflowReplayCycleSeverity,
|
||||
} from "@/lib/workflows/replay-cycle-analysis";
|
||||
|
||||
export type WorkflowMutationIntent = "apply" | "create";
|
||||
|
||||
export type WorkflowMutationProposal = {
|
||||
diagnostics: WorkflowReplayCycleDiagnostic[];
|
||||
intent: WorkflowMutationIntent;
|
||||
severity: WorkflowReplayCycleSeverity;
|
||||
};
|
||||
|
||||
type GuardMutationParams = {
|
||||
proposedSteps: WorkflowStep[];
|
||||
operation: () => Promise<void>;
|
||||
intent?: WorkflowMutationIntent;
|
||||
baselineSteps?: WorkflowStep[];
|
||||
};
|
||||
|
||||
export type WorkflowMutationGuardController = {
|
||||
diagnostics: WorkflowReplayCycleDiagnostic[];
|
||||
proposal: WorkflowMutationProposal | null;
|
||||
isMutationPending: boolean;
|
||||
guardMutation: (params: GuardMutationParams) => Promise<void>;
|
||||
confirmProposal: () => Promise<void>;
|
||||
cancelProposal: () => void;
|
||||
};
|
||||
|
||||
type MutationPhase = "idle" | "proposal" | "running";
|
||||
|
||||
export function useWorkflowMutationGuard(
|
||||
displayedSteps: WorkflowStep[],
|
||||
): WorkflowMutationGuardController {
|
||||
const diagnostics = useMemo(() => analyzeWorkflowReplayCycles(displayedSteps), [displayedSteps]);
|
||||
const [proposal, setProposal] = useState<WorkflowMutationProposal | null>(null);
|
||||
const [isMutationPending, setIsMutationPending] = useState(false);
|
||||
const mutationPhase = useRef<MutationPhase>("idle");
|
||||
const pendingOperation = useRef<(() => Promise<void>) | null>(null);
|
||||
|
||||
const releaseMutation = useCallback(() => {
|
||||
mutationPhase.current = "idle";
|
||||
setIsMutationPending(false);
|
||||
}, []);
|
||||
|
||||
const cancelProposal = useCallback(() => {
|
||||
if (mutationPhase.current !== "proposal") return;
|
||||
pendingOperation.current = null;
|
||||
setProposal(null);
|
||||
releaseMutation();
|
||||
}, [releaseMutation]);
|
||||
|
||||
const confirmProposal = useCallback(async () => {
|
||||
if (mutationPhase.current !== "proposal") return;
|
||||
const operation = pendingOperation.current;
|
||||
if (!operation) {
|
||||
setProposal(null);
|
||||
releaseMutation();
|
||||
return;
|
||||
}
|
||||
pendingOperation.current = null;
|
||||
mutationPhase.current = "running";
|
||||
setProposal(null);
|
||||
try {
|
||||
await operation();
|
||||
} finally {
|
||||
releaseMutation();
|
||||
}
|
||||
}, [releaseMutation]);
|
||||
|
||||
const guardMutation = useCallback(
|
||||
async ({
|
||||
proposedSteps,
|
||||
operation,
|
||||
intent = "apply",
|
||||
baselineSteps = displayedSteps,
|
||||
}: GuardMutationParams) => {
|
||||
if (mutationPhase.current !== "idle") return;
|
||||
mutationPhase.current = "running";
|
||||
setIsMutationPending(true);
|
||||
|
||||
try {
|
||||
const introduced = analyzeIntroducedWorkflowReplayCycles(baselineSteps, proposedSteps);
|
||||
if (introduced.length === 0) {
|
||||
await operation();
|
||||
releaseMutation();
|
||||
return;
|
||||
}
|
||||
|
||||
const severity = introduced.some((diagnostic) => diagnostic.severity === "blocking")
|
||||
? "blocking"
|
||||
: "warning";
|
||||
pendingOperation.current = severity === "warning" ? operation : null;
|
||||
mutationPhase.current = "proposal";
|
||||
setProposal({ diagnostics: introduced, intent, severity });
|
||||
} catch (error) {
|
||||
releaseMutation();
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
[displayedSteps, releaseMutation],
|
||||
);
|
||||
|
||||
return {
|
||||
diagnostics,
|
||||
proposal,
|
||||
isMutationPending,
|
||||
guardMutation,
|
||||
confirmProposal,
|
||||
cancelProposal,
|
||||
};
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
IconTrash,
|
||||
IconChevronRight,
|
||||
IconRosetteNumber1,
|
||||
IconAlertTriangle,
|
||||
} from "@tabler/icons-react";
|
||||
import { StepCapabilityIcons } from "@/components/step-capability-icons";
|
||||
import {
|
||||
@@ -37,8 +38,10 @@ import {
|
||||
import { ScrollArea, ScrollBar } from "@kandev/ui/scroll-area";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@kandev/ui/tooltip";
|
||||
import type { WorkflowStep } from "@/lib/types/http";
|
||||
import type { WorkflowReplayCycleDiagnostic } from "@/lib/workflows/replay-cycle-analysis";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { StepConfigPanel } from "./workflow-pipeline-editor-panels";
|
||||
import { WorkflowCycleDiagnostic } from "./workflow-cycle-diagnostic";
|
||||
|
||||
type WorkflowPipelineEditorProps = {
|
||||
steps: WorkflowStep[];
|
||||
@@ -46,6 +49,7 @@ type WorkflowPipelineEditorProps = {
|
||||
onAddStep: () => void;
|
||||
onRemoveStep: (stepId: string) => void;
|
||||
onReorderSteps: (steps: WorkflowStep[]) => void;
|
||||
diagnostics?: WorkflowReplayCycleDiagnostic[];
|
||||
readOnly?: boolean;
|
||||
};
|
||||
|
||||
@@ -73,6 +77,7 @@ type PipelineNodeProps = {
|
||||
isSelected: boolean;
|
||||
onSelect: () => void;
|
||||
onRemove: () => void;
|
||||
isReplayCycleAffected: boolean;
|
||||
readOnly?: boolean;
|
||||
};
|
||||
|
||||
@@ -81,6 +86,7 @@ function PipelineNode({
|
||||
isSelected,
|
||||
onSelect,
|
||||
onRemove,
|
||||
isReplayCycleAffected,
|
||||
readOnly = false,
|
||||
}: PipelineNodeProps) {
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
|
||||
@@ -98,6 +104,7 @@ function PipelineNode({
|
||||
isSelected
|
||||
? "border-primary bg-primary/5"
|
||||
: "border-border bg-card hover:border-primary/50",
|
||||
isReplayCycleAffected && "border-dashed border-amber-500 ring-1 ring-amber-500/30",
|
||||
isDragging && "opacity-50 z-50",
|
||||
)}
|
||||
onClick={onSelect}
|
||||
@@ -137,6 +144,15 @@ function PipelineNode({
|
||||
agentProfileId={step.agent_profile_id}
|
||||
fallback={<span className="text-xs text-muted-foreground/50">manual</span>}
|
||||
/>
|
||||
{isReplayCycleAffected && (
|
||||
<span
|
||||
className="flex items-center gap-1 text-xs font-medium text-amber-700 dark:text-amber-300"
|
||||
aria-label={`${step.name} is part of a replay cycle`}
|
||||
>
|
||||
<IconAlertTriangle className="size-3 shrink-0" aria-hidden="true" />
|
||||
Cycle
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{!readOnly && (
|
||||
<button
|
||||
@@ -176,6 +192,7 @@ type PipelineAreaProps = {
|
||||
onSelectStep: (stepId: string) => void;
|
||||
onRemoveStep: (stepId: string) => void;
|
||||
onAddStep: () => void;
|
||||
affectedStepIds: Set<string>;
|
||||
readOnly: boolean;
|
||||
};
|
||||
|
||||
@@ -185,6 +202,7 @@ function PipelineArea({
|
||||
onSelectStep,
|
||||
onRemoveStep,
|
||||
onAddStep,
|
||||
affectedStepIds,
|
||||
readOnly,
|
||||
}: PipelineAreaProps) {
|
||||
return (
|
||||
@@ -197,6 +215,7 @@ function PipelineArea({
|
||||
isSelected={selectedStepId === step.id}
|
||||
onSelect={() => onSelectStep(step.id)}
|
||||
onRemove={() => onRemoveStep(step.id)}
|
||||
isReplayCycleAffected={affectedStepIds.has(step.id)}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
</div>
|
||||
@@ -252,6 +271,23 @@ function StepDeleteConfirmation({
|
||||
);
|
||||
}
|
||||
|
||||
function affectedStepIds(diagnostics: WorkflowReplayCycleDiagnostic[]): Set<string> {
|
||||
return new Set(diagnostics.flatMap((diagnostic) => diagnostic.affectedStepIds));
|
||||
}
|
||||
|
||||
function WorkflowCycleAlerts({ diagnostics }: { diagnostics: WorkflowReplayCycleDiagnostic[] }) {
|
||||
if (diagnostics.length === 0) return null;
|
||||
return (
|
||||
<div className="grid min-w-0 gap-3">
|
||||
{diagnostics.map((diagnostic) => (
|
||||
<WorkflowCycleDiagnostic key={diagnostic.identity} diagnostic={diagnostic} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const EMPTY_DIAGNOSTICS: WorkflowReplayCycleDiagnostic[] = [];
|
||||
|
||||
// --- Main Pipeline Editor ---
|
||||
|
||||
export function WorkflowPipelineEditor({
|
||||
@@ -260,6 +296,7 @@ export function WorkflowPipelineEditor({
|
||||
onAddStep,
|
||||
onRemoveStep,
|
||||
onReorderSteps,
|
||||
diagnostics = EMPTY_DIAGNOSTICS,
|
||||
readOnly = false,
|
||||
}: WorkflowPipelineEditorProps) {
|
||||
const [selectedStepId, setSelectedStepId] = useState<string | null>(null);
|
||||
@@ -273,6 +310,7 @@ export function WorkflowPipelineEditor({
|
||||
}
|
||||
|
||||
const stepItems = useMemo(() => steps.map((step) => step.id), [steps]);
|
||||
const affectedIds = useMemo(() => affectedStepIds(diagnostics), [diagnostics]);
|
||||
const isMounted = useSyncExternalStore(
|
||||
() => () => {},
|
||||
() => true,
|
||||
@@ -317,12 +355,14 @@ export function WorkflowPipelineEditor({
|
||||
onSelectStep={handleSelectStep}
|
||||
onRemoveStep={requestRemoveStep}
|
||||
onAddStep={onAddStep}
|
||||
affectedStepIds={affectedIds}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<WorkflowCycleAlerts diagnostics={diagnostics} />
|
||||
<ScrollArea className="w-full pb-1">
|
||||
{isMounted ? (
|
||||
<DndContext
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import {
|
||||
createWorkflowStepAction,
|
||||
deleteWorkflowStepAction,
|
||||
getWorkflowTaskCount,
|
||||
listWorkflowStepsAction,
|
||||
reorderWorkflowStepsAction,
|
||||
updateWorkflowStepAction,
|
||||
} from "@/app/actions/workspaces";
|
||||
import type { Workflow, WorkflowStep } from "@/lib/types/http";
|
||||
import {
|
||||
useWorkflowDeleteHandlers,
|
||||
useWorkflowSaveActions,
|
||||
useWorkflowStepActions,
|
||||
} from "./workflow-card-actions";
|
||||
import { useWorkflowMutationGuard } from "./workflow-mutation-guard";
|
||||
|
||||
vi.mock("@/app/actions/workspaces", () => ({
|
||||
createWorkflowAction: vi.fn(),
|
||||
createWorkflowStepAction: vi.fn(),
|
||||
updateWorkflowStepAction: vi.fn(),
|
||||
deleteWorkflowStepAction: vi.fn(),
|
||||
reorderWorkflowStepsAction: vi.fn(),
|
||||
listWorkflowStepsAction: vi.fn(),
|
||||
getStepTaskCount: vi.fn(),
|
||||
getWorkflowTaskCount: vi.fn(),
|
||||
exportWorkflowAction: vi.fn(),
|
||||
bulkMoveTasks: vi.fn(),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(listWorkflowStepsAction).mockResolvedValue({ steps: [], total: 0 });
|
||||
});
|
||||
|
||||
const workflow = {
|
||||
id: "wf-1",
|
||||
workspace_id: "ws-1",
|
||||
name: "Synced workflow",
|
||||
source: "github",
|
||||
source_path: ".kandev/workflows/review.yaml",
|
||||
created_at: "",
|
||||
updated_at: "",
|
||||
} as Workflow;
|
||||
|
||||
function step(id: string, position: number): WorkflowStep {
|
||||
return {
|
||||
id,
|
||||
workflow_id: workflow.id,
|
||||
name: id,
|
||||
position,
|
||||
color: "bg-slate-500",
|
||||
allow_manual_move: true,
|
||||
is_start_step: position === 0,
|
||||
events: { on_enter: [] },
|
||||
created_at: "",
|
||||
updated_at: "",
|
||||
};
|
||||
}
|
||||
|
||||
it("refuses every step mutation when the workflow is read-only", async () => {
|
||||
const initialSteps = [step("todo", 0), step("review", 1)];
|
||||
let currentSteps = initialSteps;
|
||||
const setWorkflowSteps = vi.fn(
|
||||
(updater: ((previous: WorkflowStep[]) => WorkflowStep[]) | WorkflowStep[]) => {
|
||||
currentSteps = typeof updater === "function" ? updater(currentSteps) : updater;
|
||||
},
|
||||
);
|
||||
const { result } = renderHook(() => {
|
||||
const mutationGuard = useWorkflowMutationGuard(initialSteps);
|
||||
return useWorkflowStepActions({
|
||||
workflow,
|
||||
isNewWorkflow: false,
|
||||
readOnly: true,
|
||||
workflowSteps: initialSteps,
|
||||
setWorkflowSteps,
|
||||
setStepToDelete: vi.fn(),
|
||||
setStepTaskCount: vi.fn(),
|
||||
setTargetStepForMigration: vi.fn(),
|
||||
setStepDeleteOpen: vi.fn(),
|
||||
toast: vi.fn(),
|
||||
mutationGuard,
|
||||
});
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleAddWorkflowStep();
|
||||
await result.current.handleUpdateWorkflowStep("review", { name: "Renamed" });
|
||||
await result.current.handleRemoveWorkflowStep("todo");
|
||||
await result.current.handleReorderWorkflowSteps([...initialSteps].reverse());
|
||||
});
|
||||
|
||||
expect(currentSteps).toEqual(initialSteps);
|
||||
expect(setWorkflowSteps).not.toHaveBeenCalled();
|
||||
expect(createWorkflowStepAction).not.toHaveBeenCalled();
|
||||
expect(updateWorkflowStepAction).not.toHaveBeenCalled();
|
||||
expect(deleteWorkflowStepAction).not.toHaveBeenCalled();
|
||||
expect(reorderWorkflowStepsAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses to open or confirm workflow deletion when read-only", async () => {
|
||||
const deleteWorkflowRun = vi.fn();
|
||||
const wfDel = {
|
||||
setDeleteOpen: vi.fn(),
|
||||
setWorkflowTaskCount: vi.fn(),
|
||||
setWorkflowDeleteLoading: vi.fn(),
|
||||
setTargetWorkflowId: vi.fn(),
|
||||
setTargetWorkflowSteps: vi.fn(),
|
||||
setTargetStepId: vi.fn(),
|
||||
targetWorkflowId: "target-workflow",
|
||||
targetStepId: "target-step",
|
||||
setMigrateLoading: vi.fn(),
|
||||
};
|
||||
const { result } = renderHook(() =>
|
||||
useWorkflowDeleteHandlers({
|
||||
workflow,
|
||||
isNewWorkflow: false,
|
||||
readOnly: true,
|
||||
otherWorkflows: [],
|
||||
wfDel,
|
||||
deleteWorkflowRun,
|
||||
toast: vi.fn(),
|
||||
}),
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleDeleteWorkflowClick();
|
||||
await result.current.handleDeleteWorkflow();
|
||||
await result.current.handleMigrateAndDeleteWorkflow();
|
||||
});
|
||||
|
||||
expect(getWorkflowTaskCount).not.toHaveBeenCalled();
|
||||
expect(deleteWorkflowRun).not.toHaveBeenCalled();
|
||||
expect(wfDel.setDeleteOpen).not.toHaveBeenCalled();
|
||||
expect(wfDel.setMigrateLoading).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses to save an existing workflow when read-only", async () => {
|
||||
const onSaveWorkflow = vi.fn();
|
||||
const { result } = renderHook(() => {
|
||||
const mutationGuard = useWorkflowMutationGuard([]);
|
||||
return useWorkflowSaveActions({
|
||||
workflow,
|
||||
isNewWorkflow: false,
|
||||
readOnly: true,
|
||||
workflowSteps: [],
|
||||
templateStepCount: 0,
|
||||
onSaveWorkflow,
|
||||
toast: vi.fn(),
|
||||
mutationGuard,
|
||||
});
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleSaveWorkflow();
|
||||
});
|
||||
|
||||
expect(onSaveWorkflow).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import { reorderWorkflowStepsAction } from "@/app/actions/workspaces";
|
||||
import type { Workflow, WorkflowStep } from "@/lib/types/http";
|
||||
import { useWorkflowStepActions } from "./workflow-card-actions";
|
||||
import { useWorkflowMutationGuard } from "./workflow-mutation-guard";
|
||||
|
||||
vi.mock("@/app/actions/workspaces", () => ({
|
||||
createWorkflowAction: vi.fn(),
|
||||
createWorkflowStepAction: vi.fn(),
|
||||
updateWorkflowStepAction: vi.fn(),
|
||||
deleteWorkflowStepAction: vi.fn(),
|
||||
reorderWorkflowStepsAction: vi.fn(),
|
||||
listWorkflowStepsAction: vi.fn(),
|
||||
getStepTaskCount: vi.fn(),
|
||||
getWorkflowTaskCount: vi.fn(),
|
||||
exportWorkflowAction: vi.fn(),
|
||||
bulkMoveTasks: vi.fn(),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
const workflow = {
|
||||
id: "wf-1",
|
||||
workspace_id: "ws-1",
|
||||
name: "Workflow",
|
||||
created_at: "",
|
||||
updated_at: "",
|
||||
} as Workflow;
|
||||
|
||||
function step(id: string, name: string, position: number, isStartStep: boolean): WorkflowStep {
|
||||
return {
|
||||
id,
|
||||
workflow_id: workflow.id,
|
||||
name,
|
||||
position,
|
||||
color: "bg-slate-500",
|
||||
allow_manual_move: true,
|
||||
is_start_step: isStartStep,
|
||||
events: { on_enter: [] },
|
||||
created_at: "",
|
||||
updated_at: "",
|
||||
};
|
||||
}
|
||||
|
||||
function renderReorderActions(initialSteps: WorkflowStep[]) {
|
||||
let currentSteps = initialSteps;
|
||||
const setWorkflowSteps = vi.fn(
|
||||
(updater: ((previous: WorkflowStep[]) => WorkflowStep[]) | WorkflowStep[]) => {
|
||||
currentSteps = typeof updater === "function" ? updater(currentSteps) : updater;
|
||||
},
|
||||
);
|
||||
const view = renderHook(() => {
|
||||
const mutationGuard = useWorkflowMutationGuard(initialSteps);
|
||||
return useWorkflowStepActions({
|
||||
workflow,
|
||||
isNewWorkflow: false,
|
||||
workflowSteps: initialSteps,
|
||||
setWorkflowSteps,
|
||||
setStepToDelete: vi.fn(),
|
||||
setStepTaskCount: vi.fn(),
|
||||
setTargetStepForMigration: vi.fn(),
|
||||
setStepDeleteOpen: vi.fn(),
|
||||
toast: vi.fn(),
|
||||
mutationGuard,
|
||||
});
|
||||
});
|
||||
return { ...view, setWorkflowSteps, getSteps: () => currentSteps };
|
||||
}
|
||||
|
||||
function deferredPromise<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((resolvePromise) => {
|
||||
resolve = resolvePromise;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
it("keeps a reorder optimistic until the authoritative response arrives", async () => {
|
||||
const work = step("work", "Work", 0, true);
|
||||
const review = step("review", "Review", 1, false);
|
||||
const proposed = [
|
||||
{ ...review, position: 0 },
|
||||
{ ...work, position: 1 },
|
||||
];
|
||||
const authoritative = proposed.map((workflowStep) => ({
|
||||
...workflowStep,
|
||||
updated_at: "server-update",
|
||||
}));
|
||||
const response = deferredPromise<{ steps: WorkflowStep[]; total: number }>();
|
||||
vi.mocked(reorderWorkflowStepsAction).mockReturnValue(response.promise);
|
||||
const { result, getSteps } = renderReorderActions([work, review]);
|
||||
|
||||
let request!: Promise<void>;
|
||||
await act(async () => {
|
||||
request = result.current.handleReorderWorkflowSteps([review, work]);
|
||||
await vi.waitFor(() => expect(reorderWorkflowStepsAction).toHaveBeenCalledTimes(1));
|
||||
});
|
||||
expect(getSteps()).toEqual(proposed);
|
||||
|
||||
await act(async () => {
|
||||
response.resolve({ steps: authoritative, total: 2 });
|
||||
await request;
|
||||
});
|
||||
expect(getSteps()).toEqual(authoritative);
|
||||
});
|
||||
|
||||
it("rolls an optimistic reorder back when persistence fails", async () => {
|
||||
const work = step("work", "Work", 0, true);
|
||||
const review = step("review", "Review", 1, false);
|
||||
const initial = [work, review];
|
||||
const proposed = [
|
||||
{ ...review, position: 0 },
|
||||
{ ...work, position: 1 },
|
||||
];
|
||||
vi.mocked(reorderWorkflowStepsAction).mockRejectedValue(new Error("reorder failed"));
|
||||
const { result, setWorkflowSteps, getSteps } = renderReorderActions(initial);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleReorderWorkflowSteps([review, work]);
|
||||
});
|
||||
|
||||
expect(setWorkflowSteps).toHaveBeenNthCalledWith(1, proposed);
|
||||
expect(setWorkflowSteps).toHaveBeenNthCalledWith(2, initial);
|
||||
expect(getSteps()).toEqual(initial);
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { Workflow, WorkflowStep } from "@/lib/types/http";
|
||||
import type { useToast } from "@/components/toast-provider";
|
||||
import { generateUUID } from "@/lib/utils";
|
||||
import { createWorkflowStepAction, updateWorkflowStepAction } from "@/app/actions/workspaces";
|
||||
|
||||
const FALLBACK_ERROR_MESSAGE = "Request failed";
|
||||
const NEW_STEP_DEFAULTS = { name: "New Step", color: "bg-slate-500" } as const;
|
||||
|
||||
type WorkflowStepsSetter = (
|
||||
updater: ((previous: WorkflowStep[]) => WorkflowStep[]) | WorkflowStep[],
|
||||
) => void;
|
||||
type Toast = ReturnType<typeof useToast>["toast"];
|
||||
|
||||
export function newWorkflowStep(workflow: Workflow, position: number, id: string): WorkflowStep {
|
||||
return {
|
||||
id,
|
||||
workflow_id: workflow.id,
|
||||
...NEW_STEP_DEFAULTS,
|
||||
position,
|
||||
allow_manual_move: true,
|
||||
created_at: "",
|
||||
updated_at: "",
|
||||
};
|
||||
}
|
||||
|
||||
export function addLocalStep(workflow: Workflow, setWorkflowSteps: WorkflowStepsSetter) {
|
||||
setWorkflowSteps((previous) => [
|
||||
...previous,
|
||||
newWorkflowStep(workflow, previous.length, `temp-step-${generateUUID()}`),
|
||||
]);
|
||||
}
|
||||
|
||||
export function removeLocalStep(stepId: string, setWorkflowSteps: WorkflowStepsSetter) {
|
||||
setWorkflowSteps((previous) =>
|
||||
previous.filter((step) => step.id !== stepId).map((step, position) => ({ ...step, position })),
|
||||
);
|
||||
}
|
||||
|
||||
export async function addRemoteStep(
|
||||
workflow: Workflow,
|
||||
stepCount: number,
|
||||
setWorkflowSteps: WorkflowStepsSetter,
|
||||
toast: Toast,
|
||||
) {
|
||||
try {
|
||||
const created = await createWorkflowStepAction({
|
||||
workflow_id: workflow.id,
|
||||
...NEW_STEP_DEFAULTS,
|
||||
position: stepCount,
|
||||
});
|
||||
setWorkflowSteps((previous) => [...previous, created]);
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Failed to add workflow step",
|
||||
description: error instanceof Error ? error.message : FALLBACK_ERROR_MESSAGE,
|
||||
variant: "error",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function applyWorkflowStepUpdates(
|
||||
steps: WorkflowStep[],
|
||||
stepId: string,
|
||||
updates: Partial<WorkflowStep>,
|
||||
): WorkflowStep[] {
|
||||
const isSettingStartStep = updates.is_start_step === true;
|
||||
return steps.map((step) => {
|
||||
if (step.id === stepId) return { ...step, ...updates };
|
||||
if (isSettingStartStep) return { ...step, is_start_step: false };
|
||||
return step;
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateRemoteWorkflowStep({
|
||||
stepId,
|
||||
updates,
|
||||
setWorkflowSteps,
|
||||
toast,
|
||||
}: {
|
||||
stepId: string;
|
||||
updates: Partial<WorkflowStep>;
|
||||
setWorkflowSteps: WorkflowStepsSetter;
|
||||
toast: Toast;
|
||||
}) {
|
||||
try {
|
||||
const updated = await updateWorkflowStepAction(stepId, updates);
|
||||
setWorkflowSteps((previous) => applyWorkflowStepUpdates(previous, stepId, updated));
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Failed to update workflow step",
|
||||
description: error instanceof Error ? error.message : FALLBACK_ERROR_MESSAGE,
|
||||
variant: "error",
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user