paperclip/ui/src/components/BlockedInboxView.test.tsx
Dotta 4142559c37
[codex] Add blocked inbox attention view (#5603)
## Thinking Path

> - Paperclip orchestrates AI agents for zero-human companies through
company-scoped issues, comments, approvals, and execution workspaces.
> - Operators need the Inbox to show not only active work, but also
blocked work that may need human or agent attention.
> - The existing inbox experience did not have a dedicated blocked-work
surface, so blocked tasks were harder to triage and resume deliberately.
> - Backend consumers also needed a compact attention signal that
distinguishes actionable blockers from covered or waiting blocker
states.
> - This pull request adds a Blocked Inbox tab backed by issue
blocker-attention metadata, shared validators, and UI helpers.
> - The benefit is a clearer triage path for stalled or blocked
Paperclip work without exposing external wait internals in the
operator-facing UI.

## What Changed

- Added shared issue blocker-attention types, validators, and exports
for the API/UI contract.
- Added backend blocker-attention computation and issue route support
for blocked inbox data.
- Added the Blocked Inbox tab, blocked reason chips, filtering/search
UI, responsive layouts, and Storybook stories.
- Updated inbox helpers and page behavior so toolbar controls only
appear where they apply.
- Added coverage for shared validators, server blocker-attention
behavior, blocked inbox UI helpers/components, and the Inbox page.
- Added a screenshot helper script for the blocked inbox Storybook
stories.
- Addressed Greptile feedback by making urgency sorting deterministic
for null stop times, avoiding full blocked-inbox list enrichment for
counts, and hardening the screenshot helper.

## Verification

- Rebased the branch cleanly onto `public-gh/master`.
- Confirmed the diff does not include `pnpm-lock.yaml`.
- Confirmed the diff does not include database migration files.
- Ran `pnpm exec vitest run packages/shared/src/validators/issue.test.ts
server/src/__tests__/issue-blocker-attention.test.ts
ui/src/components/BlockedInboxView.test.tsx
ui/src/components/BlockedReasonChip.test.tsx
ui/src/lib/blockedInbox.test.ts ui/src/lib/inbox.test.ts
ui/src/pages/Inbox.test.tsx`.
- Ran `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck`.
- Checked `ROADMAP.md`; this is scoped inbox/operator triage work and
does not duplicate a listed roadmap feature.
- Greptile Review is green on the latest head and all four Greptile
review threads are resolved.
- GitHub PR checks are green on the latest head: policy, security/snyk,
e2e, verify, Canary Dry Run, Greptile Review, and serialized server
suites 1/4 through 4/4.

## Risks

- Medium review surface because this touches the shared issue contract,
server issue services, and the Inbox UI together.
- Blocker-attention classification may need product tuning after
operators use it on real blocked queues.
- UI screenshots were not attached in this PR-opening pass; the branch
includes `scripts/screenshot-blocked-inbox.mjs` and Storybook stories
for visual capture.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

OpenAI Codex, GPT-5-based coding agent with shell, git, GitHub CLI,
GitHub connector, and Paperclip API tool use. Reasoning mode: medium.
Context window: not exposed by the runtime.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-05-13 16:41:36 -05:00

329 lines
9.9 KiB
TypeScript

// @vitest-environment jsdom
import { act } from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Issue, IssueBlockedInboxAttention } from "@paperclipai/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mockIssuesApi = vi.hoisted(() => ({
list: vi.fn(),
count: vi.fn(),
}));
vi.mock("../api/issues", () => ({
issuesApi: mockIssuesApi,
}));
vi.mock("@/lib/router", () => ({
Link: ({
children,
className,
disableIssueQuicklook: _disableIssueQuicklook,
issuePrefetch: _issuePrefetch,
...props
}: React.ComponentProps<"a"> & { disableIssueQuicklook?: boolean; issuePrefetch?: Issue | null }) => (
<a className={className} {...props}>
{children}
</a>
),
}));
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
import { BlockedInboxView } from "./BlockedInboxView";
import { defaultIssueFilterState } from "../lib/issue-filters";
function attention(
overrides: Partial<IssueBlockedInboxAttention> = {},
): IssueBlockedInboxAttention {
return {
kind: "blocked",
state: "needs_attention",
reason: "blocked_chain_stalled",
severity: "medium",
stoppedSinceAt: "2026-05-08T10:00:00.000Z",
owner: { type: "agent", agentId: "agent-1", userId: null, label: null },
action: { label: "Resolve PAP-77", detail: null },
sourceIssue: null,
leafIssue: null,
recoveryIssue: null,
approvalId: null,
interactionId: null,
sampleIssueIdentifier: null,
redaction: { externalDetailsRedacted: false, secretFieldsOmitted: true },
...overrides,
};
}
function makeIssue(
id: string,
identifier: string,
title: string,
attentionPayload: IssueBlockedInboxAttention,
): Issue {
return {
id,
companyId: "company-1",
projectId: null,
projectWorkspaceId: null,
goalId: null,
parentId: null,
title,
description: null,
status: "in_progress",
workMode: "standard",
priority: "medium",
assigneeAgentId: "agent-1",
assigneeUserId: null,
checkoutRunId: null,
executionRunId: null,
executionAgentNameKey: null,
executionLockedAt: null,
createdByAgentId: null,
createdByUserId: null,
issueNumber: 1,
identifier,
requestDepth: 0,
billingCode: null,
assigneeAdapterOverrides: null,
executionWorkspaceId: null,
executionWorkspacePreference: null,
executionWorkspaceSettings: null,
startedAt: null,
completedAt: null,
cancelledAt: null,
hiddenAt: null,
blockedInboxAttention: attentionPayload,
createdAt: new Date("2026-05-09T00:00:00.000Z"),
updatedAt: new Date("2026-05-09T00:00:00.000Z"),
} as Issue;
}
function renderWithClient(node: React.ReactNode, container: HTMLDivElement) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, staleTime: 0, gcTime: 0 } },
});
const root = createRoot(container);
act(() => {
root.render(<QueryClientProvider client={queryClient}>{node}</QueryClientProvider>);
});
return { root, queryClient };
}
const blockedViewProps = {
companyId: "company-1",
searchQuery: "",
agentNameById: new Map<string, string>(),
issueLinkState: null,
groupBy: "none" as const,
sortBy: "most_recent" as const,
issueFilters: defaultIssueFilterState,
currentUserId: "local-board",
liveIssueIds: new Set<string>(),
workspaceFilterContext: {},
showStatusColumn: true,
showIdentifierColumn: true,
showUpdatedColumn: true,
};
async function waitFor(predicate: () => boolean, attempts = 30): Promise<void> {
for (let i = 0; i < attempts; i += 1) {
if (predicate()) return;
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 5));
});
}
throw new Error("waitFor predicate did not become true");
}
describe("BlockedInboxView", () => {
let container: HTMLDivElement;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
mockIssuesApi.list.mockReset();
});
afterEach(() => {
container.remove();
});
it("shows the empty state when no blocked issues are returned", async () => {
mockIssuesApi.list.mockResolvedValue([]);
const { root } = renderWithClient(
<BlockedInboxView
{...blockedViewProps}
/>,
container,
);
await waitFor(() => container.querySelector('[data-testid="blocked-inbox-empty"]') !== null);
expect(container.querySelector('[data-testid="blocked-inbox-empty"]')).not.toBeNull();
act(() => root.unmount());
});
it("defaults to no grouping and orders rows by most recent stopped item first", async () => {
const issues: Issue[] = [
makeIssue(
"issue-low",
"PAP-1",
"External wait row",
attention({ reason: "external_owner_action", severity: "low" }),
),
makeIssue(
"issue-stalled-high",
"PAP-2",
"Stalled chain row",
attention({
reason: "blocked_chain_stalled",
severity: "high",
stoppedSinceAt: "2026-05-09T01:00:00.000Z",
action: { label: "Resolve PAP-9", detail: null },
}),
),
makeIssue(
"issue-stalled-critical",
"PAP-3",
"Critical stalled row",
attention({
reason: "blocked_chain_stalled",
severity: "critical",
stoppedSinceAt: "2026-05-09T05:00:00.000Z",
action: { label: "Resolve PAP-10", detail: null },
}),
),
makeIssue(
"issue-decision",
"PAP-4",
"Pending board decision",
attention({
reason: "pending_board_decision",
severity: "medium",
owner: { type: "board", agentId: null, userId: null, label: "Board" },
action: { label: "Accept or reject", detail: null },
}),
),
];
mockIssuesApi.list.mockResolvedValue(issues);
const { root } = renderWithClient(
<BlockedInboxView
{...blockedViewProps}
agentNameById={new Map([["agent-1", "ClaudeCoder"]])}
/>,
container,
);
await waitFor(() => container.querySelectorAll("a").length === 4);
expect(container.querySelectorAll('[data-testid^="blocked-inbox-group-"]')).toHaveLength(0);
const titles = Array.from(container.querySelectorAll("a")).map((a) => a.textContent ?? "");
expect(titles[0]).toContain("Critical stalled row");
expect(titles[1]).toContain("Stalled chain row");
expect(mockIssuesApi.list).toHaveBeenCalledWith("company-1", expect.objectContaining({
attention: "blocked",
includeBlockedInboxAttention: true,
includeBlockedBy: true,
}));
act(() => root.unmount());
});
it("places blocker reason chips with the title before owner and timestamp metadata", async () => {
mockIssuesApi.list.mockResolvedValue([
makeIssue(
"issue-decision",
"PAP-4",
"Pending board decision",
attention({
reason: "pending_board_decision",
severity: "medium",
owner: { type: "board", agentId: null, userId: null, label: "Board" },
action: { label: "Accept or reject", detail: null },
}),
),
]);
const { root } = renderWithClient(
<BlockedInboxView
{...blockedViewProps}
/>,
container,
);
await waitFor(() => container.querySelector("a") !== null);
const rowText = container.querySelector("a")?.textContent ?? "";
expect(rowText.indexOf("Pending board decision")).toBeGreaterThanOrEqual(0);
expect(rowText.indexOf("Needs decision")).toBeGreaterThan(rowText.indexOf("Pending board decision"));
expect(rowText.indexOf("Board")).toBeGreaterThan(rowText.indexOf("Needs decision"));
expect(rowText).not.toContain("Accept or reject");
expect(container.querySelector('[data-testid="blocked-row-reason-column"]')?.textContent).toContain("Needs decision");
act(() => root.unmount());
});
it("filters rows by search query against title, identifier, owner and action", async () => {
const issues: Issue[] = [
makeIssue(
"issue-1",
"PAP-77",
"Resume parked work",
attention({
reason: "blocked_by_assigned_backlog_issue",
owner: { type: "agent", agentId: null, userId: null, label: "Charlie" },
action: { label: "Resume parked blocker", detail: null },
}),
),
makeIssue(
"issue-2",
"PAP-99",
"Other unrelated thing",
attention({
reason: "external_owner_action",
owner: { type: "external", agentId: null, userId: null, label: "Vendor" },
action: { label: "Awaiting Vendor", detail: null },
}),
),
];
mockIssuesApi.list.mockResolvedValue(issues);
const { root } = renderWithClient(
<BlockedInboxView
{...blockedViewProps}
searchQuery="charlie"
/>,
container,
);
await waitFor(() => container.querySelectorAll("a").length > 0);
const links = container.querySelectorAll("a");
const titles = Array.from(links).map((a) => a.textContent ?? "");
expect(titles.some((t) => t.includes("Resume parked work"))).toBe(true);
expect(titles.some((t) => t.includes("Other unrelated thing"))).toBe(false);
act(() => root.unmount());
});
it("renders the visible error banner with retry when the query fails", async () => {
mockIssuesApi.list.mockRejectedValue(new Error("network down"));
const { root } = renderWithClient(
<BlockedInboxView
{...blockedViewProps}
/>,
container,
);
await waitFor(() =>
container.querySelector('[data-testid="blocked-inbox-error"]') !== null,
);
const banner = container.querySelector('[data-testid="blocked-inbox-error"]');
expect(banner).not.toBeNull();
expect(banner?.getAttribute("role")).toBe("alert");
expect(banner?.textContent).toContain("Couldn't load the Blocked tab");
act(() => root.unmount());
});
});