feat(gitlab): add task MR lifecycle notifications (#2125)

Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
This commit is contained in:
Alassane
2026-08-05 13:22:31 -04:00
committed by GitHub
parent d7620d912d
commit ae31fa85a9
127 changed files with 10118 additions and 242 deletions
@@ -0,0 +1,254 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cleanup, render, screen, fireEvent } from "@testing-library/react";
import { TooltipProvider } from "@kandev/ui/tooltip";
import { ToastProvider } from "@/components/toast-provider";
import type { TaskMRAutomationOptions } from "@/lib/types/gitlab";
const hookMocks = vi.hoisted(() => ({
error: null as string | null,
options: null as TaskMRAutomationOptions | null,
loading: false,
updateMock: vi.fn(),
refreshMock: vi.fn(),
}));
const responsiveMock = vi.hoisted(() => ({
isFinePointer: true,
isMobile: false,
}));
vi.mock("@/hooks/use-responsive-breakpoint", () => ({
useResponsiveBreakpoint: () => ({
isFinePointer: responsiveMock.isFinePointer,
isMobile: responsiveMock.isMobile,
}),
}));
vi.mock("@/hooks/domains/gitlab/use-task-mr-automation", () => ({
useTaskMRAutomationOptions: () => ({
options: hookMocks.options,
loading: hookMocks.loading,
saving: false,
error: hookMocks.error,
refresh: hookMocks.refreshMock,
update: hookMocks.updateMock,
}),
}));
import { MRAutomationControls } from "./mr-automation-controls";
const MERGED_LABEL = "MR merged";
const CLOSED_LABEL = "MR closed without merging";
const REVIEW_REQUESTED_LABEL = "Your review is requested";
const FOLLOW_UP_TRIGGER = "mr-review-follow-up-trigger";
function makeOptions(overrides: Partial<TaskMRAutomationOptions> = {}): TaskMRAutomationOptions {
return {
task_id: "task-1",
prompt_on_review_requested: false,
prompt_on_merged: false,
prompt_on_closed: false,
review_reviewer_username: "",
updated_at: "2026-06-18T10:00:00Z",
mr_states: [],
...overrides,
};
}
function renderControls() {
return render(
<TooltipProvider>
<ToastProvider>
<MRAutomationControls taskId="task-1" />
</ToastProvider>
</TooltipProvider>,
);
}
function resetHookMocks() {
hookMocks.error = null;
hookMocks.options = makeOptions();
hookMocks.loading = false;
hookMocks.updateMock.mockReset();
hookMocks.updateMock.mockResolvedValue(makeOptions());
hookMocks.refreshMock.mockReset();
hookMocks.refreshMock.mockResolvedValue(makeOptions());
responsiveMock.isFinePointer = true;
responsiveMock.isMobile = false;
}
describe("MRAutomationControls", () => {
beforeEach(() => {
resetHookMocks();
});
afterEach(() => {
cleanup();
});
it("keeps the review follow-up group collapsed until opened", () => {
renderControls();
const trigger = screen.getByTestId(FOLLOW_UP_TRIGGER);
expect(trigger.getAttribute("aria-expanded")).toBe("false");
expect(screen.queryByLabelText(REVIEW_REQUESTED_LABEL)).toBeNull();
expect(screen.queryByLabelText(MERGED_LABEL)).toBeNull();
expect(screen.queryByLabelText(CLOSED_LABEL)).toBeNull();
fireEvent.click(trigger);
expect(trigger.getAttribute("aria-expanded")).toBe("true");
expect(screen.getByLabelText(REVIEW_REQUESTED_LABEL)).not.toBeNull();
expect(screen.getByLabelText(MERGED_LABEL)).not.toBeNull();
expect(screen.getByLabelText(CLOSED_LABEL)).not.toBeNull();
});
it("auto-expands when a switch is already on", () => {
hookMocks.options = makeOptions({ prompt_on_merged: true });
renderControls();
expect(screen.getByTestId(FOLLOW_UP_TRIGGER).getAttribute("aria-expanded")).toBe("true");
expect(screen.getByLabelText(MERGED_LABEL)).not.toBeNull();
});
it("shows persistent plain-language copy explaining the switch group, not just on hover/tap", () => {
renderControls();
fireEvent.click(screen.getByTestId(FOLLOW_UP_TRIGGER));
// Visible as soon as the group is open — no help-icon interaction
// required (apps/web/AGENTS.md's self-documenting-settings convention).
expect(
screen.getByText(/Wakes this task's agent when your review is requested/),
).not.toBeNull();
});
it("wires aria-describedby to sr-only descriptions for each row", () => {
renderControls();
fireEvent.click(screen.getByTestId(FOLLOW_UP_TRIGGER));
expect(screen.getByLabelText(REVIEW_REQUESTED_LABEL).getAttribute("aria-describedby")).toBe(
"task-mr-review-requested-prompt-task-1-description",
);
expect(screen.getByLabelText(MERGED_LABEL).getAttribute("aria-describedby")).toBe(
"task-mr-terminal-help-task-1",
);
expect(screen.getByLabelText(CLOSED_LABEL).getAttribute("aria-describedby")).toBe(
"task-mr-terminal-help-task-1",
);
expect(
screen.getByText(
"Wake the agent when the workspace's connected GitLab account is added as a reviewer. Being re-added after removal counts as a new request; staying assigned across MR updates does not.",
),
).not.toBeNull();
expect(
screen.getByText("Wake the agent when review work ends. Choose either or both outcomes."),
).not.toBeNull();
});
it("toggles each switch and calls update with the right patch", () => {
renderControls();
fireEvent.click(screen.getByTestId(FOLLOW_UP_TRIGGER));
fireEvent.click(screen.getByLabelText(REVIEW_REQUESTED_LABEL));
fireEvent.click(screen.getByLabelText(MERGED_LABEL));
fireEvent.click(screen.getByLabelText(CLOSED_LABEL));
expect(hookMocks.updateMock).toHaveBeenCalledWith({ prompt_on_review_requested: true });
expect(hookMocks.updateMock).toHaveBeenCalledWith({ prompt_on_merged: true });
expect(hookMocks.updateMock).toHaveBeenCalledWith({ prompt_on_closed: true });
});
it("surfaces an error from the hook", () => {
hookMocks.error = "network down";
renderControls();
fireEvent.click(screen.getByTestId(FOLLOW_UP_TRIGGER));
expect(screen.getByRole("alert").textContent).toContain("network down");
});
it("shows a retry banner outside the collapsed group when the initial load fails", () => {
hookMocks.options = null;
hookMocks.error = "initial load failed";
renderControls();
// Visible without opening the collapsible group — the group never
// auto-expands with no loaded options, so a nested error would be
// invisible in the default collapsed state.
expect(screen.getByRole("alert").textContent).toContain("initial load failed");
fireEvent.click(screen.getByTestId("mr-automation-retry"));
expect(hookMocks.refreshMock).toHaveBeenCalledTimes(1);
});
it("does not duplicate the error banner once options have loaded (save/update error)", () => {
hookMocks.options = makeOptions();
hookMocks.error = "save failed";
renderControls();
expect(screen.queryByTestId("mr-automation-retry")).toBeNull();
fireEvent.click(screen.getByTestId(FOLLOW_UP_TRIGGER));
expect(screen.getAllByRole("alert")).toHaveLength(1);
});
it("disables the switches until options have loaded", () => {
hookMocks.options = null;
hookMocks.loading = true;
renderControls();
fireEvent.click(screen.getByTestId(FOLLOW_UP_TRIGGER));
expect((screen.getByLabelText(REVIEW_REQUESTED_LABEL) as HTMLButtonElement).disabled).toBe(
true,
);
expect((screen.getByLabelText(MERGED_LABEL) as HTMLButtonElement).disabled).toBe(true);
expect((screen.getByLabelText(CLOSED_LABEL) as HTMLButtonElement).disabled).toBe(true);
});
});
describe("MRAutomationControls help affordance", () => {
beforeEach(() => {
resetHookMocks();
});
afterEach(() => {
cleanup();
});
it("shows the help affordance via keyboard focus (AC29)", () => {
renderControls();
fireEvent.click(screen.getByTestId(FOLLOW_UP_TRIGGER));
const helpButton = screen.getByTestId("mr-review-requested-help");
expect(helpButton).not.toBeNull();
fireEvent.focus(helpButton);
// happy-dom opens Radix Tooltip on focus (unlike jsdom — see
// apps/web/CLAUDE.md); assert the tooltip's role="tooltip" surface
// rendered with the help copy.
expect(screen.getByRole("tooltip").textContent).toContain(
"Wake the agent when the workspace's connected GitLab account is added as a reviewer",
);
});
it("renders a coarse-pointer tap popover instead of a hover tooltip", () => {
responsiveMock.isFinePointer = false;
renderControls();
fireEvent.click(screen.getByTestId(FOLLOW_UP_TRIGGER));
const helpButton = screen.getByTestId("mr-review-requested-help");
fireEvent.click(helpButton);
// The sr-only description and the popover both carry the same copy;
// assert the popover's role="dialog" surface rendered at all.
expect(helpButton.getAttribute("aria-haspopup")).toBe("dialog");
expect(
screen.getAllByText(
"Wake the agent when the workspace's connected GitLab account is added as a reviewer. Being re-added after removal counts as a new request; staying assigned across MR updates does not.",
).length,
).toBeGreaterThan(1);
});
it("keeps the trigger compact on desktop and touch-sized on mobile", () => {
renderControls();
const desktopTrigger = screen.getByTestId(FOLLOW_UP_TRIGGER);
expect(desktopTrigger.classList.contains("min-h-7")).toBe(true);
cleanup();
responsiveMock.isMobile = true;
renderControls();
expect(screen.getByTestId(FOLLOW_UP_TRIGGER).classList.contains("min-h-11")).toBe(true);
});
});
@@ -0,0 +1,318 @@
"use client";
import { useEffect, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { IconChevronDown, IconInfoCircle } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@kandev/ui/collapsible";
import { Label } from "@kandev/ui/label";
import { Popover, PopoverContent, PopoverTrigger } from "@kandev/ui/popover";
import { Switch } from "@kandev/ui/switch";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { useToast } from "@/components/toast-provider";
import { useTaskMRAutomationOptions } from "@/hooks/domains/gitlab/use-task-mr-automation";
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
import type { TaskMRAutomationOptions, TaskMRAutomationPatch } from "@/lib/types/gitlab";
/**
* Dual-mode help affordance: a tap popover on coarse pointers, a hover
* tooltip on fine pointers. Mirrors CIAutomationHelpButton (GitHub).
*/
function MRAutomationHelpButton({
ariaLabel,
testId,
children,
}: {
ariaLabel: string;
testId: string;
children: ReactNode;
}) {
const { isFinePointer } = useResponsiveBreakpoint();
const [open, setOpen] = useState(false);
const trigger = (
<Button
type="button"
variant="ghost"
size="icon"
data-testid={testId}
className="h-5 w-5 cursor-help text-muted-foreground hover:text-foreground"
aria-label={ariaLabel}
>
<IconInfoCircle className="h-3.5 w-3.5" />
</Button>
);
if (!isFinePointer) {
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>{trigger}</PopoverTrigger>
<PopoverContent
side="top"
align="start"
portal={false}
className="max-w-[280px] text-xs leading-relaxed"
>
{children}
</PopoverContent>
</Popover>
);
}
return (
<Tooltip>
<TooltipTrigger asChild>{trigger}</TooltipTrigger>
<TooltipContent side="top" align="start" className="max-w-[280px] text-xs leading-relaxed">
{children}
</TooltipContent>
</Tooltip>
);
}
function MRAutomationRow({
id,
label,
checked,
disabled,
onCheckedChange,
help,
describedBy,
}: {
id: string;
label: string;
checked: boolean;
disabled: boolean;
onCheckedChange: (checked: boolean) => void;
help?: ReactNode;
describedBy?: string;
}) {
const { isFinePointer, isMobile } = useResponsiveBreakpoint();
const minHeight = isMobile || !isFinePointer ? "min-h-11" : "min-h-7";
return (
<div className={`flex items-center justify-between gap-3 px-1 ${minHeight}`}>
<div className="flex min-w-0 flex-1 items-center gap-1.5">
<Label htmlFor={id} className="min-w-0 cursor-pointer text-xs leading-5">
{label}
</Label>
{help}
</div>
<Switch
id={id}
aria-label={label}
aria-describedby={describedBy}
checked={checked}
disabled={disabled}
onCheckedChange={onCheckedChange}
/>
</div>
);
}
function MRAutomationErrorRow({ error }: { error: string }) {
return (
<div role="alert" className="px-1 text-[11px] text-destructive">
<span className="min-w-0 flex-1 truncate">{error}</span>
</div>
);
}
/**
* Shown outside the collapsible section so an initial-load failure stays
* visible (and recoverable) in the default collapsed state — the group
* never auto-expands when there are no loaded options to detect an enabled
* switch from, so an error nested inside CollapsibleContent would otherwise
* be invisible until the user manually opens it.
*/
function MRAutomationLoadErrorBanner({ error, onRetry }: { error: string; onRetry: () => void }) {
const { isFinePointer, isMobile } = useResponsiveBreakpoint();
const { t } = useTranslation();
const minHeight = isMobile || !isFinePointer ? "min-h-11" : "min-h-7";
return (
<div
role="alert"
className={`flex items-center justify-between gap-2 px-1 text-[11px] text-destructive ${minHeight}`}
>
<span className="min-w-0 flex-1 truncate">{error}</span>
<Button
type="button"
variant="ghost"
size="sm"
data-testid="mr-automation-retry"
className={`cursor-pointer px-2 text-[11px] ${minHeight}`}
onClick={onRetry}
>
{t("gitlab:mrAutomationRetry")}
</Button>
</div>
);
}
function ReviewRequestedPromptRow({
taskId,
options,
disabled,
patchOption,
}: {
taskId: string;
options: TaskMRAutomationOptions | null;
disabled: boolean;
patchOption: (patch: TaskMRAutomationPatch) => void;
}) {
const { t } = useTranslation();
const helpID = `task-mr-review-requested-prompt-${taskId}-description`;
const help = t("gitlab:mrAutomationReviewRequestedHelp");
return (
<>
<span id={helpID} className="sr-only">
{help}
</span>
<MRAutomationRow
id={`task-mr-review-requested-prompt-${taskId}`}
label={t("gitlab:mrAutomationReviewRequestedLabel")}
describedBy={helpID}
checked={Boolean(options?.prompt_on_review_requested)}
disabled={disabled}
onCheckedChange={(checked) => patchOption({ prompt_on_review_requested: checked })}
help={
<MRAutomationHelpButton
testId="mr-review-requested-help"
ariaLabel={t("gitlab:mrAutomationReviewRequestedHelpAriaLabel")}
>
{help}
</MRAutomationHelpButton>
}
/>
</>
);
}
function MRAgentPromptRows({
taskId,
options,
disabled,
patchOption,
}: {
taskId: string;
options: TaskMRAutomationOptions | null;
disabled: boolean;
patchOption: (patch: TaskMRAutomationPatch) => void;
}) {
const { t } = useTranslation();
const terminalHelpID = `task-mr-terminal-help-${taskId}`;
const terminalHelp = t("gitlab:mrAutomationTerminalHelp");
return (
<>
<ReviewRequestedPromptRow
taskId={taskId}
options={options}
disabled={disabled}
patchOption={patchOption}
/>
<span id={terminalHelpID} className="sr-only">
{terminalHelp}
</span>
<MRAutomationRow
id={`task-mr-merged-prompt-${taskId}`}
label={t("gitlab:mrAutomationMergedLabel")}
describedBy={terminalHelpID}
checked={Boolean(options?.prompt_on_merged)}
disabled={disabled}
onCheckedChange={(checked) => patchOption({ prompt_on_merged: checked })}
help={
<MRAutomationHelpButton
testId="mr-terminal-help"
ariaLabel={t("gitlab:mrAutomationTerminalHelpAriaLabel")}
>
{terminalHelp}
</MRAutomationHelpButton>
}
/>
<MRAutomationRow
id={`task-mr-closed-prompt-${taskId}`}
label={t("gitlab:mrAutomationClosedLabel")}
describedBy={terminalHelpID}
checked={Boolean(options?.prompt_on_closed)}
disabled={disabled}
onCheckedChange={(checked) => patchOption({ prompt_on_closed: checked })}
/>
</>
);
}
/**
* Collapsible "Review follow-up" group of three compact switch rows. Renders
* inside the GitLab MR topbar dropdown, below the per-MR items. Auto-expands
* when any switch is already on so a previously configured task doesn't hide
* its active switches. Mirrors ReviewFollowUpSection (GitHub), AC29.
*/
export function MRAutomationControls({ taskId }: { taskId: string }) {
const { options, loading, saving, error, update, refresh } = useTaskMRAutomationOptions(taskId);
const { isFinePointer, isMobile } = useResponsiveBreakpoint();
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const { toast } = useToast();
const lifecycleEnabled = Boolean(
options?.prompt_on_review_requested || options?.prompt_on_merged || options?.prompt_on_closed,
);
const minHeight = isMobile || !isFinePointer ? "min-h-11" : "min-h-7";
useEffect(() => {
if (lifecycleEnabled) setOpen(true);
}, [lifecycleEnabled]);
const patchOption = (patch: TaskMRAutomationPatch) => {
update(patch).catch((err) => {
toast({
title: t("gitlab:mrAutomationUpdateFailedTitle"),
description:
err instanceof Error ? err.message : t("gitlab:mrAutomationUpdateFailedDescription"),
variant: "error",
});
});
};
const loadFailed = Boolean(error) && !options;
return (
<div data-testid="mr-automation-controls">
{loadFailed ? (
<MRAutomationLoadErrorBanner
error={error as string}
onRetry={() => {
refresh().catch(() => {
// Error state is already surfaced by the hook; nothing further to do here.
});
}}
/>
) : null}
<Collapsible open={open} onOpenChange={setOpen}>
<CollapsibleTrigger asChild>
<Button
type="button"
variant="ghost"
size="sm"
data-testid="mr-review-follow-up-trigger"
aria-label={t("gitlab:mrAutomationToggleAriaLabel")}
className={`w-full cursor-pointer justify-between px-1 text-xs text-muted-foreground ${minHeight}`}
>
{t("gitlab:mrAutomationTriggerLabel")}
<IconChevronDown
aria-hidden="true"
className={`h-3.5 w-3.5 transition-transform ${open ? "rotate-180" : ""}`}
/>
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="flex flex-col gap-1">
<p className="px-1 text-[11px] leading-snug text-muted-foreground">
{t("gitlab:mrAutomationDescription")}
</p>
<MRAgentPromptRows
taskId={taskId}
options={options}
disabled={saving || loading || !options}
patchOption={patchOption}
/>
{error && options ? <MRAutomationErrorRow error={error} /> : null}
</CollapsibleContent>
</Collapsible>
</div>
);
}
@@ -32,6 +32,7 @@ import { deleteTaskMR } from "@/lib/api/domains/gitlab-api";
import type { TaskMR } from "@/lib/types/gitlab";
import type { Repository } from "@/lib/types/http";
import { TaskMRLinkDialog } from "./task-mr-link-dialog";
import { MRAutomationControls } from "./mr-automation-controls";
import { useDockviewStore } from "@/lib/state/dockview-store";
import { mrTaskKey } from "./mr-detail-panel";
import { useTranslation } from "react-i18next";
@@ -119,6 +120,7 @@ function MRTriggerContent({
}
function MRMenuButton({
taskId,
mrs,
canLink,
compact,
@@ -126,6 +128,7 @@ function MRMenuButton({
onLink,
onUnlink,
}: {
taskId: string;
mrs: TaskMR[];
canLink: boolean;
compact: boolean;
@@ -201,6 +204,8 @@ function MRMenuButton({
</DropdownMenuItem>
</div>
))}
<DropdownMenuSeparator />
<MRAutomationControls taskId={taskId} />
{canLink ? (
<>
<DropdownMenuSeparator />
@@ -219,6 +224,7 @@ const EMPTY_REPOSITORIES: Repository[] = [];
const EMPTY_TASK_REPOSITORIES: Array<{ repository_id: string }> = [];
function MRTopbarControl({
taskId,
mrs,
gitlabAvailable,
compact,
@@ -226,6 +232,7 @@ function MRTopbarControl({
onLink,
onUnlink,
}: {
taskId: string;
mrs: TaskMR[];
gitlabAvailable: boolean;
compact: boolean;
@@ -236,6 +243,7 @@ function MRTopbarControl({
if (mrs.length > 0) {
return (
<MRMenuButton
taskId={taskId}
mrs={mrs}
canLink={gitlabAvailable}
compact={compact}
@@ -290,6 +298,7 @@ export const MRTopbarButton = memo(function MRTopbarButton({
return (
<>
<MRTopbarControl
taskId={activeTaskId}
mrs={mrs}
gitlabAvailable={gitlabAvailable}
compact={compact}