Files
PaperClipAI/ui/src/components/DocumentAnnotationPopover.test.tsx
T
Nicky LeachandPaperclip 68ea3fcf53 test(ui): stabilize annotation popover submit-shortcut test (#11330)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The board UI lets users add comments to document annotations
> - The annotation popover test submits a comment with a keyboard
shortcut
> - React can delay the controlled textarea update under load
> - The test can then send the shortcut before the handler sees the
typed value
> - This pull request waits for the value update before it sends the
shortcut
> - The benefit is a stable test that checks the real submit path

## Linked Issues or Issue Description

**What happened?**

The annotation popover test typed a comment and sent the submit shortcut
in one synchronous step. Under load, React sometimes had not committed
the typed value when the handler ran. The mutation then ran zero times.

**Expected behavior**

The test should wait for the controlled textarea value before it sends
the submit shortcut. The handler should read the comment and call the
create mutation.

**Steps to reproduce**

1. Run `npx vitest run
src/components/DocumentAnnotationPopover.test.tsx` from `ui/`.
2. Repeat the test under system load.
3. Observe intermittent failures where the create mutation runs zero
times.

**Paperclip version or commit**

The test runs against commit `9a08def5752bb13e4cbcb304c6295e175c92db3c`.

**Deployment mode**

This change affects the UI test suite only. It does not depend on a
deployment mode.

## What Changed

- Wait for the Comment button to enable after the controlled value
updates.
- Send the submit shortcut after React commits the typed value.
- Keep the test focused on the compose-mode submit path.

## Verification

- The author ran `npx vitest run
src/components/DocumentAnnotationPopover.test.tsx` from `ui/` with 3
tests passing.
- The current handoff worktree could not repeat the test because its
installed dependencies lack `react/jsx-runtime`.
- GitHub Actions will run the required project checks.

## Risks

Low risk. The change updates one UI test file and does not change
product code.

## Model Used

OpenAI Codex, GPT-5. The model used tool calls and code execution. The
context window size was not provided.

## 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
- [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

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-08-13 11:44:29 -07:00

139 lines
5.7 KiB
TypeScript

// @vitest-environment jsdom
import { createRef } from "react";
import { createRoot } from "react-dom/client";
import type { DocumentAnnotationThreadWithComments } from "@paperclipai/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DocumentAnnotationPopover } from "./DocumentAnnotationPopover";
const mutations = vi.hoisted(() => ({
create: vi.fn(),
reply: vi.fn(),
status: vi.fn(),
}));
vi.mock("@/hooks/useDocumentAnnotationMutations", () => ({
useDocumentAnnotationMutations: () => ({
createThread: { mutate: mutations.create, isPending: false },
addReply: { mutate: mutations.reply, isPending: false },
updateStatus: { mutate: mutations.status, isPending: false },
mutationError: null,
}),
}));
vi.mock("./MarkdownBody", () => ({ MarkdownBody: ({ children }: { children: string }) => <p>{children}</p> }));
const pendingAnchor = {
selector: {
quote: { exact: "selected plan text", prefix: "", suffix: "" },
position: { normalizedStart: 0, normalizedEnd: 18, markdownStart: 0, markdownEnd: 18 },
},
selectedText: "selected plan text",
};
function thread(): DocumentAnnotationThreadWithComments {
return {
id: "thread-1",
status: "open",
anchorState: "active",
selectedText: "selected plan text",
comments: [{
id: "comment-1",
threadId: "thread-1",
body: "Initial comment",
authorType: "user",
authorAgentId: null,
authorUserId: "user-1",
createdAt: new Date(),
updatedAt: new Date(),
}],
} as unknown as DocumentAnnotationThreadWithComments;
}
describe("DocumentAnnotationPopover", () => {
let host: HTMLDivElement;
let container: HTMLDivElement;
let root: ReturnType<typeof createRoot>;
beforeEach(() => {
vi.clearAllMocks();
host = document.createElement("div");
container = document.createElement("div");
Object.defineProperties(container, { clientWidth: { value: 500 }, clientHeight: { value: 500 } });
host.appendChild(container);
document.body.appendChild(host);
root = createRoot(container);
});
afterEach(async () => {
await vi.waitFor(() => root.unmount());
host.remove();
});
const render = async (overrides: Partial<React.ComponentProps<typeof DocumentAnnotationPopover>> = {}) => {
const onClose = vi.fn();
const props: React.ComponentProps<typeof DocumentAnnotationPopover> = {
anchorRect: { top: 40, left: 60, width: 100, height: 20 },
containerRef: createRef<HTMLDivElement>(),
target: { kind: "issue", issueId: "issue-1", documentKey: "plan" },
documentKey: "plan",
baseRevisionId: "rev-1",
baseRevisionNumber: 1,
pendingAnchor,
thread: null,
focusedCommentId: null,
onFocusThread: vi.fn(),
onClose,
onThreadCreated: vi.fn(),
...overrides,
};
props.containerRef.current = container;
root.render(<DocumentAnnotationPopover {...props} />);
await vi.waitFor(() => expect(container.querySelector('[data-testid="document-annotation-popover"]')).not.toBeNull());
return { onClose };
};
it("anchors compose mode and submits with the keyboard shortcut", async () => {
await render();
const card = container.querySelector('[data-testid="document-annotation-popover"]') as HTMLElement;
expect(card.style.top).toBe("66px");
expect(card.style.left).toBe("60px");
const textarea = container.querySelector("textarea") as HTMLTextAreaElement;
const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")?.set;
setter?.call(textarea, "Looks good");
textarea.dispatchEvent(new Event("input", { bubbles: true }));
// Wait for React to commit the composer value before the submit shortcut.
// The Comment button enables only after the controlled value updates, so its
// enabled state proves the keydown handler now reads the typed text. Without
// this wait the keydown can run against an empty composer and never submit.
const commentButton = Array.from(container.querySelectorAll("button")).find((button) => button.textContent?.includes("Comment")) as HTMLButtonElement;
await vi.waitFor(() => expect(commentButton.disabled).toBe(false));
textarea.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", metaKey: true, bubbles: true }));
await vi.waitFor(() => expect(mutations.create).toHaveBeenCalledWith("Looks good"));
});
it("dismisses on Escape and outside pointer down", async () => {
const first = await render();
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
expect(first.onClose).toHaveBeenCalledTimes(1);
document.body.dispatchEvent(new Event("pointerdown", { bubbles: true }));
expect(first.onClose).toHaveBeenCalledTimes(2);
});
it("replies to and resolves a focused thread", async () => {
await render({ pendingAnchor: null, thread: thread() });
const textarea = container.querySelector("textarea") as HTMLTextAreaElement;
const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")?.set;
setter?.call(textarea, "A reply");
textarea.dispatchEvent(new Event("input", { bubbles: true }));
await vi.waitFor(() => expect(textarea.value).toBe("A reply"));
const buttons = Array.from(container.querySelectorAll("button"));
buttons.find((button) => button.textContent?.includes("Reply"))?.click();
buttons.find((button) => button.textContent?.includes("Resolve"))?.click();
await vi.waitFor(() => {
expect(mutations.reply).toHaveBeenCalledWith({ threadId: "thread-1", body: "A reply" });
expect(mutations.status).toHaveBeenCalledWith({ threadId: "thread-1", status: "resolved" });
});
});
});