fix: coalesce ci auto-fix queue rounds (#1552)

* fix: coalesce ci auto-fix queue rounds

* fix: centralize ci auto-fix round cap

* fix: keep ci auto-fix state fresh

* fix: refine ci auto-fix round status

* fix: handle ci auto-fix exhaustion edge cases

* fix: reduce ci auto-fix dispatch complexity

* fix: refresh pending ci auto-fix before direct prompt

* fix: harden ci auto-fix queue replacement

---------

Co-authored-by: root <root@kandev.ts.net>
This commit is contained in:
Carlos Florêncio
2026-06-30 01:19:52 +01:00
committed by GitHub
parent bffbc8e96f
commit ef9807bd72
26 changed files with 1826 additions and 65 deletions
@@ -17,7 +17,8 @@ import { Textarea } from "@kandev/ui/textarea";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { useToast } from "@/components/toast-provider";
import { useTaskCIAutomationOptions } from "@/hooks/domains/github/use-task-ci-options";
import type { TaskCIAutomationPatch, TaskPR } from "@/lib/types/github";
import { autoFixRoundForState, findCIAutomationStateForPR } from "@/lib/github/ci-automation";
import type { TaskCIAutomationPatch, TaskCIPRAutomationState, TaskPR } from "@/lib/types/github";
const PR_FEEDBACK_PLACEHOLDER = "{{pr.feedback}}";
@@ -207,12 +208,35 @@ function CIAutomationErrorRow({
);
}
function CIAutoFixRoundExplanation({
state,
maxRounds,
}: {
state: TaskCIPRAutomationState | undefined;
maxRounds: number | null | undefined;
}) {
const round = autoFixRoundForState(state, maxRounds);
return (
<div
data-testid="ci-auto-fix-round-explanation"
className="rounded-md border border-border/70 bg-muted/30 px-2.5 py-2 text-[11px] leading-relaxed text-muted-foreground"
>
Auto-fix has used {round.current} of {round.max} rounds for this PR. A round is counted when
Kandev sends or queues a CI auto-fix message. Updating an already queued auto-fix message does
not use another round. When this is at {round.max}/{round.max} and there is no pending
auto-fix message left to update, Kandev pauses auto-fix for this PR so it cannot loop forever.
Disable and re-enable auto-fix after manual review to start over.
</div>
);
}
export function PRCIAutomationControls({ pr }: { pr: TaskPR }) {
const { options, loading, saving, error, refresh, update, resetPrompt } =
useTaskCIAutomationOptions(pr.task_id);
const { toast } = useToast();
const [promptOpen, setPromptOpen] = useState(false);
const [promptDraft, setPromptDraft] = useState("");
const automationState = findCIAutomationStateForPR(options?.pr_states, pr);
const openPromptEditor = useCallback(() => {
setPromptDraft(options?.auto_fix_prompt_override ?? options?.effective_auto_fix_prompt ?? "");
@@ -281,6 +305,12 @@ export function PRCIAutomationControls({ pr }: { pr: TaskPR }) {
disabled={disabled}
onCheckedChange={(checked) => patchOption({ auto_fix_enabled: checked })}
/>
{options?.auto_fix_enabled && (
<CIAutoFixRoundExplanation
state={automationState}
maxRounds={options.auto_fix_max_rounds}
/>
)}
<CIAutomationRow
id={`task-ci-auto-merge-${pr.task_id}`}
label="Auto-merge when ready"
@@ -0,0 +1,216 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ReactNode } from "react";
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { TooltipProvider } from "@kandev/ui/tooltip";
import { StateProvider } from "@/components/state-provider";
import { ToastProvider } from "@/components/toast-provider";
import { PRStatusChip } from "./pr-status-chip";
import type { AppState } from "@/lib/state/store";
import type { TaskCIAutomationOptions, TaskPR } from "@/lib/types/github";
const AUTO_FIX_BADGE_TESTID = "pr-status-auto-fix-chip";
const CHIP_TESTID = "pr-status-chip";
const ROUND_EXPLANATION_TESTID = "ci-auto-fix-round-explanation";
const testConstants = vi.hoisted(() => ({
defaultCIFixPrompt: "Default CI fix prompt",
}));
const responsiveMock = vi.hoisted(() => ({
breakpoint: "desktop" as "mobile" | "tablet" | "compactDesktop" | "desktop",
isFinePointer: true,
}));
vi.mock("@/hooks/use-responsive-breakpoint", () => ({
useResponsiveBreakpoint: () => ({
breakpoint: responsiveMock.breakpoint,
isMobile: responsiveMock.breakpoint === "mobile",
isTablet: responsiveMock.breakpoint === "tablet",
isDesktop:
responsiveMock.breakpoint === "compactDesktop" || responsiveMock.breakpoint === "desktop",
isCompactDesktop: responsiveMock.breakpoint === "compactDesktop",
isFullDesktop: responsiveMock.breakpoint === "desktop",
isFinePointer: responsiveMock.isFinePointer,
usesDesktopWorkbench:
responsiveMock.breakpoint === "compactDesktop" || responsiveMock.breakpoint === "desktop",
}),
}));
vi.mock("@/lib/api/domains/github-api", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/api/domains/github-api")>();
return {
...actual,
getPRFeedback: vi.fn().mockResolvedValue(null),
getTaskCIAutomationOptions: vi.fn().mockResolvedValue(makeCIOptions()),
listWorkspaceTaskPRs: vi.fn().mockResolvedValue({ task_prs: {} }),
};
});
vi.mock("@/lib/ws/connection", () => ({
getWebSocketClient: vi.fn(() => null),
}));
function renderWithStore(initialState: Partial<AppState>, ui: ReactNode) {
return render(
<StateProvider initialState={initialState}>
<ToastProvider>
<TooltipProvider>{ui}</TooltipProvider>
</ToastProvider>
</StateProvider>,
);
}
function makePR(overrides: Partial<TaskPR> = {}): TaskPR {
return {
id: "pr-id",
task_id: "task-1",
owner: "acme",
repo: "demo",
pr_number: 42,
pr_url: "https://github.com/acme/demo/pull/42",
pr_title: "Test PR",
head_branch: "feat",
base_branch: "main",
author_login: "alice",
state: "open",
review_state: "approved",
checks_state: "success",
mergeable_state: "clean",
review_count: 1,
pending_review_count: 0,
comment_count: 0,
unresolved_review_threads: 0,
checks_total: 2,
checks_passing: 2,
additions: 0,
deletions: 0,
created_at: "",
merged_at: null,
closed_at: null,
last_synced_at: null,
updated_at: "",
...overrides,
};
}
function makeCIOptions(overrides: Partial<TaskCIAutomationOptions> = {}): TaskCIAutomationOptions {
return {
task_id: "task-1",
auto_fix_enabled: false,
auto_merge_enabled: false,
auto_fix_prompt_override: null,
effective_auto_fix_prompt: testConstants.defaultCIFixPrompt,
using_default_prompt: true,
updated_at: "2026-06-18T10:00:00Z",
auto_fix_max_rounds: 10,
pr_states: [],
...overrides,
};
}
function makeCIPrState(roundCount: number, exhausted = false) {
return {
task_id: "task-1",
repository_id: "",
pr_number: 42,
last_fix_signature: "",
last_fix_checkpoint_json: "",
last_fix_enqueued_at: null,
last_fix_session_id: null,
auto_fix_round_count: roundCount,
auto_fix_exhausted_at: exhausted ? "2026-06-18T11:00:00Z" : null,
last_merge_signature: "",
last_merge_attempt_at: null,
last_error: exhausted ? "CI auto-fix paused after 10 rounds for this PR" : null,
created_at: "2026-06-18T10:00:00Z",
updated_at: "2026-06-18T10:00:00Z",
};
}
function stateWithAutoFix(
roundCount: number,
exhausted = false,
maxRounds = 10,
): Partial<AppState> {
return {
taskPRs: { byTaskId: { "task-1": [makePR()] } },
taskCIAutomation: {
byTaskId: {
"task-1": makeCIOptions({
auto_fix_enabled: true,
auto_fix_max_rounds: maxRounds,
pr_states: [makeCIPrState(roundCount, exhausted)],
}),
},
loading: {},
saving: {},
errors: {},
},
};
}
beforeEach(() => {
responsiveMock.breakpoint = "desktop";
responsiveMock.isFinePointer = true;
});
afterEach(() => {
cleanup();
});
describe("PRStatusChip auto-fix round display", () => {
it("shows the CI auto-fix round count in the enabled chip", () => {
renderWithStore(stateWithAutoFix(3), <PRStatusChip taskId="task-1" />);
expect(screen.getByTestId(AUTO_FIX_BADGE_TESTID).textContent).toBe("Auto-fix 3/10");
});
it("shows exhausted auto-fix state as a warning chip", () => {
renderWithStore(stateWithAutoFix(10, true), <PRStatusChip taskId="task-1" />);
const chip = screen.getByTestId(AUTO_FIX_BADGE_TESTID);
expect(chip.textContent).toBe("Auto-fix 10/10");
expect(chip.getAttribute("data-auto-fix-exhausted")).toBe("true");
});
it("does not mark 10/10 as exhausted until the backend pauses auto-fix", () => {
renderWithStore(stateWithAutoFix(10), <PRStatusChip taskId="task-1" />);
const chip = screen.getByTestId(AUTO_FIX_BADGE_TESTID);
expect(chip.textContent).toBe("Auto-fix 10/10");
expect(chip.getAttribute("data-auto-fix-exhausted")).toBe("false");
});
it("uses the max round count returned by the backend", () => {
renderWithStore(stateWithAutoFix(3, false, 12), <PRStatusChip taskId="task-1" />);
expect(screen.getByTestId(AUTO_FIX_BADGE_TESTID).textContent).toBe("Auto-fix 3/12");
});
it("explains the auto-fix round count from the hover popover", async () => {
renderWithStore(stateWithAutoFix(1), <PRStatusChip taskId="task-1" />);
fireEvent.mouseEnter(screen.getByTestId(CHIP_TESTID));
const explanation = await screen.findByTestId(ROUND_EXPLANATION_TESTID);
expect(explanation.textContent).toContain("Auto-fix has used 1 of 10 rounds");
expect(explanation.textContent).toContain(
"Updating an already queued auto-fix message does not use another round",
);
expect(explanation.textContent).toContain(
"pauses auto-fix for this PR so it cannot loop forever",
);
});
it("shows the auto-fix round explanation in the mobile drawer", () => {
responsiveMock.breakpoint = "mobile";
responsiveMock.isFinePointer = false;
renderWithStore(stateWithAutoFix(2), <PRStatusChip taskId="task-1" />);
act(() => {
fireEvent.click(screen.getByTestId(CHIP_TESTID));
});
const explanation = screen.getByTestId(ROUND_EXPLANATION_TESTID);
expect(explanation.textContent).toContain("Auto-fix has used 2 of 10 rounds");
});
});
@@ -9,6 +9,12 @@ import { PR_CI_DESKTOP_POPOVER_SCROLL_CLASS } from "./pr-ci-popover";
import type { AppState } from "@/lib/state/store";
import type { TaskCIAutomationOptions, TaskPR } from "@/lib/types/github";
const AUTO_FIX_BADGE_TESTID = "pr-status-auto-fix-chip";
const testConstants = vi.hoisted(() => ({
defaultCIFixPrompt: "Default CI fix prompt",
}));
const responsiveMock = vi.hoisted(() => ({
breakpoint: "desktop" as "mobile" | "tablet" | "compactDesktop" | "desktop",
isFinePointer: true,
@@ -38,7 +44,7 @@ vi.mock("@/lib/api/domains/github-api", async (importOriginal) => {
auto_fix_enabled: false,
auto_merge_enabled: false,
auto_fix_prompt_override: null,
effective_auto_fix_prompt: "Default CI fix prompt",
effective_auto_fix_prompt: testConstants.defaultCIFixPrompt,
using_default_prompt: true,
updated_at: "2026-06-18T10:00:00Z",
pr_states: [],
@@ -100,7 +106,7 @@ function makeCIOptions(overrides: Partial<TaskCIAutomationOptions> = {}): TaskCI
auto_fix_enabled: false,
auto_merge_enabled: false,
auto_fix_prompt_override: null,
effective_auto_fix_prompt: "Default CI fix prompt",
effective_auto_fix_prompt: testConstants.defaultCIFixPrompt,
using_default_prompt: true,
updated_at: "2026-06-18T10:00:00Z",
pr_states: [],
@@ -229,10 +235,10 @@ describe("PRStatusChip desktop branch", () => {
},
<PRStatusChip taskId="task-1" />,
);
expect(screen.getByTestId("pr-status-auto-fix-chip").textContent).toBe("Auto-fix");
expect(screen.getByTestId(AUTO_FIX_BADGE_TESTID).textContent).toBe("Auto-fix 0/10");
expect(screen.getByTestId("pr-status-auto-merge-chip").textContent).toBe("Auto-merge");
expect(screen.getByTestId(CHIP_TESTID).getAttribute("aria-label")).toBe(
"Pull request #42 CI status, auto-fix enabled, auto-merge enabled",
"Pull request #42 CI status, auto-fix enabled 0 of 10 rounds used, auto-merge enabled",
);
});
});
@@ -293,10 +299,10 @@ describe("PRStatusChip mobile branch", () => {
},
<PRStatusChip taskId="task-1" />,
);
expect(screen.getByTestId("pr-status-auto-fix-chip").textContent).toBe("Auto-fix");
expect(screen.getByTestId(AUTO_FIX_BADGE_TESTID).textContent).toBe("Auto-fix 0/10");
expect(screen.queryByTestId("pr-status-auto-merge-chip")).toBeNull();
expect(screen.getByTestId(CHIP_TESTID).getAttribute("aria-label")).toBe(
"Pull request #42 CI status, auto-fix enabled",
"Pull request #42 CI status, auto-fix enabled 0 of 10 rounds used",
);
});
+73 -11
View File
@@ -37,7 +37,9 @@ import {
pickDefaultPR,
} from "@/components/github/pr-task-icon";
import { useTouchDrawer } from "@/hooks/use-compact-task-chrome";
import type { TaskPR } from "@/lib/types/github";
import { autoFixRoundForState, findCIAutomationStateForPR } from "@/lib/github/ci-automation";
import type { AutoFixRoundInfo } from "@/lib/github/ci-automation";
import type { TaskCIAutomationOptions, TaskPR } from "@/lib/types/github";
const HOVER_OPEN_DELAY_MS = 150;
const HOVER_CLOSE_DELAY_MS = 150;
@@ -56,6 +58,7 @@ type ChipStatus =
type AutomationFlags = {
autoFix: boolean;
autoMerge: boolean;
autoFixRound: AutoFixRoundInfo | null;
};
function chipStatus(pr: TaskPR): ChipStatus {
@@ -160,10 +163,6 @@ function useChipPopoverInteractions() {
export function PRStatusChip({ taskId }: { taskId: string | null }) {
const { prs } = useTaskPR(taskId);
const { options: automationOptions } = useTaskCIAutomationOptions(taskId);
const automationFlags: AutomationFlags = {
autoFix: Boolean(automationOptions?.auto_fix_enabled),
autoMerge: Boolean(automationOptions?.auto_merge_enabled),
};
// Defensive Array.isArray: a partial hydration can briefly seed the store
// with a non-array value (same guard as PRTaskIcon).
// Only open PRs are worth a CI chip — terminal PRs (merged/closed) are
@@ -180,8 +179,62 @@ export function PRStatusChip({ taskId }: { taskId: string | null }) {
usePRFeedbackBackgroundSync(pickDefaultPR(openPRs));
if (openPRs.length === 0) return null;
if (openPRs.length === 1)
return <PRStatusChipInner pr={openPRs[0]} automation={automationFlags} />;
return <PRStatusChipMultiInner prs={openPRs} automation={automationFlags} />;
return (
<PRStatusChipInner
pr={openPRs[0]}
automation={automationForPR(automationOptions, openPRs[0])}
/>
);
return (
<PRStatusChipMultiInner
prs={openPRs}
automation={automationForPRs(automationOptions, openPRs)}
/>
);
}
function automationForPR(
options: TaskCIAutomationOptions | null | undefined,
pr: TaskPR,
): AutomationFlags {
return {
autoFix: Boolean(options?.auto_fix_enabled),
autoMerge: Boolean(options?.auto_merge_enabled),
autoFixRound: options?.auto_fix_enabled
? autoFixRoundForState(
findCIAutomationStateForPR(options.pr_states, pr),
options.auto_fix_max_rounds,
)
: null,
};
}
function automationForPRs(
options: TaskCIAutomationOptions | null | undefined,
prs: TaskPR[],
): AutomationFlags {
const roundInfos = options?.auto_fix_enabled
? prs.map((pr) =>
autoFixRoundForState(
findCIAutomationStateForPR(options.pr_states, pr),
options.auto_fix_max_rounds,
),
)
: [];
return {
autoFix: Boolean(options?.auto_fix_enabled),
autoMerge: Boolean(options?.auto_merge_enabled),
autoFixRound: pickAttentionRound(roundInfos),
};
}
function pickAttentionRound(roundInfos: AutoFixRoundInfo[]): AutoFixRoundInfo | null {
if (roundInfos.length === 0) return null;
return roundInfos.reduce((best, next) => {
if (next.exhausted && !best.exhausted) return next;
if (next.exhausted === best.exhausted && next.current > best.current) return next;
return best;
});
}
type ChipButtonAttrs = {
@@ -196,7 +249,9 @@ type ChipButtonAttrs = {
function automationAriaSuffix(automation: AutomationFlags): string {
const flags = [
automation.autoFix ? "auto-fix enabled" : null,
automation.autoFix
? `auto-fix enabled${automation.autoFixRound ? ` ${automation.autoFixRound.current} of ${automation.autoFixRound.max} rounds used` : ""}`
: null,
automation.autoMerge ? "auto-merge enabled" : null,
].filter(Boolean);
return flags.length > 0 ? `, ${flags.join(", ")}` : "";
@@ -220,14 +275,21 @@ function chipButtonAttrs(
function AutomationFlagBadges({ automation }: { automation: AutomationFlags }) {
if (!automation.autoFix && !automation.autoMerge) return null;
const autoFixRound = automation.autoFixRound;
return (
<>
{automation.autoFix && (
{automation.autoFix && autoFixRound && (
<span
data-testid="pr-status-auto-fix-chip"
className="rounded-sm bg-emerald-500/15 px-1 py-0.5 text-[9px] font-medium leading-none text-emerald-500"
data-auto-fix-round={`${autoFixRound.current}/${autoFixRound.max}`}
data-auto-fix-exhausted={autoFixRound.exhausted ? "true" : "false"}
className={`rounded-sm px-1 py-0.5 text-[9px] font-medium leading-none ${
autoFixRound.exhausted
? "bg-yellow-500/15 text-yellow-500"
: "bg-emerald-500/15 text-emerald-500"
}`}
>
Auto-fix
Auto-fix {autoFixRound.current}/{autoFixRound.max}
</span>
)}
{automation.autoMerge && (