feat(github): explain workflow approval attention (#3584)

This commit is contained in:
Carlos Florêncio
2026-09-10 23:39:56 +01:00
committed by GitHub
parent 1262d4476d
commit f817de3df5
56 changed files with 3694 additions and 82 deletions
@@ -19,6 +19,7 @@ import type { CheckRun, TaskPR } from "@/lib/types/github";
import { PRCIAutomationControls } from "./pr-ci-automation-controls";
import { PRMergeButton } from "./pr-merge-button";
import { PRMergeabilityRow } from "./pr-mergeability-row";
import { PRWorkflowAttentionNotice } from "./pr-workflow-attention-notice";
import {
ChangeRequestCIPopoverFrame,
ChangeRequestChecksSection,
@@ -289,6 +290,7 @@ export function PRCIPopover({
return (
<ChangeRequestCIPopoverFrame>
<PRCIPopoverHeader pr={pr} onOpenDetailPanel={onOpenDetailPanel} />
<PRWorkflowAttentionNotice pr={pr} attention={feedback?.workflow_attention} />
{authLost ? (
<ReconnectGitHubBlock />
) : (
+54 -14
View File
@@ -20,10 +20,11 @@ import { useCommentsStore, isPRFeedbackComment } from "@/lib/state/slices/commen
import type { PRFeedbackComment } from "@/lib/state/slices/comments";
import { useToast } from "@/components/toast-provider";
import { submitPRReview } from "@/lib/api/domains/github-pr-api";
import type { TaskPR, PRFeedback } from "@/lib/types/github";
import type { TaskPR, PRFeedback, MergeableState } from "@/lib/types/github";
import { PRMergeButton } from "./pr-merge-button";
import { PRMergeabilityNotice, buildConflictResolutionMessage } from "./pr-mergeability-notice";
import { hasActiveMergeQueueEntry, PRMergeQueueStatus } from "./pr-merge-queue-status";
import { PRWorkflowAttentionNotice } from "./pr-workflow-attention-notice";
import { usePRScopedReviewRequest } from "./use-pr-scoped-review-request";
// --- Dockview panel wrapper ---
@@ -387,6 +388,47 @@ function useConflictQueued(sessionId: string, prNumber: number): boolean {
);
}
function PRDetailNotice({
displayPR,
attention,
mergeableState,
mergeable,
isDraft,
prState,
baseBranch,
onResolveConflicts,
resolveDisabled,
}: {
displayPR: TaskPR;
attention?: PRFeedback["workflow_attention"];
mergeableState: MergeableState | undefined;
mergeable: boolean;
isDraft: boolean;
prState: TaskPR["state"];
baseBranch: string;
onResolveConflicts: () => void;
resolveDisabled: boolean;
}) {
return (
<div className="space-y-2">
<PRWorkflowAttentionNotice pr={displayPR} attention={attention} />
{hasActiveMergeQueueEntry(displayPR) ? (
<PRMergeQueueStatus pr={displayPR} />
) : (
<PRMergeabilityNotice
state={mergeableState}
mergeable={mergeable}
isDraft={isDraft}
prState={prState}
baseBranch={baseBranch}
onResolveConflicts={onResolveConflicts}
resolveDisabled={resolveDisabled}
/>
)}
</div>
);
}
export function PRDetailContent({ taskPR, sessionId }: { taskPR: TaskPR; sessionId: string }) {
const { t } = useTranslation();
const workspaceId = useAppStore((state) => state.workspaces.activeId);
@@ -458,19 +500,17 @@ export function PRDetailContent({ taskPR, sessionId }: { taskPR: TaskPR; session
</>
}
notice={
hasActiveMergeQueueEntry(displayPR) ? (
<PRMergeQueueStatus pr={displayPR} />
) : (
<PRMergeabilityNotice
state={mergeableState}
mergeable={isMergeable}
isDraft={isDraft}
prState={liveState}
baseBranch={taskPR.base_branch}
onResolveConflicts={onResolveConflicts}
resolveDisabled={conflictQueued}
/>
)
<PRDetailNotice
displayPR={displayPR}
attention={feedback?.workflow_attention}
mergeableState={mergeableState}
mergeable={isMergeable}
isDraft={isDraft}
prState={liveState}
baseBranch={taskPR.base_branch}
onResolveConflicts={onResolveConflicts}
resolveDisabled={conflictQueued}
/>
}
/>
);
@@ -47,6 +47,7 @@ import {
import type { AutomationFlags } from "@/components/github/pr-status-automation-badges";
import type { TaskPR } from "@/lib/types/github";
import type { TFunction } from "i18next";
import { getTaskPRWorkflowAttention } from "./pr-workflow-attention";
const HOVER_OPEN_DELAY_MS = 150;
const HOVER_CLOSE_DELAY_MS = 150;
@@ -63,6 +64,7 @@ type ChipStatus =
| "waiting"
| "queued"
| "in_progress"
| "attention"
| "neutral";
type TriggerRef = { current: HTMLButtonElement | null };
type SingleChipProps = {
@@ -96,6 +98,7 @@ function chipStatus(pr: TaskPR): ChipStatus {
// getPRStatusColor + PRStatusIcon (dirty = red, behind = amber).
if (pr.mergeable_state === "dirty") return "conflict";
if (pr.mergeable_state === "behind") return "behind";
if (getTaskPRWorkflowAttention(pr)) return "attention";
// Pending checks / pending review must beat checks_state === "success" so a
// PR with all checks green but reviewers still outstanding renders as
// in-progress, not passed. Without this order, the chip flips to green the
@@ -121,6 +124,7 @@ const CHIP_STATUS_RANK: Record<ChipStatus, number> = {
blocked: 4,
behind: 3,
queued: 2.5,
attention: 2.25,
draft: 0.5,
in_progress: 2,
waiting: 1.5,
@@ -486,6 +490,14 @@ function ChipStatusGlyph({ status }: { status: ChipStatus }) {
aria-hidden="true"
/>
);
case "attention":
return (
<IconAlertTriangleFilled
data-testid="pr-status-glyph-attention"
className="h-3.5 w-3.5 text-yellow-500"
aria-hidden="true"
/>
);
default:
return <IconPointFilled className="h-3.5 w-3.5 text-muted-foreground" aria-hidden="true" />;
}
@@ -26,6 +26,7 @@ import {
type PRTaskIconDisclosureProps,
} from "./pr-task-icon-disclosure";
import { getTaskPRAutomationSummary, type TaskPRInfo } from "./pr-task-automation";
import { getTaskPRWorkflowAttention } from "./pr-workflow-attention";
export type { TaskPRInfo } from "./pr-task-automation";
export { getTaskPRAutomationSummary } from "./pr-task-automation";
@@ -79,6 +80,7 @@ export function hasPRChecksPassedWithoutReviewWaitForDisplay(pr: TaskPR): boolea
// syncs that do not populate check details.
export function isPRReadyToMerge(pr: TaskPR): boolean {
if (pr.state !== "open") return false;
if (getTaskPRWorkflowAttention(pr)) return false;
if (!hasExplicitPRChecksPassed(pr)) return false;
if (pr.mergeable_state !== "clean") return false;
// Guard against stale mergeable_state: enforce required_reviews to match GitHub's gate.
@@ -165,6 +167,7 @@ export function getPRStatusColor(pr: TaskPR): string {
}
const blockerColor = openMergeBlockerColor(pr);
if (blockerColor) return blockerColor;
if (getTaskPRWorkflowAttention(pr)) return YELLOW_500;
if (isPRReadyToMerge(pr)) {
return EMERALD_400;
}
@@ -14,6 +14,11 @@ import {
type ChangeRequestTaskSummaryStatus,
type ChangeRequestTaskSummaryTone,
} from "@/components/integrations/change-request-task-status-summary";
import {
getCurrentWorkflowAttention,
isWorkflowApprovalRequired,
workflowAttentionWorkflowNames,
} from "./pr-workflow-attention";
export type PRTaskSummaryRowKind = ChangeRequestTaskSummaryRowKind;
export type PRTaskSummaryTone = ChangeRequestTaskSummaryTone;
@@ -46,14 +51,57 @@ function deriveReviewRow(reviewState: string): PRTaskSummaryRow | null {
return rawRow("review", reviewState);
}
function deriveCIRow(checksState: string): PRTaskSummaryRow | null {
if (!checksState) return null;
if (checksState === "success") return { kind: "ci", status: "passed", tone: "success" };
if (checksState === "failure") return { kind: "ci", status: "failed", tone: "danger" };
if (checksState === "pending") {
return { kind: "ci", status: "in_progress", tone: "warning" };
function workflowAttentionRow(pr: TaskPR): PRTaskSummaryRow | null {
const attention = getCurrentWorkflowAttention(pr);
if (!attention) return null;
if (attention.state === "unknown") {
return {
kind: "ci",
id: "workflow-attention",
status: "workflow_unavailable",
tone: "muted",
};
}
return rawRow("ci", checksState);
if (attention.state !== "approval_required" && attention.state !== "action_required") {
return null;
}
const names = workflowAttentionWorkflowNames(attention);
return {
kind: "ci",
id: "workflow-attention",
status: isWorkflowApprovalRequired(attention) ? "awaiting_approval" : "workflow_attention",
tone: "warning",
...(names
? {
detail: {
key: "github:workflowAttentionWorkflows",
values: { names },
},
}
: {}),
};
}
function deriveCIRows(pr: TaskPR): PRTaskSummaryRow[] {
const attentionRow = workflowAttentionRow(pr);
const attentionExplainsUnstable =
attentionRow?.status === "awaiting_approval" || attentionRow?.status === "workflow_attention";
const rows: PRTaskSummaryRow[] = [];
if (pr.checks_state === "success") rows.push({ kind: "ci", status: "passed", tone: "success" });
else if (pr.checks_state === "failure") {
rows.push({ kind: "ci", status: "failed", tone: "danger" });
} else if (pr.checks_state === "pending") {
rows.push({ kind: "ci", status: "in_progress", tone: "warning" });
} else if (
pr.checks_state === "unstable" ||
(pr.mergeable_state === "unstable" && !attentionExplainsUnstable)
) {
if (!attentionExplainsUnstable) {
rows.push({ kind: "ci", status: "checks_not_successful", tone: "warning" });
}
} else if (pr.checks_state) rows.push(rawRow("ci", pr.checks_state));
if (attentionRow) rows.push(attentionRow);
return rows;
}
function deriveMergeRow(pr: TaskPR, readyToMerge: boolean): PRTaskSummaryRow | null {
@@ -86,6 +134,7 @@ function deriveMergeRow(pr: TaskPR, readyToMerge: boolean): PRTaskSummaryRow | n
if (pr.mergeable_state === "clean") {
return { kind: "merge", status: "mergeable", tone: "muted" };
}
if (pr.mergeable_state === "unstable") return null;
return rawRow("merge", pr.mergeable_state);
}
@@ -96,7 +145,7 @@ export function derivePRTaskStatusSummary(
const rows = [
deriveStateRow(pr.state),
deriveReviewRow(pr.review_state),
deriveCIRow(pr.checks_state),
...deriveCIRows(pr),
deriveMergeRow(pr, readyToMerge),
].filter((row): row is PRTaskSummaryRow => row !== null);
@@ -0,0 +1,143 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ReactNode } from "react";
import { 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, aggregateChipStatus } from "./pr-status-chip";
import { makeTestPR as makePR } from "./pr-status-chip.test-fixtures";
import type { AppState } from "@/lib/state/store";
import type { TaskPR, WorkflowAttention } from "@/lib/types/github";
const CHIP_TESTID = "pr-status-chip";
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({
task_id: "task-1",
auto_fix_enabled: false,
auto_merge_enabled: false,
auto_fix_prompt_override: null,
effective_auto_fix_prompt: "Default CI fix prompt",
using_default_prompt: true,
updated_at: "2026-06-18T10:00:00Z",
pr_states: [],
pr_options: [],
}),
listWorkspaceTaskPRs: vi.fn().mockResolvedValue({ task_prs: {} }),
};
});
vi.mock("@/lib/ws/connection", () => ({
getWebSocketClient: () => null,
}));
function renderWithStore(initialState: Partial<AppState>, ui: ReactNode) {
return render(
<StateProvider initialState={initialState}>
<ToastProvider>
<TooltipProvider>{ui}</TooltipProvider>
</ToastProvider>
</StateProvider>,
);
}
function makeAttention(
state: WorkflowAttention["state"],
runs: WorkflowAttention["runs"] = [],
): WorkflowAttention {
return {
state,
head_sha: "head-1",
observed_at: "2026-09-10T10:00:00Z",
stale: true,
runs,
};
}
function makeAttentionPR(attention: WorkflowAttention): TaskPR {
return makePR({ head_sha: "head-1", workflow_attention: attention });
}
beforeEach(() => {
responsiveMock.breakpoint = "desktop";
responsiveMock.isFinePointer = true;
});
afterEach(() => {
cleanup();
});
describe("workflow attention chip status", () => {
it("marks current-head workflow attention as a warning", () => {
expect(aggregateChipStatus([makeAttentionPR(makeAttention("approval_required"))])).toBe(
"attention",
);
});
});
describe("workflow attention desktop popover", () => {
it("shows the workflow reason and an external workflow link", async () => {
const pr = makeAttentionPR(
makeAttention("approval_required", [
{
run_id: 7,
run_attempt: 1,
workflow_id: 9,
name: "Run tests",
url: "https://github.com/acme/demo/actions/runs/7",
reason: "approval_required",
},
]),
);
renderWithStore(
{ taskPRs: { byTaskId: { "task-1": [pr] } } },
<PRStatusChip taskId="task-1" />,
);
fireEvent.mouseEnter(screen.getByTestId(CHIP_TESTID));
const notice = await screen.findByTestId("pr-workflow-attention");
expect(notice.textContent).toContain("Awaiting maintainer approval");
expect(notice.textContent).toContain("Run tests");
expect(screen.getByTestId("pr-workflow-attention-link").getAttribute("href")).toBe(
"https://github.com/acme/demo/actions/runs/7",
);
expect(screen.getByTestId("pr-workflow-attention-link").className).toContain("min-h-11");
expect(notice.textContent).toContain("Last known status");
});
it("shows unavailable workflow evidence without claiming approval", async () => {
renderWithStore(
{ taskPRs: { byTaskId: { "task-1": [makeAttentionPR(makeAttention("unknown"))] } } },
<PRStatusChip taskId="task-1" />,
);
fireEvent.mouseEnter(screen.getByTestId(CHIP_TESTID));
const notice = await screen.findByTestId("pr-workflow-attention");
expect(notice.textContent).toContain("Workflow status unavailable");
expect(notice.textContent).not.toContain("Awaiting maintainer approval");
});
});
@@ -0,0 +1,43 @@
import { describe, expect, it } from "vitest";
import { getPRStatusColor, isPRReadyToMerge } from "./pr-task-icon";
import { makeTestPR as makePR } from "./pr-status-chip.test-fixtures";
const YELLOW_500 = "text-yellow-500";
describe("workflow attention task icon", () => {
const attention = {
state: "approval_required" as const,
head_sha: "head-1",
observed_at: "2026-09-10T10:00:00Z",
stale: true,
runs: [],
};
it("blocks readiness while current-head workflow attention is active", () => {
expect(
isPRReadyToMerge(
makePR({
head_sha: "head-1",
review_state: "approved",
checks_state: "success",
mergeable_state: "clean",
workflow_attention: attention,
}),
),
).toBe(false);
});
it("uses a warning color instead of ready green", () => {
expect(
getPRStatusColor(
makePR({
head_sha: "head-1",
review_state: "approved",
checks_state: "success",
mergeable_state: "clean",
workflow_attention: { ...attention, stale: false },
}),
),
).toBe(YELLOW_500);
});
});
@@ -0,0 +1,78 @@
"use client";
import { IconAlertTriangle } from "@tabler/icons-react";
import { useTranslation } from "react-i18next";
import type { TaskPR, WorkflowAttention } from "@/lib/types/github";
import {
getWorkflowAttentionForDisplay,
isWorkflowApprovalRequired,
workflowAttentionReasonKey,
} from "./pr-workflow-attention";
export function PRWorkflowAttentionNotice({
pr,
attention: suppliedAttention,
}: {
pr: TaskPR;
attention?: WorkflowAttention | null;
}) {
const { t } = useTranslation();
const attention = getWorkflowAttentionForDisplay(pr, suppliedAttention);
if (!attention) return null;
return (
<section
data-testid="pr-workflow-attention"
role="status"
className="rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs"
>
<div className="flex items-start gap-2">
<IconAlertTriangle
className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400"
aria-hidden="true"
/>
<div className="min-w-0 flex-1 space-y-2">
<p className="font-medium text-foreground">
{attention.state === "unknown"
? t("github:workflowStatusUnavailable")
: t(
isWorkflowApprovalRequired(attention)
? "github:workflowAwaitingApproval"
: "github:workflowNeedsAttention",
)}
</p>
{attention.runs.map((run) => (
<div
key={`${run.run_id}-${run.run_attempt}`}
data-testid="pr-workflow-attention-run"
className="flex flex-col gap-1"
>
<div className="flex min-w-0 flex-wrap items-baseline gap-x-2 gap-y-0.5">
<span className="min-w-0 break-words font-medium text-foreground">
{run.name || t("github:workflow")}
</span>
<span className="text-muted-foreground">
{t(workflowAttentionReasonKey(run.reason))}
</span>
</div>
{run.url ? (
<a
data-testid="pr-workflow-attention-link"
href={run.url}
target="_blank"
rel="noreferrer"
className="inline-flex min-h-11 cursor-pointer items-center self-start text-primary hover:underline [@media(pointer:fine)]:min-h-0"
>
{t("github:viewWorkflowOnGithub")}
</a>
) : null}
</div>
))}
{attention.stale ? (
<p className="text-muted-foreground">{t("github:workflowAttentionStale")}</p>
) : null}
</div>
</div>
</section>
);
}
@@ -0,0 +1,154 @@
import { describe, expect, it } from "vitest";
import { derivePRTaskStatusSummary } from "./pr-task-status-summary";
import { makeTestPR as makePR } from "./pr-status-chip.test-fixtures";
import type { TaskPR, WorkflowAttention, WorkflowAttentionRun } from "@/lib/types/github";
const HEAD_SHA = "head-1";
const OBSERVED_AT = "2026-09-10T10:00:00Z";
const WORKFLOW_ATTENTION_ID = "workflow-attention";
function makeSummaryPR(overrides: Partial<TaskPR> = {}): TaskPR {
return makePR({
review_state: "",
checks_state: "",
mergeable_state: "",
...overrides,
});
}
function makeAttention(
state: WorkflowAttention["state"],
runs: WorkflowAttentionRun[] = [],
overrides: Partial<WorkflowAttention> = {},
): WorkflowAttention {
return {
state,
head_sha: HEAD_SHA,
observed_at: OBSERVED_AT,
stale: false,
runs,
...overrides,
};
}
const approvalRun: WorkflowAttentionRun = {
run_id: 7,
run_attempt: 1,
workflow_id: 9,
name: "Run tests",
url: "https://github.com/acme/widget/actions/runs/7",
reason: "approval_required",
};
describe("workflow attention status summaries", () => {
it("shows the maintainer approval reason when no check runs exist", () => {
const summary = derivePRTaskStatusSummary(
makeSummaryPR({
head_sha: HEAD_SHA,
checks_state: "unstable",
workflow_attention: makeAttention("approval_required", [approvalRun]),
}),
false,
);
expect(summary.rows).toEqual([
{
kind: "ci",
id: WORKFLOW_ATTENTION_ID,
status: "awaiting_approval",
tone: "warning",
detail: {
key: "github:workflowAttentionWorkflows",
values: { names: "Run tests" },
},
},
]);
});
it("keeps an actual failed check beside workflow attention", () => {
const summary = derivePRTaskStatusSummary(
makeSummaryPR({
head_sha: HEAD_SHA,
checks_state: "failure",
workflow_attention: makeAttention("action_required", [], { stale: true }),
}),
false,
);
expect(summary.rows).toEqual([
{ kind: "ci", status: "failed", tone: "danger" },
{
kind: "ci",
id: WORKFLOW_ATTENTION_ID,
status: "workflow_attention",
tone: "warning",
},
]);
});
it("explains an unexplained unstable check state without claiming approval", () => {
const summary = derivePRTaskStatusSummary(makeSummaryPR({ checks_state: "unstable" }), false);
expect(summary.rows).toEqual([
{ kind: "ci", status: "checks_not_successful", tone: "warning" },
]);
});
});
describe("workflow attention fallbacks", () => {
it("does not expose unstable mergeability when workflow approval explains it", () => {
const summary = derivePRTaskStatusSummary(
makeSummaryPR({
head_sha: HEAD_SHA,
mergeable_state: "unstable",
workflow_attention: makeAttention("approval_required"),
}),
false,
);
expect(summary.rows).toEqual([
{ kind: "ci", id: WORKFLOW_ATTENTION_ID, status: "awaiting_approval", tone: "warning" },
]);
});
it("localizes unexplained unstable mergeability as an unsuccessful check", () => {
const summary = derivePRTaskStatusSummary(
makeSummaryPR({ mergeable_state: "unstable" }),
false,
);
expect(summary.rows).toEqual([
{ kind: "ci", status: "checks_not_successful", tone: "warning" },
]);
});
it("keeps unavailable workflow evidence distinct from missing checks", () => {
const summary = derivePRTaskStatusSummary(
makeSummaryPR({
head_sha: HEAD_SHA,
workflow_attention: makeAttention("unknown", [], { stale: true }),
}),
false,
);
expect(summary.rows).toEqual([
{ kind: "ci", id: WORKFLOW_ATTENTION_ID, status: "workflow_unavailable", tone: "muted" },
]);
});
it("keeps an unstable check warning beside unavailable workflow evidence", () => {
const summary = derivePRTaskStatusSummary(
makeSummaryPR({
head_sha: HEAD_SHA,
checks_state: "unstable",
workflow_attention: makeAttention("unknown", [], { stale: true }),
}),
false,
);
expect(summary.rows).toEqual([
{ kind: "ci", status: "checks_not_successful", tone: "warning" },
{ kind: "ci", id: WORKFLOW_ATTENTION_ID, status: "workflow_unavailable", tone: "muted" },
]);
});
});
@@ -0,0 +1,189 @@
import { describe, expect, it } from "vitest";
import type { TaskPR, WorkflowAttention } from "@/lib/types/github";
import {
getActiveWorkflowAttention,
getCurrentWorkflowAttention,
getWorkflowAttentionForDisplay,
} from "./pr-workflow-attention";
const EARLIER_OBSERVED_AT = "2026-09-10T10:00:00Z";
const LATER_OBSERVED_AT = "2026-09-10T11:00:00Z";
function makeAttention(overrides: Partial<WorkflowAttention> = {}): WorkflowAttention {
return {
state: "approval_required",
head_sha: "head-1",
observed_at: EARLIER_OBSERVED_AT,
stale: false,
runs: [
{
run_id: 7,
run_attempt: 1,
workflow_id: 9,
name: "Run tests",
url: "https://github.com/acme/widget/actions/runs/7",
reason: "approval_required",
},
],
...overrides,
};
}
function makePR(overrides: Partial<TaskPR> = {}): TaskPR {
return {
id: "pr-id",
workspace_id: "workspace-1",
task_id: "task-id",
owner: "acme",
repo: "widget",
pr_number: 143,
pr_url: "https://github.com/acme/widget/pull/143",
pr_title: "Workflow attention",
head_branch: "feat/workflow",
base_branch: "main",
author_login: "octocat",
state: "open",
review_state: "",
checks_state: "",
mergeable_state: "unstable",
review_count: 0,
pending_review_count: 0,
comment_count: 0,
unresolved_review_threads: 0,
checks_total: 0,
checks_passing: 0,
additions: 0,
deletions: 0,
created_at: "",
merged_at: null,
closed_at: null,
last_synced_at: null,
updated_at: "",
head_sha: "head-1",
...overrides,
};
}
describe("getActiveWorkflowAttention", () => {
it("returns current approval evidence, including stale same-head evidence", () => {
const attention = makeAttention({ stale: true });
expect(getActiveWorkflowAttention(makePR({ workflow_attention: attention }))).toBe(attention);
});
it("rejects legacy, unknown, terminal, and changed-head observations", () => {
expect(getActiveWorkflowAttention(makePR())).toBeNull();
expect(
getActiveWorkflowAttention(
makePR({ workflow_attention: makeAttention({ state: "unknown" }) }),
),
).toBeNull();
expect(
getActiveWorkflowAttention(makePR({ workflow_attention: makeAttention({ state: "none" }) })),
).toBeNull();
expect(
getActiveWorkflowAttention(
makePR({ workflow_attention: makeAttention({ head_sha: "old-head" }) }),
),
).toBeNull();
expect(
getActiveWorkflowAttention(makePR({ state: "merged", workflow_attention: makeAttention() })),
).toBeNull();
});
it("shows unavailable evidence and preserves a stored positive result during a live read failure", () => {
const unknown = makeAttention({ state: "unknown", runs: [] });
const stored = makeAttention({ stale: false });
const carrier = makePR({ workflow_attention: stored });
expect(getWorkflowAttentionForDisplay(makePR({ workflow_attention: unknown }))).toEqual(
unknown,
);
expect(getWorkflowAttentionForDisplay(carrier, unknown)).toEqual({
...stored,
stale: true,
});
expect(
getWorkflowAttentionForDisplay(carrier, makeAttention({ state: "none", runs: [] })),
).toBeNull();
});
it("does not render an authoritative empty result and normalizes legacy null runs", () => {
expect(
getWorkflowAttentionForDisplay(
makePR({ workflow_attention: makeAttention({ state: "none", runs: [] }) }),
),
).toBeNull();
expect(
getWorkflowAttentionForDisplay(
makePR({ workflow_attention: makeAttention({ state: "unknown", runs: null as never }) }),
),
).toEqual(makeAttention({ state: "unknown", runs: [] }));
});
it("lets a newer stored empty observation clear cached attention", () => {
const cached = makeAttention({ observed_at: EARLIER_OBSERVED_AT });
const storedNone = makeAttention({
state: "none",
runs: [],
observed_at: LATER_OBSERVED_AT,
});
expect(
getWorkflowAttentionForDisplay(makePR({ workflow_attention: storedNone }), cached),
).toBeNull();
});
it("lets newer stored attention reappear when cached feedback is an older clear", () => {
const cached = makeAttention({
state: "none",
runs: [],
observed_at: EARLIER_OBSERVED_AT,
});
const stored = makeAttention({ observed_at: LATER_OBSERVED_AT });
expect(getWorkflowAttentionForDisplay(makePR({ workflow_attention: stored }), cached)).toBe(
stored,
);
});
it("ignores mismatched cached heads when stored evidence is current", () => {
const stored = makeAttention({ observed_at: LATER_OBSERVED_AT });
const cached = makeAttention({ head_sha: "old-head", observed_at: "2026-09-10T12:00:00Z" });
expect(getWorkflowAttentionForDisplay(makePR({ workflow_attention: stored }), cached)).toBe(
stored,
);
});
it("preserves current unknown-read semantics while applying observation recency", () => {
const stored = makeAttention({ observed_at: LATER_OBSERVED_AT });
const olderUnknown = makeAttention({
state: "unknown",
runs: [],
observed_at: EARLIER_OBSERVED_AT,
});
const newerUnknown = makeAttention({
state: "unknown",
runs: [],
observed_at: "2026-09-10T12:00:00Z",
});
expect(
getWorkflowAttentionForDisplay(makePR({ workflow_attention: stored }), olderUnknown),
).toBe(stored);
expect(
getWorkflowAttentionForDisplay(makePR({ workflow_attention: stored }), newerUnknown),
).toEqual({ ...stored, stale: true });
});
});
describe("getCurrentWorkflowAttention", () => {
it("normalizes legacy null run arrays for summary consumers", () => {
const current = getCurrentWorkflowAttention(
makePR({ workflow_attention: makeAttention({ runs: null as never }) }),
);
expect(current?.runs).toEqual([]);
});
});
@@ -0,0 +1,101 @@
import type { TaskPR, WorkflowAttention, WorkflowAttentionState } from "@/lib/types/github";
import { parseStrictRfc3339Timestamp } from "@/lib/utils/strict-timestamp";
type WorkflowAttentionCarrier = {
state: string;
head_sha?: string | null;
workflow_attention?: WorkflowAttention | null;
};
function isAttentionState(state: WorkflowAttentionState): boolean {
return state === "approval_required" || state === "action_required";
}
function currentWorkflowObservation(
carrier: WorkflowAttentionCarrier,
attention: WorkflowAttention | null | undefined,
): WorkflowAttention | null {
if (
carrier.state !== "open" ||
!carrier.head_sha ||
!attention ||
attention.head_sha !== carrier.head_sha
) {
return null;
}
return attention;
}
function normalizeWorkflowAttention(attention: WorkflowAttention | null): WorkflowAttention | null {
if (!attention || attention.state === "none") return null;
if (attention.runs != null) return attention;
return { ...attention, runs: attention.runs ?? [] };
}
export function getCurrentWorkflowAttention(
carrier: WorkflowAttentionCarrier,
): WorkflowAttention | null {
return normalizeWorkflowAttention(
currentWorkflowObservation(carrier, carrier.workflow_attention),
);
}
function suppliedObservationIsAtLeastAsFresh(
stored: WorkflowAttention,
supplied: WorkflowAttention,
): boolean {
const storedTimestamp = parseStrictRfc3339Timestamp(stored.observed_at);
const suppliedTimestamp = parseStrictRfc3339Timestamp(supplied.observed_at);
if (suppliedTimestamp === null) return storedTimestamp === null;
if (storedTimestamp === null) return true;
return suppliedTimestamp >= storedTimestamp;
}
/**
* Chooses the best observation for a surface that has both stored TaskPR data
* and an optional live feedback response. A failed live read must not hide a
* stored same-head positive observation, while an authoritative empty result
* must clear it.
*/
export function getWorkflowAttentionForDisplay(
carrier: WorkflowAttentionCarrier,
suppliedAttention?: WorkflowAttention | null,
): WorkflowAttention | null {
const stored = currentWorkflowObservation(carrier, carrier.workflow_attention);
if (suppliedAttention == null) return normalizeWorkflowAttention(stored);
const incoming = currentWorkflowObservation(carrier, suppliedAttention);
if (!incoming) return normalizeWorkflowAttention(stored);
const useIncoming = stored === null || suppliedObservationIsAtLeastAsFresh(stored, incoming);
const selected = useIncoming ? incoming : stored;
if (useIncoming && incoming.state === "unknown" && stored && isAttentionState(stored.state)) {
return normalizeWorkflowAttention({ ...stored, stale: true });
}
return normalizeWorkflowAttention(selected);
}
export function getActiveWorkflowAttention(
carrier: WorkflowAttentionCarrier,
attention: WorkflowAttention | null | undefined = carrier.workflow_attention,
): WorkflowAttention | null {
const current = normalizeWorkflowAttention(currentWorkflowObservation(carrier, attention));
return current && isAttentionState(current.state) ? current : null;
}
export function getTaskPRWorkflowAttention(pr: TaskPR): WorkflowAttention | null {
return getActiveWorkflowAttention(pr);
}
export function workflowAttentionWorkflowNames(attention: WorkflowAttention): string {
const names = attention.runs.map((run) => run.name.trim()).filter(Boolean);
return names.join(", ");
}
export function isWorkflowApprovalRequired(attention: WorkflowAttention): boolean {
return attention.state === "approval_required";
}
export function workflowAttentionReasonKey(reason: string): string {
return reason === "approval_required"
? "github:workflowApprovalRequired"
: "github:workflowNeedsAttention";
}