fix(ui): restore chat submission on plain HTTP origins (#20308)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Operators send task replies and chat messages from the board UI.
> - Browsers can omit `crypto.randomUUID` on a plain HTTP origin.
> - The send handler calls that API before it sends the request. Its
error handler restores the draft.
> - The UI already has a UUID helper with a fallback for this case.
> - This pull request uses that helper in the task and chat send paths
and image upload state.
> - Operators can send messages and retain the existing request receipt
behavior on these origins.

## Linked Issues or Issue Description

Fixes: #15846
Refs #15495, #16090, #15135, #17081.

Related open proposals: #15937, #16522, #16947. They remain unmerged.
This change adds independent regression and browser verification. It
does not establish a cause for every intermittent send failure in those
reports.

## What Changed

- Use `createUuid` for both composer attempt IDs, both request ID
fallbacks, and image upload state.
- Test five successive sends in task and chat modes without
`randomUUID`.
- Test upload receipts, retry request identity, the next draft, and
first-message creation without that API.

## Verification

- Base: `d10c6e0e8b3005cb49d0732a670ab1a851833b01`.
- Six focused regression cases fail with the original calls. The same
cases pass with this change.
- The three affected test files pass: 506 tests.
- `pnpm --filter @paperclipai/ui typecheck`, `pnpm --filter
@paperclipai/ui build`, and `pnpm check:token-gates` pass.
- `pnpm verify` ran 460 UI files: 7,895 tests pass and one is skipped.
One CLI startup suite failed because this environment supplied empty AI
endpoint variables. That suite passes when those variables are unset.
The aggregate run also reported changed inputs, so it is not a reusable
verification pass.
- Chromium, real local UI and API, empty synthetic instance: the
original Send action sends no request and retains the draft when
`randomUUID` is absent. With the fix, five task replies, a
scheduled-task reply, a Classic reply, and five standing-chat messages
save. Request IDs are distinct and drafts clear. An image uploads and
its receipt is attached to the saved comment.
- Browser scope: loopback HTTP with `randomUUID` removed before page
code runs. This models the missing browser API. Service workers are
blocked for the fixed request-count checks. Telemetry is disabled. No
agent runs start. This does not test a remote LAN browser, provider
execution, or intermittent failures after real agent exchanges.
- Required CI and Greptile review are pending at PR creation.

## Risks

- Low risk. The change uses the existing UUID helper and keeps the send
and receipt contracts.
- Other causes of intermittent send failures may remain. This change
only addresses the reproduced missing-UUID failure.

## Model Used

- OpenAI GPT-6 (`gpt-6`), with reasoning, tool use, and code execution.
The harness does not disclose a more specific revision or context window
size.

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

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-11-13 13:31:38 -06:00
1 parent d738ed5ee4
commit bc4bc61f9c
6 files changed
+75 -8

No files matched your search

+4 -1
View File
@@ -3003,7 +3003,8 @@ describe("IssueChatThread", () => {
} finally { act(() => root.unmount()); client.clear(); }
});
it("resends an unconfirmed comment with the same request ID and keeps the next draft", async () => {
it.each(["secure context", "plain HTTP"])("resends an unconfirmed comment with the same request ID and keeps the next draft on %s", async (context) => {
if (context === "plain HTTP") vi.stubGlobal("crypto", { getRandomValues: crypto.getRandomValues.bind(crypto) });
const key = "resend-unconfirmed-comment";
let rejectSend!: (error: Error) => void;
const onAdd = vi.fn()
@@ -3026,6 +3027,7 @@ describe("IssueChatThread", () => {
type("Typed during the outage");
await act(async () => button("Send").click());
type("Next thought");
expect(onAdd).toHaveBeenCalledOnce();
await act(async () => rejectSend(new CommentSubmissionUnknownError()));
expect(container.textContent).toContain("Sending when reconnected…");
expect(JSON.parse(localStorage.getItem(`${key}:submission:v1`)!).request.body).toBe("Typed during the outage");
@@ -3038,6 +3040,7 @@ describe("IssueChatThread", () => {
expect(localStorage.getItem(`${key}:submission:v1`)).toBeNull();
} finally {
await act(async () => root.unmount());
vi.unstubAllGlobals();
}
});
+3 -2
View File
@@ -1,3 +1,4 @@
import { createUuid } from "@/lib/uuid";
import { useCurrentAccountGuard } from "../hooks/useAccountBoundMutation";
import { resolveIssueChatHumanAuthor } from "@/lib/issue-chat-human-author";
import { useCurrentWorkspaceRetry, useWorkspaceBaseRefRecovery, useWorkspaceRetry } from "./WorkspaceBaseRefRecovery";
@@ -5182,7 +5183,7 @@ const IssueChatComposer = forwardRef<
setBody(trimmed);
return;
}
attemptId = crypto.randomUUID();
attemptId = createUuid();
if (requestOwner === undefined) markRequestUnbound(attemptId);
// The exact request is stored before it is sent, so a lost response or
// an outage can resend it with the same ID instead of losing it.
@@ -6229,7 +6230,7 @@ export function IssueChatThread({
const sendComposerComment = useCallback<IssueChatThreadProps["onAdd"]>(
async (body, reopen, reassignment, attachmentIds, clientRequestId, runSettings) => {
pendingSubmitScrollRef.current = true;
clientRequestId ??= crypto.randomUUID();
clientRequestId ??= createUuid();
const attempt = beginSubmission(clientRequestId, undefined, reopen);
try {
await (runSettings
@@ -312,6 +312,65 @@ function renderComposer(props: ComponentProps<typeof TaskChatComposer>) {
}
describe("TaskChatComposer", () => {
describe("plain HTTP without randomUUID", () => {
beforeEach(() => {
vi.stubGlobal("crypto", { getRandomValues: crypto.getRandomValues.bind(crypto) });
});
afterEach(() => vi.unstubAllGlobals());
it.each([false, true])("sends repeated messages with distinct receipts (conversation=%s)", async (conversationMode) => {
const onAdd = vi.fn().mockResolvedValue(undefined);
renderComposer({ onAdd, conversationMode, workMode: "standard", draftKey: "http-repeated" });
for (let turn = 0; turn < 5; turn++) {
typeText(`Message ${turn}`);
if (turn % 2) pressKey("Enter", { metaKey: true });
else flushSync(() => sendButton().click());
await flushAsync();
expect(onAdd).toHaveBeenCalledTimes(turn + 1);
expect(onAdd.mock.calls[turn][0]).toBe(`Message ${turn}`);
expect(onAdd.mock.calls[turn][4]).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
expect(editable().textContent).toBe("");
expect(loadDraftSubmission("http-repeated")).toBeNull();
}
expect(new Set(onAdd.mock.calls.map(call => call[4])).size).toBe(5);
});
it("keeps the request identity and next draft after a lost receipt", async () => {
let rejectSend!: (error: Error) => void;
const onAdd = vi.fn()
.mockReturnValueOnce(new Promise<void>((_, reject) => { rejectSend = reject; }))
.mockResolvedValue(undefined);
renderComposer({ onAdd, workMode: "standard", draftKey: "http-retry" });
typeText("Keep this request");
await act(async () => sendButton().click());
expect(onAdd).toHaveBeenCalledOnce();
const attemptId = onAdd.mock.calls[0][4];
expect(loadDraftSubmission("http-retry")?.attemptId).toBe(attemptId);
typeText("Next draft");
await act(async () => rejectSend(new CommentSubmissionUnknownError()));
const resend = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Resend now")!;
await act(async () => resend.click());
expect(onAdd).toHaveBeenNthCalledWith(2, "Keep this request", undefined, undefined, undefined, attemptId);
expect(editable().textContent).toBe("Next draft");
expect(loadDraftSubmission("http-retry")).toBeNull();
});
it("uploads an image and submits its receipt on plain HTTP", async () => {
const onAdd = vi.fn().mockResolvedValue(undefined);
const attachmentId = "cdd72566-48f4-4996-8899-285101990a30";
const contentPath = `/api/attachments/${attachmentId}/content`;
const onAttachImage = vi.fn().mockResolvedValue({ id: attachmentId, contentPath });
renderComposer({ onAdd, onAttachImage, workMode: "standard" });
typeText("Inspect this image");
pasteFiles([new File(["synthetic image"], "sample.png", { type: "image/png" })]);
await flushAsync();
expect(onAttachImage).toHaveBeenCalledOnce();
expect(sendButton().disabled).toBe(false);
await act(async () => sendButton().click());
expect(onAdd).toHaveBeenCalledWith(`Inspect this image\n\n![sample.png](${contentPath})`, undefined, undefined, [attachmentId], expect.any(String));
});
});
it("stages creation images above the editor without changing the text", async () => {
const creation = {
value: "Before the screenshot",
@@ -1,3 +1,4 @@
import { createUuid } from "@/lib/uuid";
import { useCurrentAccountGuard } from "@/hooks/useAccountBoundMutation";
import { ComposerFileDropTarget } from "./ComposerFileDropTarget";
import { AgentAvatar } from "../AgentAvatar";
@@ -721,7 +722,7 @@ export function TaskChatComposer({
}
async function uploadImage(file: File): Promise<string> {
const id = crypto.randomUUID();
const id = createUuid();
setAttachments((prev) => [
...prev,
{
@@ -1076,7 +1077,7 @@ export function TaskChatComposer({
setBody(submittedBody);
return;
}
attemptId = crypto.randomUUID();
attemptId = createUuid();
if (requestOwner === undefined) markRequestUnbound(attemptId);
// IDs come only from this composer's upload receipts, never from parsing
// arbitrary Markdown. A removed inline image no longer selects its receipt.
+4 -2
View File
@@ -1532,6 +1532,7 @@ describe("IssueDetail", () => {
});
afterEach(async () => {
vi.unstubAllGlobals();
await act(async () => {
root.unmount();
});
@@ -2090,7 +2091,8 @@ describe("IssueDetail", () => {
});
it.each(["message", "attachment"])("creates an unused conversation only for the first %s and updates its canonical cache", async (kind) => {
it.each(["message", "attachment", "plain HTTP message"])("creates an unused conversation only for the first %s and updates its canonical cache", async (kind) => {
if (kind === "plain HTTP message") vi.stubGlobal("crypto", { getRandomValues: crypto.getRandomValues.bind(crypto) });
mockIssuesApi.markRead.mockClear();
const agent = createAgent();
const canonical = createIssue({ conversationAgentId: agent.id, conversationUserId: "user-1", conversationState: "waiting", status: "in_review" });
@@ -2108,7 +2110,7 @@ describe("IssueDetail", () => {
onAdd: (body: string) => Promise<void>;
onAttachImage: (file: File) => Promise<IssueAttachment>;
};
if (kind === "message") {
if (kind !== "attachment") {
await act(async () => { await props.onAdd("Clarify this goal"); });
expect(mockIssuesApi.addComment).toHaveBeenCalledWith(canonical.id, "Clarify this goal", undefined, undefined, undefined, expect.any(String));
expect(invalidate).toHaveBeenCalledWith({ queryKey: queryKeys.issues.comments(canonical.id) });
+2 -1
View File
@@ -1,3 +1,4 @@
import { createUuid } from "@/lib/uuid";
import { companyProjectsQuery } from "@/lib/company-projects-query";
import { NativeControllerContainmentRecovery } from "../components/IssueRecoveryActionCard";
import { useIssueIdBatches } from "@/hooks/useIssueIdBatches";
@@ -5116,7 +5117,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
assertCurrentAccount();
queryClient.setQueryData(queryKeys.issues.detail(writableIssueId), updated);
}
return issuesApi.addComment(writableIssueId, body, reopen, interrupt, attachmentIds, clientRequestId ?? crypto.randomUUID());
return issuesApi.addComment(writableIssueId, body, reopen, interrupt, attachmentIds, clientRequestId ?? createUuid());
},
onMutate: async ({ body, reopen, interrupt }) => {
// Start cache cancellation immediately but do not put it in front of the