Files
PaperClipAI/tests/e2e/board-attachment-receipts.spec.ts
T
Devin FoleyandPaperclip 158613ef81 Permit idle sleep with proved passive remote workspaces (#23335)
## Thinking Path

> - Paperclip runs agent work and retains its files after a run ends.
> - Remote workspaces save those files in a durable archive.
> - The idle inventory still treats every remote workspace row as active
work.
> - A saved archive or an unused setup reservation can then keep an idle
instance awake.
> - This PR adds a read-only proof in the remote workspace owner and
uses it in the existing idle check.
> - The proof keeps active work and uncertain recovery awake and
preserves all retained data.

## Linked Issues or Issue Description

**What happened?**

A retained `cloud_sandbox` workspace blocks idle sleep after its archive
commits and its allocation is released. The passive workspace check only
accepts local directories and git worktrees. An unused reservation can
also remain after a bootstrap failure that started no provider work.

**Expected behavior**

An idle instance can sleep when existing receipts prove that its remote
files are saved or that a setup reservation was never used. Missing,
foreign, contradictory, and unfinished state must keep blocking sleep.

**Steps to reproduce**

1. Save a remote workspace and finish its snapshot operation.
2. Release its allocation with the matching stop receipt, or retain no
allocation.
3. Keep the workspace row and inspect idle safety. Before this change,
the row still reports work.

Related: remote workspace storage in #18403. No duplicate open
sleep/workspace PR was found.

## What Changed

- Add a pure SQL proof for a committed, scoped archive and its completed
source operation. Require the stored encryption scheme and correctly
shaped IV, tag, and ciphertext. An unchanged save can reuse an older
snapshot.
- Require exact release evidence for a retained location and every
allocation of an unused reservation. Unused reservations require an
ended legacy bootstrap, an explicit no-provider-work result, no live
controller or retry, and no native finalization. A pristine reservation
cannot carry retained recovery-file references.
- Apply that proof through the existing passive workspace check. Keep
runtime configuration, commands, due cleanup, reopen fences, and every
independent run, lease, and recovery check.
- Add PostgreSQL regression cases and describe the proof in the
idle-safety documentation. The existing shared database fixture keeps
the tests in one suite instead of adding another database startup.
- Correct two pre-existing receipt browser assertions uncovered by
required CI. Plain comments have supported keyed retries since October
28; the older tests assumed one POST even when receipt reads lose the
race to backoff. Assert exact request identity and payload across
retries, one saved comment, and preservation of the next draft.

## Verification

- Receipt CI follow-up, Node 25.6.1 on macOS: the full
`board-attachment-receipts.spec.ts` passed twice with four Chromium
workers (28/28). Both corrected cases passed with delayed issue reads
after reproducing both old failures under the same delay. `node
scripts/typecheck-test-projects.mjs --reuse-declarations tests/e2e` and
the focused test-budget check passed. Only browser assertions changed
after the 323-test server verification.
- Node 25.6.1 on macOS: `pnpm --filter @paperclipai/server typecheck`
passed.
- Final revision: `pnpm exec vitest run
server/src/__tests__/idle-sleep-safety.test.ts
server/src/__tests__/idle-sleep-diagnostics.test.ts`: 323 passed. Both
suites used real embedded PostgreSQL. An earlier run also selected the
remote-workspace lifecycle suite; its 16 cases were skipped because its
external test database was not configured.
- Red-green: the new saved-workspace regression failed before the first
proof. Both unused-reservation cases failed before that proof was added.
The focused regressions passed after the changes. Empty key material and
a foreign allocation bound to an unused writer were also reproduced
red-green during review.
- `pnpm verify --explain` returned the documented exit 2 because the
documentation path requires broader CI. Required CI will supply that
coverage; a full local repository run was not substituted.
- After rebasing onto current `master`, the focused passive-state tests
and server typecheck passed again.
- `git diff --check` and a staged secret/PII scan passed.
- The previous revision (`078e60f`) received Greptile 5/5 with its
key-format thread resolved. [Initial
CI](https://github.com/paperclipai/paperclip/actions/runs/46536659729)
failed in a Rust executable fixture (`ExecutableFileBusy`) and a browser
receipt assertion. The targeted rerun passed Rust but failed the
companion receipt test. Both browser assertions expected one POST,
contrary to the documented keyed retry contract. A scratch fault fixture
delaying issue reads by 1.6 seconds reproduced both old failures
(`Expected: 1 / Received: 2`); both revised cases passed under the same
delay. The delay fixture is kept outside the branch. Final head
`97269b3420387b28fda5f35f69a6b9ed45d5bb54` is merge-ready: all required
gates passed, 81 checks succeeded and four were skipped by workflow
policy, Greptile is 5/5 on this head, and the one review thread is
resolved. GitHub reports `MERGEABLE` / `CLEAN`. The skipped
external-database local cases and earlier failed attempts remain
recorded above.
- No provider suspension, external wake, deployment, or cost-saving
result is claimed from these local checks. The proof adds no provider
call, recurring scan, or extra database round trip. It runs within the
existing bounded, read-only snapshot.

## Risks

This expands automatic sleep eligibility for proved passive remote
state. A proof error could stop an instance with unfinished work. The
new cases cover dirty or foreign authority, missing or malformed
snapshot key material, incomplete operations, foreign or unverified
leases, active ownership, retry state, and retained recovery references.
The SQL checks the stored key format; archive decryption and object
verification remain with the restore owner. The existing owned hold,
generation checks, runtime probes, and final host authorization still
apply. The change does not delete files, clear reservations, rewrite
history, create receipts, change schedules, or add a migration. Revert
the remote-provider predicate to restore the previous refusal behavior.
Hosted stop/wake qualification remains part of deployment acceptance.

## Model Used

OpenAI GPT-6.1-sol with xhigh reasoning through Codex in T3 Code.
Tool-assisted implementation, source review, and PostgreSQL
verification.

## 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 described the issue in-PR following the bug report template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
ticket id or instance-derived details
- [x] I have run relevant tests locally and they pass; skipped
external-database cases are stated above
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation
- [x] I have considered and documented risks
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

- Final revision [ci /
e2e](https://github.com/paperclipai/paperclip/actions/runs/46539276027/job/142275047883):
passed.

- Final revision [ci /
verify](https://github.com/paperclipai/paperclip/actions/runs/46539276027/job/142275348382):
passed.

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-30 17:29:31 -08:00

640 lines
27 KiB
TypeScript

import { randomUUID } from "node:crypto";
import {
expect,
test,
type APIRequestContext,
type APIResponse,
type Locator,
type Page,
} from "@playwright/test";
// Real local Board UI, upload storage, comment HTTP routes, and disposable DB.
// Only the interface flag and explicit transport/upload rejection faults are mocked.
// Tasks have no recipient: no agent, runner, or provider is contacted.
type Attachment = {
id: string;
issueCommentId: string | null;
contentPath: string;
};
type Comment = { id: string; body: string; clientRequestId?: string | null };
type CommentRequest = {
body: string;
clientRequestId: string;
attachmentIds?: string[];
};
async function body<T>(
response: Pick<APIResponse, "json" | "ok" | "status" | "text">,
): Promise<T> {
expect(response.ok(), `${response.status()}: ${await response.text()}`).toBe(
true,
);
return response.json() as Promise<T>;
}
async function dismissAnnouncement(page: Page, dismiss: Locator) {
const menuOpen = await page.getByRole("menu", { name: "Add to composer", exact: true }).isVisible();
if (menuOpen) await page.keyboard.press("Escape");
const [button] = await dismiss.elementHandles();
if (button) {
try { await button.click(); }
catch (error) {
if (!(error instanceof Error) || !error.message.includes("Element is not attached") || await dismiss.count()) throw error;
}
}
if (menuOpen) await page.getByRole("button", { name: "Add to composer", exact: true }).click();
}
async function setup(page: Page, request: APIRequestContext, classic: boolean) {
await page.route("**/api/workspace-preferences/me", route => route.fulfill({ json: {
userId: "local-board", coordinatorWorkspaceEnabled: !classic, updatedAt: null,
} }));
// Announcements can appear after navigation or reload and cover the classic
// composer's attachment button. Dismiss through the same UI as a Board user.
await page.addLocatorHandler(
page.getByRole("complementary", { name: "Paperclip announcements", exact: true })
.getByRole("button", { name: "Dismiss announcement", exact: true }),
async (dismiss) => dismissAnnouncement(page, dismiss),
);
const company = await body<{ id: string; issuePrefix: string }>(
await request.post("/api/companies", {
data: { name: `Board receipt browser ${randomUUID()}` },
}),
);
const issue = await body<{ id: string; identifier: string }>(
await request.post(`/api/companies/${company.id}/issues`, {
data: {
title: "Inspect the newly uploaded Board files",
status: "todo",
// Keep attachment sends on the comment route. A task assigned to the
// current human now suggests an empty recipient and sends a reassignment.
assigneeUserId: null,
},
}),
);
await page.route("**/api/instance/settings/experimental", (route) =>
route.fulfill({
contentType: "application/json",
body: JSON.stringify({ enableClassicTaskInterface: classic }),
}),
);
await page.goto(`/${company.issuePrefix}/issues/${issue.identifier}`);
await expect(
page.getByRole("heading", {
name: "Inspect the newly uploaded Board files",
exact: true,
}),
).toBeVisible();
const composer = classic
? page.getByTestId("issue-chat-composer")
: page.locator(".paperclip-task-chat-composer");
const editor = composer.getByRole("textbox", {
name: "editable markdown",
exact: true,
});
const send = classic
? composer.getByRole("button", { name: /Send|Reply/ }).last()
: page.getByTestId("task-chat-composer-send");
await expect(editor).toBeVisible();
return {
company,
issue,
composer,
editor,
send,
sendComment: async () => {
await send.click();
if (classic) {
const confirm = page.getByTestId("issue-chat-no-assignee-send-anyway");
await expect(confirm).toBeVisible();
await confirm.click();
}
},
attachments: () =>
request
.get(`/api/issues/${issue.id}/attachments`)
.then(body<Attachment[]>),
comments: () =>
request.get(`/api/issues/${issue.id}/comments`).then(body<Comment[]>),
};
}
const files = [
{
name: "board-fresh.txt",
mimeType: "text/plain",
buffer: Buffer.from("Object: cat\nAccent: teal\nCount: 3\n"),
},
{
name: "board-fresh.png",
mimeType: "image/png",
buffer: Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jfFoAAAAASUVORK5CYII=",
"base64",
),
},
];
async function openAttachmentChooser(page: Page, composer: Locator) {
await composer.getByRole("button", { name: "Add to composer" }).click();
const chooser = page.waitForEvent("filechooser");
await page.getByRole("menuitem", { name: "Files and images", exact: true }).click();
return chooser;
}
test("new-task images survive reload, retain bytes, and clear after creation", async ({ page, request }) => {
const fixture = await setup(page, request, false);
await page.getByRole("button", { name: /^New [Tt]ask$/, exact: true }).first().click();
const dialog = page.getByRole("dialog", { name: "New task", exact: true });
const editor = dialog.getByRole("textbox", { name: "editable markdown", exact: true });
await editor.fill("Keep the caption and image after reload.");
const chooser = await openAttachmentChooser(page, dialog);
await chooser.setFiles(files[1]!);
await expect(dialog.getByRole("img", { name: "board-fresh.png", exact: true })).toBeVisible();
await expect.poll(() => page.evaluate(async () => {
const db = await new Promise<IDBDatabase>((resolve, reject) => {
const request = indexedDB.open("paperclip:issue-draft-files", 1);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
try {
return await new Promise<number>((resolve, reject) => {
const tx = db.transaction("files", "readonly");
const request = tx.objectStore("files").getAll();
tx.oncomplete = () => resolve(request.result.flat().length);
tx.onerror = () => reject(tx.error);
});
} finally { db.close(); }
})).toBe(1);
await expect.poll(() => page.evaluate(() => Object.entries(localStorage)
.some(([key, value]) => key.startsWith("paperclip:issue-draft:") && value.includes("Keep the caption")))).toBe(true);
await page.reload();
await page.getByRole("button", { name: /^New [Tt]ask$/, exact: true }).first().click();
await expect(editor).toContainText("Keep the caption and image after reload.");
await expect(dialog.getByRole("img", { name: "board-fresh.png", exact: true })).toBeVisible();
const upload = page.waitForResponse((response) => response.request().method() === "POST"
&& /\/issues\/[^/]+\/attachments$/.test(new URL(response.url()).pathname));
await dialog.getByRole("button", { name: "Create task", exact: true }).click();
const attachment = await body<Attachment>(await upload);
const content = await request.get(attachment.contentPath);
expect(content.ok()).toBe(true);
expect(await content.body()).toEqual(files[1]!.buffer);
await expect(dialog).toBeHidden();
await page.reload();
await page.getByRole("button", { name: /^New [Tt]ask$/, exact: true }).first().click();
await expect(dialog.getByRole("img")).toHaveCount(0);
});
test("an older image draft retains the rich editor", async ({ page, request }) => {
const fixture = await setup(page, request, false);
const attachment = await body<Attachment>(await request.post(`/api/companies/${fixture.company.id}/issues/${fixture.issue.id}/attachments`, {
multipart: { file: { name: files[1]!.name, mimeType: files[1]!.mimeType, buffer: files[1]!.buffer } },
}));
await page.addInitScript(({ issueId, imagePath }) => {
localStorage.setItem(`paperclip:issue-comment-draft:${issueId}`, `Keep this older caption.\n\n![Older image](${imagePath})`);
}, { issueId: fixture.issue.id, imagePath: attachment.contentPath });
await page.reload();
await expect(fixture.editor).toBeVisible();
await expect(fixture.editor).toContainText("Keep this older caption.");
await expect(fixture.composer.getByRole("img", { name: "Older image", exact: true })).toBeVisible();
await expect(fixture.composer.locator("textarea")).toHaveCount(0);
});
test("two open tabs retain their staged images when either tab saves or creates a task", async ({ page, request, context }) => {
await setup(page, request, false);
const second = await context.newPage();
await second.goto(page.url());
const dialogs = [page, second].map((tab) => tab.getByRole("dialog", { name: "New task", exact: true }));
for (const [index, tab] of [page, second].entries()) {
await tab.getByRole("button", { name: /^New [Tt]ask$/, exact: true }).first().click();
await dialogs[index]!.getByRole("textbox", { name: "editable markdown", exact: true }).fill(`Keep tab ${index + 1}'s image.`);
await expect(dialogs[index]!.getByRole("button", { name: "Create task", exact: true })).toBeEnabled();
}
const savedNames = () => page.evaluate(async () => {
const db = await new Promise<IDBDatabase>((resolve, reject) => {
const request = indexedDB.open("paperclip:issue-draft-files", 1);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
try {
return await new Promise<string[]>((resolve, reject) => {
const tx = db.transaction("files", "readonly");
const request = tx.objectStore("files").getAll();
tx.oncomplete = () => resolve(request.result.flat().map((item: { file: File }) => item.file.name).sort());
tx.onerror = () => reject(tx.error);
});
} finally { db.close(); }
});
for (const [index, tab] of [page, second].entries()) {
const chooser = await openAttachmentChooser(tab, dialogs[index]!);
await chooser.setFiles({ ...files[1]!, name: `tab-${index + 1}.png` });
await expect(dialogs[index]!.getByRole("img", { name: `tab-${index + 1}.png`, exact: true })).toBeVisible();
await expect.poll(savedNames).toEqual(index === 0 ? ["tab-1.png"] : ["tab-1.png", "tab-2.png"]);
}
await dialogs[0]!.getByRole("button", { name: "Create task", exact: true }).click();
await expect(dialogs[0]!).toBeHidden();
await expect.poll(savedNames).toEqual(["tab-2.png"]);
await second.reload();
await second.getByRole("button", { name: /^New [Tt]ask$/, exact: true }).first().click();
await expect(dialogs[1]!.getByRole("img", { name: "tab-2.png", exact: true })).toBeVisible();
await dialogs[1]!.getByRole("textbox", { name: "editable markdown", exact: true }).fill("Create the remaining tab's image.");
await dialogs[1]!.getByRole("button", { name: "Create task", exact: true }).click();
await expect(dialogs[1]!).toBeHidden();
await expect.poll(savedNames).toEqual([]);
await second.close();
});
async function upload(
page: Page,
fixture: Awaited<ReturnType<typeof setup>>,
file: (typeof files)[number],
) {
const chooser = await openAttachmentChooser(page, fixture.composer);
const response = page.waitForResponse(
(res) =>
res.request().method() === "POST" &&
new URL(res.url()).pathname.endsWith(
`/issues/${fixture.issue.id}/attachments`,
),
);
await chooser.setFiles(file);
const receipt = await body<Attachment>(await response);
await expect
.poll(async () =>
(await fixture.attachments()).some((item) => item.id === receipt.id),
)
.toBe(true);
return receipt;
}
for (const classic of [false, true]) {
test(`uploaded file and image receipts survive reload and bind exactly once (classic=${classic})`, async ({
page,
request,
}, testInfo) => {
const fixture = await setup(page, request, classic);
await fixture.editor.fill(
"Inspect only these fresh Board attachments. Keep this internal.",
);
const receipts = [];
for (const file of files) receipts.push(await upload(page, fixture, file));
const draftKey = `paperclip:issue-comment-draft:${fixture.issue.id}`;
await expect
.poll(() =>
page.evaluate(
(key) =>
JSON.parse(localStorage.getItem(`${key}:attachments:v1`) ?? "null")
?.attachments?.length,
draftKey,
),
)
.toBe(2);
await expect
.poll(() => page.evaluate((key) => localStorage.getItem(key), draftKey))
.toContain("Inspect only these fresh Board attachments.");
await testInfo.attach("before-reload-draft", {
body: JSON.stringify(
await page.evaluate(
(key) => ({
text: localStorage.getItem(key),
receipts: localStorage.getItem(`${key}:attachments:v1`),
}),
draftKey,
),
),
contentType: "application/json",
});
await page.reload();
await expect(fixture.editor).toContainText(
"Inspect only these fresh Board attachments.",
);
await expect(
fixture.composer.getByText("board-fresh.txt", { exact: true }),
).toBeVisible();
await expect(fixture.composer.locator("img")).toHaveCount(1);
const outbound = page.waitForRequest(
(req) =>
req.method() === "POST" &&
new URL(req.url()).pathname.endsWith("/comments"),
);
await fixture.sendComment();
expect((await outbound).postDataJSON().attachmentIds.sort()).toEqual(
receipts.map((row) => row.id).sort(),
);
await expect.poll(async () => (await fixture.comments()).length).toBe(1);
const [comment] = await fixture.comments();
const savedBubble = classic
? page.locator(`[id="comment-${comment!.id}"]`)
: page.getByTestId("task-chat-human-bubble").filter({
hasText:
"Inspect only these fresh Board attachments. Keep this internal.",
});
await expect(savedBubble).toHaveCount(1);
expect(comment.body).toContain(receipts[0]!.contentPath);
expect(comment.body).toContain(receipts[1]!.contentPath);
expect(
(await fixture.attachments()).map((item) => item.issueCommentId),
).toEqual([comment.id, comment.id]);
for (let index = 0; index < receipts.length; index++) {
const downloaded = await request.get(receipts[index]!.contentPath);
expect(downloaded.ok()).toBe(true);
expect(await downloaded.body()).toEqual(files[index]!.buffer);
}
await expect
.poll(() =>
page.evaluate(
(key) => localStorage.getItem(`${key}:attachments:v1`),
draftKey,
),
)
.toBeNull();
await page.reload();
await expect(fixture.editor).toBeEmpty();
expect(await fixture.comments()).toHaveLength(1);
await expect(savedBubble).toHaveCount(1);
await page.screenshot({
path: testInfo.outputPath("bound-board-attachments.png"),
fullPage: true,
});
});
}
{
const classic = false;
test(`lost accepted response settles without duplicate delivery (classic=${classic})`, async ({
page,
request,
}, testInfo) => {
const fixture = await setup(page, request, classic);
await fixture.editor.fill("Accepted once: inspect this exact file.");
const receipt = await upload(page, fixture, files[0]!);
let accepted = false;
const attempts: CommentRequest[] = [];
let acceptedRequestId: string | undefined;
await page.route("**/api/issues/*/comments", async (route) => {
if (route.request().method() !== "POST") return route.continue();
attempts.push(route.request().postDataJSON());
if (accepted) return route.continue();
acceptedRequestId = attempts[0]!.clientRequestId;
const response = await route.fetch();
expect(response.status()).toBe(201);
accepted = true;
await route.abort("connectionreset");
});
await fixture.sendComment();
await expect.poll(() => accepted).toBe(true);
expect(await fixture.comments()).toHaveLength(1);
expect(acceptedRequestId).toEqual(expect.any(String));
expect((await fixture.comments())[0]!.clientRequestId).toBe(acceptedRequestId);
expect(
(await fixture.attachments()).find((row) => row.id === receipt.id)
?.issueCommentId,
).toBeTruthy();
await page.reload();
// A restored plain comment may retry with its original key before its
// receipt loads. That retry must preserve the payload and save no duplicate.
await expect(fixture.editor).toBeEmpty();
await expect(fixture.composer.getByRole("alert")).toHaveCount(0);
await expect(fixture.composer.getByText("board-fresh.txt", { exact: true })).toHaveCount(0);
await expect(fixture.send).toBeDisabled();
for (const attempt of attempts) expect(attempt).toEqual(attempts[0]);
const settledAttempts = attempts.length;
await fixture.editor.press("Control+Enter");
expect(attempts).toHaveLength(settledAttempts);
expect(await fixture.comments()).toHaveLength(1);
await page.screenshot({
path: testInfo.outputPath("accepted-response-lost.png"),
fullPage: true,
});
expect(
(await fixture.attachments()).find((row) => row.id === receipt.id)
?.issueCommentId,
).toBeTruthy();
await page.reload();
await expect(fixture.composer.getByRole("alert")).toHaveCount(0);
await fixture.editor.fill(
"A deliberately new comment after the original receipt settled.",
);
await fixture.sendComment();
await expect.poll(async () => (await fixture.comments()).length).toBe(2);
});
test(`known rejection retains the same uploaded receipt for explicit retry (classic=${classic})`, async ({
page,
request,
}) => {
const fixture = await setup(page, request, classic);
await fixture.editor.fill("Known rejection, then retry the same file.");
const receipt = await upload(page, fixture, files[0]!);
let rejected = false;
await page.route("**/api/issues/*/comments", async (route) => {
if (route.request().method() !== "POST" || rejected)
return route.continue();
rejected = true;
await route.fulfill({
status: 422,
contentType: "application/json",
body: JSON.stringify({ error: "Fixture policy rejected this attempt" }),
});
});
await fixture.sendComment();
await expect(fixture.editor).toContainText("Known rejection,");
await expect(fixture.send).toBeEnabled();
expect(await fixture.comments()).toHaveLength(0);
await page.reload();
await expect(fixture.editor).toContainText("Known rejection,");
await expect(fixture.composer.getByRole("alert")).toHaveCount(0);
await fixture.sendComment();
await expect.poll(async () => (await fixture.comments()).length).toBe(1);
expect(
(await fixture.attachments()).find((row) => row.id === receipt.id)
?.issueCommentId,
).toBeTruthy();
});
test(`reload during a pending save settles its receipt and preserves a newer draft (classic=${classic})`, async ({
page,
request,
}) => {
const fixture = await setup(page, request, classic);
await fixture.editor.fill("One text-only save interrupted by reload.");
let release!: () => void;
const held = new Promise<void>((resolve) => {
release = resolve;
});
let accepted = false;
const attempts: CommentRequest[] = [];
let acceptedRequestId: string | undefined;
await page.route("**/api/issues/*/comments", async (route) => {
if (route.request().method() !== "POST") return route.continue();
const payload = route.request().postDataJSON() as CommentRequest;
attempts.push(payload);
acceptedRequestId ??= payload.clientRequestId;
const response = await route.fetch();
expect(response.status()).toBe(201);
accepted = true;
await held;
// Reload cancels the original browser request; the owned server response
// has already been observed and must never be replayed by the fixture.
await route.fulfill({ response }).catch(() => {});
});
try {
await fixture.sendComment();
await expect.poll(() => accepted).toBe(true);
expect(await fixture.comments()).toHaveLength(1);
await fixture.editor.fill("A newer draft written while delivery was pending.");
await page.reload();
release();
await expect(fixture.editor).toHaveText(
"A newer draft written while delivery was pending.",
);
await expect(fixture.composer.getByRole("alert")).toHaveCount(0);
await expect(fixture.send).toBeEnabled();
// Reload can race the keyed resend backoff. Every attempt before the
// deliberate next send must still be the exact original request.
for (const attempt of attempts) expect(attempt).toEqual(attempts[0]);
expect(await fixture.comments()).toHaveLength(1);
expect(acceptedRequestId).toEqual(expect.any(String));
expect((await fixture.comments())[0]!.clientRequestId).toBe(acceptedRequestId);
await fixture.sendComment();
await expect.poll(async () => (await fixture.comments()).length).toBe(2);
const nextRequest = attempts.find(attempt => attempt.clientRequestId !== acceptedRequestId);
expect(nextRequest).toMatchObject({ body: "A newer draft written while delivery was pending." });
for (const attempt of attempts) {
expect(attempt).toEqual(attempt.clientRequestId === acceptedRequestId ? attempts[0] : nextRequest);
}
expect(new Set((await fixture.comments()).map(comment => comment.clientRequestId)))
.toEqual(new Set([acceptedRequestId, nextRequest!.clientRequestId]));
expect((await fixture.comments()).map((comment) => comment.body).sort()).toEqual([
"A newer draft written while delivery was pending.",
"One text-only save interrupted by reload.",
]);
} finally {
release();
}
});
}
for (const classic of [false, true])
test(`removed pending inline upload cannot reappear or submit after its HTTP response (classic=${classic})`, async ({
page,
request,
}) => {
const fixture = await setup(page, request, classic);
await fixture.editor.fill("Send without the removed image.");
let release!: () => void;
const held = new Promise<void>((resolve) => {
release = resolve;
});
let arrived = false;
await page.route(
`**/api/companies/${fixture.company.id}/issues/${fixture.issue.id}/attachments`,
async (route) => {
const response = await route.fetch();
arrived = true;
await held;
await route.fulfill({ response });
},
);
const chooser = await openAttachmentChooser(page, fixture.composer);
await chooser.setFiles(files[1]!);
await expect.poll(() => arrived).toBe(true);
await expect(fixture.send).toBeDisabled();
try {
await expect(
fixture.composer.getByText(
classic ? "Uploading to task" : "Uploading board-fresh.png…",
{ exact: true },
),
).toBeVisible();
const remove = fixture.composer.getByRole("button", {
name: "Remove board-fresh.png",
});
await expect(remove).toBeVisible();
await remove.click();
release();
await expect(fixture.send).toBeEnabled();
await expect(fixture.composer.locator("img")).toHaveCount(0);
const outbound = page.waitForRequest(
(req) =>
req.method() === "POST" &&
new URL(req.url()).pathname.endsWith("/comments"),
);
await fixture.sendComment();
expect((await outbound).postDataJSON().attachmentIds).toBeUndefined();
await expect.poll(async () => (await fixture.comments()).length).toBe(1);
expect((await fixture.comments())[0]!.body).not.toContain(
"/api/attachments/",
);
expect((await fixture.attachments())[0]!.issueCommentId).toBeNull();
} finally {
release();
}
});
test("legacy failed upload can be removed before sending the retained text", async ({
page,
request,
}) => {
const fixture = await setup(page, request, true);
await fixture.editor.fill("Keep this text after removing the failed file.");
await page.route(
`**/api/companies/${fixture.company.id}/issues/${fixture.issue.id}/attachments`,
(route) =>
route.fulfill({
status: 500,
contentType: "application/json",
body: JSON.stringify({ error: "Fixture upload rejected" }),
}),
);
const chooser = await openAttachmentChooser(page, fixture.composer);
await chooser.setFiles(files[0]!);
await expect(
fixture.composer.getByText("Fixture upload rejected", { exact: true }),
).toBeVisible();
await expect(fixture.send).toBeDisabled();
const remove = fixture.composer.getByRole("button", {
name: "Remove board-fresh.txt",
});
await expect(remove).toBeVisible();
await remove.click();
await fixture.sendComment();
await expect.poll(async () => (await fixture.comments()).length).toBe(1);
expect((await fixture.comments())[0]!.body).toBe(
"Keep this text after removing the failed file.",
);
expect(await fixture.attachments()).toHaveLength(0);
});
test("announcement dismissal handler tolerates an already-removed announcement", async ({ page }) => {
await page.setContent(`<aside aria-label="Paperclip announcements"><button aria-label="Dismiss announcement">Dismiss</button></aside><button id="continue" onclick="this.dataset.clicked='yes'">Continue</button>`);
const dismiss = page.getByRole("complementary", { name: "Paperclip announcements" }).getByRole("button", { name: "Dismiss announcement" });
await page.addLocatorHandler(dismiss, async locator => {
await page.locator("aside").evaluate(element => element.remove());
await dismissAnnouncement(page, locator);
});
await page.getByRole("button", { name: "Continue", exact: true }).click({ timeout: 1000 });
await expect(page.locator("#continue")).toHaveAttribute("data-clicked", "yes");
await expect(dismiss).toHaveCount(0);
});
test("announcement dismissal handler preserves errors while the target remains", async ({ page }) => {
await page.setContent('<aside aria-label="Paperclip announcements"><button disabled aria-label="Dismiss announcement">Dismiss</button></aside><button>Continue</button>');
const dismiss = page.getByRole("complementary", { name: "Paperclip announcements" }).getByRole("button", { name: "Dismiss announcement" });
page.setDefaultTimeout(1000);
await expect(dismissAnnouncement(page, dismiss)).rejects.toThrow(/Timeout|timeout/);
await expect(dismiss).toBeVisible();
await expect(dismiss).toBeDisabled();
});
test("announcement dismissal handler tolerates detachment after its element snapshot", async ({ page }) => {
await page.setContent('<aside aria-label="Paperclip announcements"><button aria-label="Dismiss announcement">Dismiss</button></aside>');
const dismiss = page.getByRole("complementary", { name: "Paperclip announcements" }).getByRole("button", { name: "Dismiss announcement" });
const snapshot = await dismiss.elementHandles();
expect(snapshot).toHaveLength(1);
await snapshot[0]!.evaluate(element => (element as ChildNode).remove());
dismiss.elementHandles = async () => snapshot;
await dismissAnnouncement(page, dismiss);
await expect(dismiss).toHaveCount(0);
});