mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 21:21:27 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The restart chaos harness (`tests/restart-chaos/`) clicks every
needed Retry in the real board UI with Playwright.
> - In one wave, a task failed and showed Retry. The "You completed 5
tasks!" star modal was open over the page.
> - The modal is a Radix dialog. It sets `aria-hidden="true"` on the
rest of the page, so `getByRole('button', { name: 'Retry' })` did not
find the visible Retry.
> - The grade said `ui_retry_button_missing`. That name hides the real
cause.
> - This pull request makes the harness close a covering modal before it
looks for Retry. When a modal does not close and keeps a visible Retry
unreachable, the grade says `ui_retry_blocked_by_modal`.
> - The benefit is that a chaos grade names the real cause, and a
promotional prompt does not fail a wave.
## Linked Issues or Issue Description
Refs #20713 (product fix: the star prompt no longer opens over a task
that needs Retry)
**What happened?**
A restart chaos wave saved a "Retry missing" screenshot. The screenshot
shows the Retry banner and the star modal over it. The saved DOM shows
the Retry button as visible, with a box, inside the banner. The harness
still graded the task `ui_retry_button_missing`.
**Expected behavior**
The harness closes a modal that covers the page, as a user does, and
then clicks Retry. If a modal does not close, the grade names the modal
as the cause.
**Steps to reproduce**
1. Open a task page that shows a failed attempt with Retry.
2. Open a Radix modal over the page (the star prompt did this).
3. Run `BoardUi.clickRetry` on that task. It reports
`ui_retry_button_missing`.
## What Changed
- `board-ui.ts`: before and while it waits for Retry, `clickRetryOnPage`
closes an open modal that does not itself offer Retry. It clicks "Not
now" (or "No thanks", "Maybe later", "Dismiss") when present, else it
presses Escape. It also closes a modal that opens after Retry appears
and swallows the click, then clicks again. At most three dialogs are
closed. Each click has a timeout equal to the per-button request wait.
- The click result has a new optional `dismissedDialogs` list (first
line of each closed dialog). The observer copies it into the task's
retry attempt.
- New failure reason `ui_retry_blocked_by_modal` (in `types.ts`): a
visible Retry exists in the DOM, it is not reachable by role, and a
modal stays open. R3 in `grader.ts` reports it with the banner text,
like the other UI reasons.
- `README.md`: the board UI Retry paragraph names the dismissal and the
new reason.
- Tests in `board-ui.test.ts` use real Chromium pages with a modal and
an `aria-hidden` page: "Not now" closes it and Retry is clicked; Escape
closes it and Retry is clicked; a modal that opens on hover over Retry
is closed and Retry is clicked; a modal that does not close gives
`ui_retry_blocked_by_modal`. `grader.test.ts` covers the new R3 detail.
## Verification
- Red first: the three new `board-ui.test.ts` cases failed on master
(the covered Retry was reported as missing).
- Green: `cd tests/restart-chaos && npx vitest run board-ui.test.ts
grader.test.ts triggers.test.ts` (with `observer.test.ts`) gives 99
passed.
- `npx tsc --noEmit -p tests/restart-chaos/tsconfig.json` passes.
- `pnpm verify` exits 2 because the README is a global CI input. CI
supplies the broad coverage.
## Risks
- Low risk. This changes only the test harness.
- The harness can close a dialog that the product meant to keep open.
The closed dialog is recorded in `dismissedDialogs`, so the evidence
still shows it.
> 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
- Anthropic Claude Opus 5.5 (`claude-opus-5-5`), in Claude Code with
tool use (shell, file edit, test runs).
## 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 searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude <noreply@anthropic.com>
169 lines
8.9 KiB
TypeScript
169 lines
8.9 KiB
TypeScript
import { mkdir, writeFile } from "node:fs/promises";
|
|
import path from "node:path";
|
|
import { chromium, type Browser, type ElementHandle, type Page } from "@playwright/test";
|
|
import { UI_RETRY_BLOCKED_BY_MODAL, UI_RETRY_BUTTON_MISSING, UI_RETRY_NO_REQUEST } from "./types.js";
|
|
|
|
export { UI_RETRY_BLOCKED_BY_MODAL, UI_RETRY_BUTTON_MISSING, UI_RETRY_NO_REQUEST };
|
|
|
|
export interface UiRetryClick {
|
|
clicked: boolean;
|
|
httpStatus: number | null;
|
|
accepted: boolean | null;
|
|
error: string | null;
|
|
bannerText: string | null;
|
|
diagnostics?: { screenshot: string | null; dom: string | null } | null;
|
|
dismissedDialogs?: string[];
|
|
}
|
|
|
|
export async function saveRetryMissingDiagnostics(page: Page, directory: string, label: string) {
|
|
const stem = path.join(directory, `ui-retry-missing-${label.replace(/[^A-Za-z0-9_-]+/g, "_")}-${Date.now()}`);
|
|
await mkdir(directory, { recursive: true });
|
|
const screenshot = await page.screenshot({ path: `${stem}.png`, fullPage: true, timeout: 10_000 })
|
|
.then(() => `${stem}.png`).catch(() => null);
|
|
const banners = await page.locator("[role=status], [role=alert]")
|
|
.evaluateAll(nodes => nodes.map(node => (node as Element).outerHTML.slice(0, 20_000))).catch(() => []);
|
|
const buttons = [];
|
|
for (const button of await page.getByRole("button", { name: "Retry", exact: true, includeHidden: true })
|
|
.elementHandles().catch(() => [])) {
|
|
buttons.push({
|
|
visible: await button.isVisible().catch(() => null),
|
|
box: await button.boundingBox().catch(() => null),
|
|
inBanner: await button.evaluate(node => Boolean((node as Element).closest("[role=status], [role=alert]"))).catch(() => null),
|
|
html: await button.evaluate(node => (node as Element).outerHTML.slice(0, 2_000)).catch(() => null),
|
|
});
|
|
}
|
|
const dom = await writeFile(`${stem}.json`, JSON.stringify({ url: page.url(), savedAt: new Date().toISOString(),
|
|
banners, retryButtons: buttons }, null, 2)).then(() => `${stem}.json`).catch(() => null);
|
|
return { screenshot, dom };
|
|
}
|
|
|
|
const PER_BUTTON_REQUEST_MS = 5_000;
|
|
const DIALOG_SCAN_MS = 1_000;
|
|
const MAX_DISMISSED_DIALOGS = 3;
|
|
const BLOCKING_DIALOG = '[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"], '
|
|
+ '[aria-modal="true"]:not([data-state="closed"]), dialog[open]';
|
|
const DISMISS_BUTTON = /^(not now|no thanks|maybe later|dismiss)$/i;
|
|
|
|
const blockingDialog = (page: Page) => page.locator(BLOCKING_DIALOG).filter({ visible: true }).first();
|
|
|
|
async function dismissBlockingDialog(page: Page): Promise<string | null> {
|
|
const dialog = blockingDialog(page);
|
|
if (!await dialog.isVisible().catch(() => false)) return null;
|
|
if (await dialog.getByRole("button", { name: "Retry", exact: true }).count().catch(() => 0)) return null;
|
|
const label = (await dialog.innerText().catch(() => "")).trim().split(/\r?\n/)[0]?.slice(0, 120) || "dialog";
|
|
const handle = await dialog.elementHandle().catch(() => null);
|
|
const notNow = dialog.getByRole("button", { name: DISMISS_BUTTON }).filter({ visible: true }).first();
|
|
const clicked = await notNow.count().catch(() => 0) > 0 && await notNow.click({ timeout: 2_000 }).then(() => true, () => false);
|
|
if (!clicked) await page.keyboard.press("Escape").catch(() => undefined);
|
|
const closed = handle
|
|
? await handle.waitForElementState("hidden", { timeout: 2_000 }).then(() => true, () => false)
|
|
: !await blockingDialog(page).isVisible().catch(() => false);
|
|
return closed ? label : null;
|
|
}
|
|
|
|
export function isRetryRequestFor(issueRefs: readonly string[], method: string, url: string): boolean {
|
|
if (method !== "POST") return false;
|
|
const match = /\/api\/issues\/([^/]+)\/retry$/.exec(new URL(url).pathname);
|
|
return Boolean(match && issueRefs.includes(decodeURIComponent(match[1]!)));
|
|
}
|
|
|
|
async function retryButtonsBannerFirst(page: Page): Promise<ElementHandle[]> {
|
|
const candidates: Array<{ button: ElementHandle; inBanner: boolean }> = [];
|
|
for (const button of await page.getByRole("button", { name: "Retry", exact: true }).elementHandles()) {
|
|
if (!await button.isVisible().catch(() => false)) continue;
|
|
const inBanner = await button.evaluate(node => Boolean((node as Element).closest("[role=status], [role=alert]"))).catch(() => false);
|
|
candidates.push({ button, inBanner });
|
|
}
|
|
return [...candidates.filter(candidate => candidate.inBanner), ...candidates.filter(candidate => !candidate.inBanner)].map(candidate => candidate.button);
|
|
}
|
|
|
|
export async function clickRetryOnPage(page: Page, url: string, issueRefs: readonly string[], timeoutMs: number,
|
|
perButtonMs = PER_BUTTON_REQUEST_MS, diagnosticsDirectory: string | null = null): Promise<UiRetryClick> {
|
|
await page.goto(url, { waitUntil: "domcontentloaded", timeout: timeoutMs });
|
|
const banner = async () => {
|
|
const texts = await page.locator("[role=status], [role=alert]").allInnerTexts().catch(() => []);
|
|
return texts.map(text => text.trim()).filter(Boolean).join(" | ").slice(0, 500) || null;
|
|
};
|
|
const reachable = page.getByRole("button", { name: "Retry", exact: true }).filter({ visible: true }).first();
|
|
const dismissedDialogs: string[] = [];
|
|
const dismissed = () => (dismissedDialogs.length ? { dismissedDialogs } : {});
|
|
const dismissDialogs = async () => {
|
|
const before = dismissedDialogs.length;
|
|
while (dismissedDialogs.length < MAX_DISMISSED_DIALOGS) {
|
|
const closed = await dismissBlockingDialog(page);
|
|
if (closed === null) break;
|
|
dismissedDialogs.push(closed);
|
|
}
|
|
return dismissedDialogs.length > before;
|
|
};
|
|
const blockedByModal = async () => await blockingDialog(page).isVisible().catch(() => false)
|
|
&& await page.getByRole("button", { name: "Retry", exact: true, includeHidden: true }).filter({ visible: true }).count().catch(() => 0) > 0;
|
|
const deadline = Date.now() + timeoutMs;
|
|
for (;;) {
|
|
await dismissDialogs();
|
|
const remaining = deadline - Date.now();
|
|
if (remaining <= 0) break;
|
|
if (await reachable.waitFor({ state: "visible", timeout: Math.min(remaining, DIALOG_SCAN_MS) }).then(() => true, () => false)) break;
|
|
}
|
|
if (!await reachable.isVisible().catch(() => false)) {
|
|
const bannerText = await banner();
|
|
const diagnostics = diagnosticsDirectory
|
|
? await saveRetryMissingDiagnostics(page, diagnosticsDirectory, issueRefs[0] ?? "issue").catch(() => null) : undefined;
|
|
const blocked = await blockedByModal();
|
|
return { clicked: false, httpStatus: null, accepted: null, error: blocked ? UI_RETRY_BLOCKED_BY_MODAL : UI_RETRY_BUTTON_MISSING, bannerText,
|
|
...(diagnostics !== undefined ? { diagnostics } : {}), ...dismissed() };
|
|
}
|
|
const bannerText = await banner();
|
|
for (const button of await retryButtonsBannerFirst(page)) {
|
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
await dismissDialogs();
|
|
const response = page.waitForResponse(candidate => isRetryRequestFor(issueRefs, candidate.request().method(), candidate.url()),
|
|
{ timeout: perButtonMs }).catch(() => null);
|
|
await button.click({ timeout: perButtonMs }).catch(() => undefined);
|
|
const answered = await response;
|
|
if (answered) {
|
|
const body = await answered.json().catch(() => null) as { accepted?: unknown } | null;
|
|
return { clicked: true, httpStatus: answered.status(), accepted: answered.ok() ? body?.accepted === true : false,
|
|
error: answered.ok() ? null : `retry request failed with ${answered.status()}`, bannerText, ...dismissed() };
|
|
}
|
|
if (!await dismissDialogs()) break;
|
|
}
|
|
}
|
|
if (await blockedByModal()) {
|
|
return { clicked: false, httpStatus: null, accepted: null, error: UI_RETRY_BLOCKED_BY_MODAL, bannerText, ...dismissed() };
|
|
}
|
|
return { clicked: true, httpStatus: null, accepted: null, error: UI_RETRY_NO_REQUEST, bannerText, ...dismissed() };
|
|
}
|
|
|
|
export class BoardUi {
|
|
private browser: Promise<Browser> | null = null;
|
|
|
|
constructor(private readonly baseUrl: string, private readonly launch: () => Promise<Browser> = () => chromium.launch({ headless: true }),
|
|
private readonly diagnosticsDirectory: string | null = null) {}
|
|
|
|
async clickRetry(identifier: string, issueId: string = identifier, timeoutMs = 60_000, perButtonMs = PER_BUTTON_REQUEST_MS): Promise<UiRetryClick> {
|
|
let context: Awaited<ReturnType<Browser["newContext"]>> | null = null;
|
|
try {
|
|
this.browser ??= this.launch();
|
|
context = await (await this.browser).newContext({ viewport: { width: 1440, height: 1000 } });
|
|
return await clickRetryOnPage(await context.newPage(), `${this.baseUrl}/issues/${encodeURIComponent(identifier)}`,
|
|
[identifier, issueId], timeoutMs, perButtonMs, this.diagnosticsDirectory);
|
|
} catch (error) {
|
|
return { clicked: false, httpStatus: null, accepted: null, error: error instanceof Error ? error.message : String(error), bannerText: null };
|
|
} finally {
|
|
await context?.close().catch(() => undefined);
|
|
}
|
|
}
|
|
|
|
async close(): Promise<void> {
|
|
const browser = this.browser;
|
|
this.browser = null;
|
|
if (!browser) return;
|
|
try {
|
|
await (await browser).close();
|
|
} catch {
|
|
return;
|
|
}
|
|
}
|
|
}
|