Files
PaperClipAI/tests/e2e/board-attachment-receipts.spec.ts
T
Nicky LeachandClaude Opus 5.5 83c6832ccb fix(build): typecheck package, Playwright, and e2e test files in CI (#18839)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Runner, plugin, and Playwright tests verify how those agents run,
connect, and appear in the board
> - Most package tsconfigs exclude tests, and Vitest strips types, so a
type error in those tests fails nothing
> - The tests drifted to 803 real type errors, and some of those errors
hid assertions that checked nothing
> - paperclipai/paperclip#18739 and paperclipai/paperclip#18738 check
the server test tree and four test projects, but not these files
> - This pull request adds a required check for these test files, fixes
every error, and fails CI if a test file is in no program
> - The benefit is that a type error in any test file outside
`server/src` now fails CI

## Linked Issues or Issue Description

Refs #18739
Refs #18738

**What happened?**

517 test files were in no program that required CI checks. A type error
in those files did not fail CI.

**Expected behavior**

CI fails on a type error in any test file.

**Steps to reproduce**

Add `export const value: number = "text";` to a test file under
`packages/paperclip-runner/src` on master. CI stays green, because
`tsconfig.json` excludes test files and Vitest strips types.

**Measured gap**

Each row is a program with its tests included, on one thread. File and
error counts are for head `7d4b5e907a`. Memory peaks were measured
before the two latest merges of master.

| Group | Test files | Real errors | Peak |
| --- | ---: | ---: | ---: |
| `paperclip-runner` Node source | 290 | 644 | 1.09 GiB |
| `paperclip-runner` surfaces | 9 | 12 | 0.42 GiB |
| `paperclip-runner` devtools and examples | 14 | 0 | 0.68 GiB |
| `sandbox-providers/kubernetes` | 21 | 65 | 0.44 GiB |
| 8 other sandbox providers and `bridge-template` | 32 | 4 | 0.34 GiB |
| `plugins/sdk` | 22 | 15 | 0.41 GiB |
| `plugin-workspace-diff` | 5 | 0 | 0.37 GiB |
| `plugin-orchestration-smoke-example` | 1 | 1 | 0.15 GiB |
| `kv-demo-mcp-server` | 3 | 0 | 0.13 GiB |
| `packages/db` scripts | 1 | 0 | 1.01 GiB |
| 8 Playwright suites under `tests/` | 52 | 25 | 1.72 GiB |
| `tests/runner-acceptance` | 3 | 0 | 0.58 GiB |
| `tests/e2e`, through layer declarations | 63 | 37 | at most 1.59 GiB |
| `ui` `AttentionInteractionResolver.test.tsx` | 1 | 0 | n/a |
| **Total** | **517** | **803** | |

27 of the 803 errors came from master while this pull request was open.
Each merge of master brought new test code that no check had read.

Errors that were config errors, not real errors:

- One TS2688 for each provider, because the root install does not
install provider dependencies.
- 9 in the Runner Node program (TS7016 and TS6059).
- 2 in `tsconfig.browser.json`. TypeScript 7 removed `baseUrl`, so that
config was invalid.
- 213 in the Playwright suites (`@/*` aliases and Vite types).
- About 60 in `tests/e2e` (import extensions and aliases).

`packages/plugins/create-paperclip-plugin` has no gap. Its tsconfig
excludes its test, but `cli/tsconfig.json` reaches that test through an
import. `server/test-baselines` also has no gap, because
`tests/lifecycle-baseline` reads it.

## What Changed

- Added `scripts/typecheck-test-programs.mjs` and its tests. The
`Typecheck + Release Registry` job runs it. It checks each program in
`PROGRAMS` on one thread.
- The script fails if a tracked `*.test.ts(x)` or `*.spec.ts(x)` file
outside `server/src` is in no program. The compiler file list decides
this, because `include` drops `foo.test.tsx` when `foo.test.ts` exists.
- Added a `tsconfig.test.json` to each uncovered package, and
`tests/tsconfig.playwright.json`.
- Added `tests/e2e` to `PROJECTS` in
`scripts/typecheck-test-projects.mjs`, with a `tsconfig.json` and a
`tsconfig.layers.json`.
- Added `scripts/typecheck-sandbox-providers`. It is a small workspace
that installs provider SDKs from one lockfile. I did not add a lockfile
inside each provider, because
`scripts/build-standalone-public-packages.mjs` uses a frozen install
when one exists, and that changes what a release resolves.
- Corrected `packages/paperclip-runner/tsconfig.browser.json` for
TypeScript 7.
- Set `rootDir` to `..` in
`packages/paperclip-runner/tsconfig.test.json`, because one Runner test
imports from `packages/adapter-utils/src`. The program does not emit
files, so this changes no build output.
- Moved the Kubernetes provider from `vitest ^3.2.4` to `^4.1.8`, the
version the other providers use. Vitest 3 requires `tinypool ^1.1.1`,
which has two critical advisories (GHSA-85c8-ppgw-ccpr and
GHSA-5gmw-xhrv-c9v3). The first patched version is 2.1.2. Its tests have
the same result on both versions: 189 passed, and the same 12
`file-sync` tests failed.
- Moved the Kubernetes provider from `zod ^3.24.2` to `^4.6.6`, and gave
its two `z.record` calls a key schema. This is the only production
change, and it stays in this pull request. See "Production change for
review".
- Renamed `AttentionInteractionResolver.test.ts` to
`AttentionInteractionResolver.replace.test.ts`, so TypeScript reads the
`.test.tsx` beside it.
- Fixed all 803 errors, with changes to test files and test support
only. The fix for `contracts/native-execution.test.ts` is the same as
the fix in paperclipai/paperclip#18739, so those two changes merge
cleanly.
- Updated `doc/DEVELOPING.md`.

This pull request does not edit `server/scripts/typecheck-layers.mjs`.
paperclipai/paperclip#18739 and paperclipai/paperclip#18738 have both
merged, and this branch includes them.

### Production change for review

The new lockfile made dependency review flag `zod@3.25.76` as a
high-severity advisory (GHSA-mrhx-c7xc-m3w5). The first patched version
is 4.6.6, so 3.x has no fix. The published Kubernetes plugin uses zod to
validate operator config. The zod 3 source does not compile against zod
4, so a typecheck-only override cannot fix this.

The existing tests do not prove this change, because they also passed
with the invalid one-argument `z.record`. So I parsed 45 inputs with the
same schema on zod 3.25.76 and zod 4.6.7:

| Result | Inputs | Detail |
| --- | ---: | --- |
| Identical | 23 | Includes defaults, valid config, and a `__proto__`
key |
| Same outcome, new error wording | 21 | For example, `Invalid url` is
now `Invalid URL`. `validateConfig` shows this text to operators. |
| Different outcome | 1 | `jobTtlSecondsAfterFinished: 2 ** 60` was
valid and is now rejected. The new limit is `Number.MAX_SAFE_INTEGER`. |

I did not test this against a real cluster.

The decision is to keep this change in this pull request. Since then,
paperclipai/paperclip#17364 has moved the rest of the repository to zod
4.6.x, so the Kubernetes plugin now matches it.

### Behavior change for review

`reducedMotion` under `use` is not a Playwright option. It had no effect
in 11 configs and 2 `test.use` calls, so those suites ran with
`no-preference`. The options are now under `contextOptions`, so reduced
motion now takes effect. `app-shell-design.spec.ts` asserts a real
transition, so it now asks for `no-preference` itself.

The baseline manifest has `snapshotCount: 0`, so this invalidates no
published baseline. A frozen trial reference PNG can differ.

### Findings

These are product questions. I did not change them, and I did not hide
them with casts:

1. **`PrpEvent` and its schema disagree.** The TypeScript type in
`src/protocol/replay-contract.ts` requires `normalizedSessionId`. The
`required` list in `protocol/schemas/event.schema.json` does not include
it. `validatePrpEvent` accepts events that the type forbids.
2. **`requestCheckboxConfirmation` is stricter than its runtime.** It
uses the output type, so plugin authors must pass `continuationPolicy`
and `allowDeclineReason`, although the schema gives them defaults.
`z.input` would fix this.
3. **`RetainedRunnerdMaintenanceInput.backend.kind` is a free string.**
The quarantine domain comes from `descriptor.kind`, but the release uses
`proof.backend.kind`. If they differ,
`completeRetainedNativeSessionCleanup` returns 0 and the quarantine
stays. The production caller passes `"runner"` today, so this is not a
live bug.
4. **`CodexHarnessSession.close(input?)` is optional, but the contract
requires `{ reason }`.**

These are tests that verified nothing. I corrected them, and they pass:

- `backends/native-instruction-measurement.test.ts` filtered on
`placement === "core"`, which is not a valid placement. It measured an
empty tool list. It now measures 14 tools.
- `drivers/acpx/codex-acpx-driver.test.ts` checked for `usage.updated`,
which is not an event type.
- The `hostFixture()` helper in `drivers/acpx/runtime-host.test.ts`
ignored two overrides, so
`expect(prepareSandbox).not.toHaveBeenCalled()` could not fail.
- `live/live-session.test.ts` set `agent: "pi"` before a spread that
overwrote it.
- `native-distribution-integrity.test.ts` passed an AbortSignal where
`openCommand` expects `{ signal }`.

These are gaps that this pull request does not close:

- **The root lockfile still has some old zod versions.**
paperclipai/paperclip#17364 moved the direct zod dependencies to 4.6.x.
`pnpm-lock.yaml` still resolves `zod@3.25.76`, `4.1.11`, and `4.4.3`,
which are below the patched 4.6.6.
`packages/paperclip-runner/scripts/pi-distribution/package.json` pins
`zod` to `3.25.76`, and some agent SDKs resolve `4.4.3`. Dependency
review does not flag them, because this pull request does not add them.
- **Dead GitHub coverage.** `chat-adapters-ui-providers.spec.ts`
returned early for GitHub, so four later `provider === "github"`
branches never ran. I removed them. They included the private key file
and paste match, and the reconnect flow. Nothing asserts those behaviors
in that spec now.
- **Provider tests do not run in CI.** The root `vitest.config.ts` lists
only Daytona. The other 8 providers, `bridge-template` included, are
typechecked now, but CI does not run their tests.
- **One `packages/db` test never runs.**
`scripts/clean-poisoned-claude-sessions.test.ts` is outside the
`include` of `packages/db/vitest.config.ts`.
- **`plugin-orchestration-smoke-example` does not collect.**
`@paperclipai/shared` is not linked in its `node_modules`. It passes 3
of 3 with an alias.

## Verification

Run these commands:

```sh
node scripts/typecheck-test-programs.mjs --low-memory
pnpm --filter @paperclipai/server typecheck
node scripts/typecheck-test-projects.mjs --low-memory --reuse-declarations
node --test scripts/typecheck-test-programs.test.mjs
```

Results on macOS (arm64), Node 26.12. CI uses Node 24, and its
`Typecheck + Release Registry` job also passes. At head `7d4b5e907a`,
the test programs, `tests/e2e`, and the script tests pass again with 0
errors. The times and peaks below come from the run before the two
latest merges of master:

| Check | Result |
| --- | --- |
| Test programs, `--low-memory` | Exit 0, 0 errors, 42 seconds, peak
1.78 GiB |
| Server layers, low memory | Exit 0, 0 errors, 38 seconds, peak 3.41
GiB |
| Test projects, including `tests/e2e` | Exit 0, 0 errors, 13 seconds,
peak 1.59 GiB |
| Script tests | 12 passed |
| Injected type error in each of 23 places | Each one failed its program
with TS2322 |
| Coverage check | 0 unchecked files, 10 seconds |

I did not run this in a 4 GiB container. The peaks above are `maximum
resident set size` for the largest single process.

**Runtime check of the fixes.** Types do not prove that a test still
works, so I ran the suites before the two latest merges of master:

| Suite | Result |
| --- | --- |
| Runner, full suite | 4,885 passed, 3 failed, 13 skipped |
| Sandbox providers, 10 packages | 939 passed, 12 failed, 36 skipped |
| Plugin SDK | 200 passed |
| `kv-demo-mcp-server` | 12 passed |
| Renamed UI test and its sibling | 4 passed |

All 15 failures exist without these fixes or come from the local
machine:

- **3 Cursor Cloud timeouts.** `artifact-delivery.test.ts` has 1 and
`cursor-cloud-driver.test.ts` has 2. They time out in a full local run,
and all 133 tests in those files with `codex-security-config.test.ts`
pass when run alone. They fail in the same way with those two files at
their unedited versions.
- **12 Kubernetes `file-sync.test.ts` failures.** They fail in the same
way before and after the fixes. The first failure is that
`/proc/self/fd` does not exist on macOS.

After each of the two latest merges of master, I ran only the Runner
test files that I changed:

| Merge | Result |
| --- | --- |
| `885c249cb9`, 8 files | 534 passed |
| `7d4b5e907a`, 7 files | 672 passed, 16 failed |

The 16 failures are in the two `source-reconciliation` test files. They
fail in the same way with master's unedited versions of those files. 15
of them fail with `ACPX sidecar exited at initialize`, so I think my
local build of the Rust and sidecar binaries is out of date. I did not
rebuild them to check. CI builds them from scratch, and all Runner jobs
pass in CI at `7d4b5e907a`.

**Not run:**

- `tests/e2e` and the 8 Playwright suites need a server, so most of them
have only compile checks. `playwright test --list` loads 308 tests from
the main e2e config.
- `packages/plugins/sandbox-providers/kubernetes/test/integration` needs
a cluster, so it has only compile checks.
- I did not run the full `pnpm test:run` or root `pnpm build`. Required
CI runs them.

**Reduced motion.** I ran 6 motion-sensitive Storybook specs in system
Chrome with a temporary config, once with `reduce` and once with
`no-preference`. Both runs had 45 passed and the same 5 failed. So
reduced motion did not change those results. The 5 failures do not
depend on motion. At least one comes from the browser, because system
Chrome prints `oklch(55.6% 0 0)` where the test expects `oklch(0.556 0
0)`. I did not run the other Storybook specs. The `storybook-visual`
label runs that workflow.

## Risks

- **A new lockfile to maintain.** A change to a provider `package.json`
now fails the typecheck job until someone refreshes
`scripts/typecheck-sandbox-providers/pnpm-lock.yaml`. The failure
message gives the command.
- **The job has a new install.** The step downloads provider SDKs, so it
depends on the npm registry. It uses `--frozen-lockfile` and
`--ignore-scripts`.
- **The local install replaces provider `node_modules`.** A contributor
with a standalone provider install must reinstall that provider after
running the script.
- **Reduced motion can change Storybook results.** See "Behavior change
for review". That workflow is not part of required CI.
- **Kubernetes plugin validation changed.** A release of this plugin
ships zod 4. Error wording changes, and very large integers are now
rejected. See "Production change for review".
- **Master moves fast.** Each merge of master brought new test code with
type errors, 27 so far. After this merges, the check reports those
errors in the pull request that adds them.

## Model Used

- Provider: Anthropic Claude, through Claude Code
- Model: Claude Opus 5.5 (`claude-opus-5-5`)
- Capabilities: tool use, code execution, and subagents for the type
fixes in separate files

## 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)
- [ ] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived
details. The app generated the branch name.
- [ ] I have run tests locally and they pass. See the failures explained
in Verification.
- [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
- [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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 07:33:59 -08:00

621 lines
26 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 };
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,
});
});
test(`lost accepted response settles from its exact receipt without replay (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;
let attempts = 0;
let acceptedRequestId: string | undefined;
await page.route("**/api/issues/*/comments", async (route) => {
if (route.request().method() !== "POST") return route.continue();
attempts++;
if (accepted) return route.continue();
acceptedRequestId = route.request().postDataJSON().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();
// The durable request receipt proves delivery even though the POST reply
// was lost. No manual Review/Discard bookkeeping or blind replay remains.
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();
await fixture.editor.press("Control+Enter");
expect(attempts).toBe(1);
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;
let attempts = 0;
let acceptedRequestId: string | undefined;
await page.route("**/api/issues/*/comments", async (route) => {
if (route.request().method() !== "POST") return route.continue();
attempts++;
acceptedRequestId ??= route.request().postDataJSON().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();
expect(attempts).toBe(1);
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);
expect(attempts).toBe(2);
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);
});