import type { IssueBlockerAttention, IssueRecoveryAction, IssueRelationIssueSummary, IssueScheduledRetry, SuccessfulRunHandoffState, } from "@paperclipai/shared"; import type { ReactNode } from "react"; import { AlertTriangle, CheckCircle2, Circle, Flag, Loader2, RotateCcw } from "lucide-react"; import { Link } from "@/lib/router"; import { cn } from "../lib/utils"; import { Button } from "@/components/ui/button"; import { createIssueDetailPath } from "../lib/issueDetailBreadcrumb"; import { formatMonitorOffset } from "../lib/issue-monitor"; import { useRetryNowMutation } from "../hooks/useRetryNowMutation"; import { IssueLinkQuicklook } from "./IssueLinkQuicklook"; import { LockedIssueChip, isLockedIssueStub } from "./LockedIssueChip"; import { RetryErrorBand } from "./IssueScheduledRetryCard"; import { isAssignedBacklogBlocker, orderWaitingBlockers, type WaitingBlockerStatus, } from "../lib/issue-blockers"; import { isSuccessfulRunHandoffRequired } from "../lib/successful-run-handoff"; import { Badge } from "@/components/ui/badge"; import { deriveActiveRecoveryDisplayState, RECOVERY_CHIP_DEFAULT_TONE, recoveryChipLabel, } from "../lib/recovery-display"; import { formatRecoveryLineageSummary, readRecoveryRetryLineage, } from "../lib/recovery-lineage"; import { StatusGlyph } from "./StatusGlyph"; function BlockerRecoveryIndicator({ action, scheduledRetry, }: { action: IssueRecoveryAction; /** The blocker's own scheduled retry, used to verify that the stored attempt is in flight. */ scheduledRetry?: IssueScheduledRetry | null; }) { const liveness = { scheduledRetry: scheduledRetry ?? null }; const state = deriveActiveRecoveryDisplayState(action, liveness); if (!state) return null; const tone = RECOVERY_CHIP_DEFAULT_TONE[state]; const Icon = tone.icon; // The blocker chip reads the same stored lineage as the source task's recovery card, so // a parent view never contradicts the task it is waiting on. const lineage = readRecoveryRetryLineage(action, liveness); const label = recoveryChipLabel(state, action.kind, lineage); const detail = lineage ? formatRecoveryLineageSummary(lineage) : null; return ( svg]:size-2.5 gap-0.5 px-1.5 text-(length:--text-nano) ${tone.className}`} > {label} ); } function SuccessfulRunRetryNowControl({ issueId, scheduledRetry, }: { issueId: string; scheduledRetry: IssueScheduledRetry; }) { const retryNow = useRetryNowMutation(issueId); const dueAtIso = scheduledRetry.scheduledRetryAt ? new Date(scheduledRetry.scheduledRetryAt).toISOString() : null; const relative = dueAtIso ? formatMonitorOffset(dueAtIso) : null; const scheduleLabel = relative === "now" ? "due now" : relative ? `scheduled ${relative}` : "scheduled"; const success = retryNow.isSuccess && (retryNow.data?.outcome === "promoted" || retryNow.data?.outcome === "already_promoted"); return (
{retryNow.data?.outcome === "waiting" && retryNow.data.scheduledRetry?.runId === scheduledRetry.runId ? retryNow.data.message : <>Paperclip will ask the assignee to choose the next step {scheduleLabel}. Retry now starts that follow-up immediately.}
{ retryNow.reset(); retryNow.mutate(); }} />
); } const EMPTY_LIVE_IDS: ReadonlySet = new Set(); function waitingTaskStatusLabel(status: string): string { return status.replace(/_/g, " ").replace(/\b\w/g, (character) => character.toUpperCase()); } function WaitingChipLink({ blocker, running = false, }: { blocker: IssueRelationIssueSummary; running?: boolean; }) { const issuePathId = blocker.identifier ?? blocker.id; return ( {blocker.identifier ?? blocker.id.slice(0, 8)} {blocker.title} {running ? ( running ) : null} ); } function WaitingStepGlyph({ status }: { status: WaitingBlockerStatus }) { if (status === "done") { return ; } if (status === "running") { return ( ); } return ; } /** * Calm in-flight counterpart to the amber "still needs a next step" alarm. * The handoff is still `required`, but a correction run is live on the issue, * so the alarm would be crying wolf while an agent is already working. Saying * it quietly beats saying nothing: the reader still learns a disposition is * outstanding, and learns that the alarm comes back if the run ends without * choosing one. */ function SuccessfulRunHandoffInFlightNotice({ liveRunId, assigneeAgentId, }: { liveRunId?: string | null; assigneeAgentId?: string | null; }) { const shortRunId = liveRunId ? liveRunId.slice(0, 8) : null; return (

A correction run is in progress — the agent is working. This alert returns if the run stops without choosing a next step. {shortRunId ? ( <> {" "} {assigneeAgentId ? ( run {shortRunId} ) : ( run {shortRunId} )} ) : null}

); } /** * Blue "Waiting on live work" variant — rendered in place of the * amber notice when `blockerAttention.state === "covered"`: the blocker chain * is a healthy plan executing in order and something in it is live. */ function WaitingOnLiveWorkNotice({ blockerAttentionState, chainBlockers, terminalBlockers, liveIds, parkedBlockers, renderParkedChip, }: { blockerAttentionState?: string; chainBlockers: IssueRelationIssueSummary[]; terminalBlockers: IssueRelationIssueSummary[]; liveIds: ReadonlySet; parkedBlockers: IssueRelationIssueSummary[]; renderParkedChip: (blocker: IssueRelationIssueSummary) => ReactNode; }) { const steps = orderWaitingBlockers(chainBlockers, liveIds); const total = steps.length; const doneCount = steps.filter((step) => step.status === "done").length; const runningCount = steps.filter((step) => step.status === "running").length; // "Now running" replaces "Ultimately waiting on": prefer live terminal // leaves that are not already shown in the ordered queue list. const stepIds = new Set(steps.map((step) => step.blocker.id)); const nowRunningSeen = new Set(); const nowRunning: IssueRelationIssueSummary[] = []; for (const blocker of [...terminalBlockers, ...chainBlockers]) { if (!liveIds.has(blocker.id)) continue; if (stepIds.has(blocker.id)) continue; if (nowRunningSeen.has(blocker.id)) continue; nowRunningSeen.add(blocker.id); nowRunning.push(blocker); } const queuedNoun = total === 1 ? "task" : "tasks"; return (

Waiting on live work

Queued behind {total} {queuedNoun} being worked in order. This task resumes automatically when the chain is done. Comments still notify the assignee.

{doneCount} of {total} done {runningCount > 0 ? ` · ${runningCount} running` : null}
{steps.map(({ blocker, status }) => ( ))}
{steps.map(({ blocker, status }) => (
))}
This task — resumes automatically when the chain is done
{nowRunning.length > 0 ? (
Now running
{nowRunning.map((blocker) => ( ))}
) : null} {parkedBlockers.length > 0 ? (
Blocked by parked work {parkedBlockers.map((blocker) => renderParkedChip(blocker))}
) : null}
); } export function IssueBlockedNotice({ issueId, issueStatus, blockers, allBlockers, liveIssueIds, blockerAttention, successfulRunHandoff, scheduledRetry, agentName, }: { issueId?: string | null; issueStatus?: string; /** Unresolved blockers (drives the amber notice; unchanged). */ blockers: IssueRelationIssueSummary[]; /** * Full blocker list (resolved + unresolved). Used by the blue "Waiting on * live work" variant to render done steps and progress counts. Falls back to * {@link blockers} when not supplied. */ allBlockers?: IssueRelationIssueSummary[]; /** Company-wide set of issue ids with a queued/running run (own or blocker). */ liveIssueIds?: ReadonlySet; blockerAttention?: IssueBlockerAttention | null; successfulRunHandoff?: SuccessfulRunHandoffState | null; scheduledRetry?: IssueScheduledRetry | null; agentName?: string | null; }) { if (issueStatus === "done" || issueStatus === "cancelled") return null; // A live run on this issue means an agent is already handling it — the // missing-disposition complaint only applies when the issue is stuck. // `hasLiveContinuation` is the server's view; `liveIssueIds` catches runs // that started after the issue payload was fetched. const issueHasLiveRun = Boolean(issueId && liveIssueIds?.has(issueId)); const showSuccessfulRunHandoff = successfulRunHandoff != null && isSuccessfulRunHandoffRequired({ successfulRunHandoff, scheduledRetry }) && !issueHasLiveRun; // Outstanding handoff + a live run on the issue: the alarm is suppressed, so // render the quiet in-flight line in its place rather than nothing at all. // The unpromoted-scheduled-retry carve-out keeps `showSuccessfulRunHandoff` // true, so the amber notice (and its "Retry now" control) still wins there. // This stands in for the handoff alarm only. When the issue also has // blockers, the blocker notice below is the stronger signal and owns the // slot, exactly as it did before this line existed. const handoffInFlightNotice = successfulRunHandoff != null && successfulRunHandoff.required === true && !showSuccessfulRunHandoff && (successfulRunHandoff.hasLiveContinuation || issueHasLiveRun) ? ( ) : null; if (!showSuccessfulRunHandoff && blockers.length === 0 && issueStatus !== "blocked") { return handoffInFlightNotice; } const successfulRunRetryNow = showSuccessfulRunHandoff && issueId && scheduledRetry?.status === "scheduled_retry" ? { issueId, scheduledRetry } : null; const blockerLabel = blockers.length === 1 ? "the linked task" : "the linked tasks"; const terminalBlockers = blockers .flatMap((blocker) => blocker.terminalBlockers ?? []) .filter((blocker, index, all) => all.findIndex((candidate) => candidate.id === blocker.id) === index); const isStalled = blockerAttention?.state === "stalled"; const parkedBlockers = (() => { const seen = new Set(); const collected: IssueRelationIssueSummary[] = []; const sources: IssueRelationIssueSummary[] = [...blockers]; for (const blocker of blockers) { for (const terminal of blocker.terminalBlockers ?? []) { sources.push(terminal); } } for (const blocker of sources) { if (!isAssignedBacklogBlocker(blocker)) continue; if (seen.has(blocker.id)) continue; seen.add(blocker.id); collected.push(blocker); } return collected; })(); const showParkedRow = parkedBlockers.length > 0; const stalledLeafIdentifier = blockerAttention?.sampleStalledBlockerIdentifier ?? blockerAttention?.sampleBlockerIdentifier ?? null; const stalledLeafBlockers = (() => { const candidates: IssueRelationIssueSummary[] = []; for (const blocker of [...blockers, ...terminalBlockers]) { if (blocker.status !== "in_review") continue; if (candidates.some((existing) => existing.id === blocker.id)) continue; candidates.push(blocker); } if (stalledLeafIdentifier) { const preferred = candidates.find( (blocker) => (blocker.identifier ?? blocker.id) === stalledLeafIdentifier, ); if (preferred) { return [preferred, ...candidates.filter((blocker) => blocker.id !== preferred.id)]; } } return candidates; })(); const showStalledRow = isStalled && stalledLeafBlockers.length > 0; // Rule C (PAP-13554 / plan §Rule C): when the issue is `blocked` and a // blocker edge is genuinely not done, a human comment does NOT reopen it — // the reopen gate keeps it blocked. `blockers` here is the *unresolved* set // (status ≠ done/cancelled), so a non-empty list on a `blocked` issue is // exactly the case the human's message can't move to todo. Done-but-pending- // finalize blockers are `done`, so they fall out of this set and into the // Rule B reopen path — we must not claim "a message won't reopen" for those. // Name the deepest unresolved leaf (prefer terminal leaves) with its status // so "I sent a message and nothing happened" can't recur silently. const responsibleName = agentName ?? "the assignee"; const reopenSuppressed = issueStatus === "blocked" && !isStalled && blockers.length > 0; const unresolvedLeafBlockers = (() => { if (!reopenSuppressed) return [] as IssueRelationIssueSummary[]; const seen = new Set(); const collected: IssueRelationIssueSummary[] = []; for (const blocker of blockers) { const terminals = (blocker.terminalBlockers ?? []).filter( (leaf) => leaf.status !== "done" && leaf.status !== "cancelled", ); const leaves = terminals.length > 0 ? terminals : [blocker]; for (const leaf of leaves) { if (seen.has(leaf.id)) continue; seen.add(leaf.id); collected.push(leaf); } } return collected; })(); const reopenSuppressedLeaf = unresolvedLeafBlockers[0] ?? null; const reopenSuppressedLeafId = reopenSuppressedLeaf ? reopenSuppressedLeaf.identifier ?? reopenSuppressedLeaf.id.slice(0, 8) : null; const reopenSuppressedLeafStatus = reopenSuppressedLeaf ? isLockedIssueStub(reopenSuppressedLeaf) ? "unavailable" : reopenSuppressedLeaf.status.replace(/_/g, " ") : null; const reopenSuppressedOtherCount = Math.max(unresolvedLeafBlockers.length - 1, 0); const renderBlockerChip = (blocker: IssueRelationIssueSummary) => { // A private blocker arrives as a locked stub (no title/status). Show the // locked chip plus the access note instead of a link into a 404. if (isLockedIssueStub(blocker)) { return ( Private — you don't have access ); } const issuePathId = blocker.identifier ?? blocker.id; const recoveryAction = blocker.activeRecoveryAction ?? null; return ( {blocker.identifier ?? blocker.id.slice(0, 8)} {blocker.title} {recoveryAction ? ( ) : null} ); }; // Blue "Waiting on live work" variant: the blocker chain is a healthy plan // executing in order and something in it is live. `covered` is // the only state that goes blue — stalled / needs_attention / none keep the // amber notice byte-for-byte. The successful-run handoff notice is about this // task's own finished run, so it always keeps its amber priority styling. const liveIds = liveIssueIds ?? EMPTY_LIVE_IDS; const chainBlockers = allBlockers ?? blockers; const hasLiveWaitingBlocker = [...chainBlockers, ...terminalBlockers].some((blocker) => ( liveIds.has(blocker.id) )); const waitingOnLiveWork = !showSuccessfulRunHandoff && blockerAttention?.state === "covered" && chainBlockers.length > 0 && hasLiveWaitingBlocker; if (waitingOnLiveWork) { return ( ); } return (
{showSuccessfulRunHandoff ? ( <>

This task still needs a next step.

A run finished successfully, but the task is still open. Paperclip needs someone to choose what happens next.

  • Mark it done or cancelled.
  • Send it for review or ask for input.
  • Record what is blocking it and who owns that blocker.
  • Delegate follow-up work or queue a continuation.
{successfulRunHandoff.sourceRunId && successfulRunHandoff.assigneeAgentId ? ( run {successfulRunHandoff.sourceRunId.slice(0, 8)} ) : successfulRunHandoff.sourceRunId ? ( run {successfulRunHandoff.sourceRunId.slice(0, 8)} ) : null} Asked {agentName ?? "the assignee"} to choose the next step
{successfulRunHandoff.detectedProgressSummary ? (

Detected progress: {successfulRunHandoff.detectedProgressSummary}

) : null} {successfulRunRetryNow ? ( ) : null} ) : null} {showSuccessfulRunHandoff && (blockers.length > 0 || issueStatus === "blocked") ? (
) : null} {blockers.length > 0 || issueStatus === "blocked" ? ( <>

{blockers.length > 0 ? isStalled ? stalledLeafBlockers.length > 1 ? <>Work on this task is blocked by {blockerLabel}, but the chain is stalled in review without a clear next step. Resolve the stalled reviews below or remove them as blockers. : <>Work on this task is blocked by {blockerLabel}, but the chain is stalled in review without a clear next step. Resolve the stalled review below or remove it as a blocker. : reopenSuppressed ? <>A message won’t restart this task yet — it stays blocked by {blockerLabel} until {blockers.length === 1 ? "it is" : "they are"} done, then it reopens automatically. Comments still notify {responsibleName} for questions or triage in the meantime. : <>Work on this task is blocked by {blockerLabel} until {blockers.length === 1 ? "it is" : "they are"} complete. Comments still notify the assignee for questions or triage. : <>Work on this task is blocked until someone moves it back to To do. Comments still notify the assignee for questions or triage.}

{reopenSuppressed && reopenSuppressedLeafId ? (

Still blocked by{" "} {reopenSuppressedLeafId} {reopenSuppressedLeafStatus ? <> ({reopenSuppressedLeafStatus}) : null} {reopenSuppressedOtherCount > 0 ? ` and ${reopenSuppressedOtherCount} other ${ reopenSuppressedOtherCount === 1 ? "task" : "tasks" }` : null} .

) : null} {blockers.length > 0 ? (
{blockers.map(renderBlockerChip)}
) : null} {showStalledRow ? (
Stalled in review {stalledLeafBlockers.map(renderBlockerChip)}
) : terminalBlockers.length > 0 ? (
Ultimately waiting on {terminalBlockers.map(renderBlockerChip)}
) : null} {showParkedRow ? (
Blocked by parked work {parkedBlockers.map(renderBlockerChip)}
) : null} ) : null}
); }