feat(ui): keep writes durable through temporary disconnects (#17960)

<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/123/changes/paperclip/123
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - People save tasks, write documents, make decisions and send board
messages.
> - A disconnect can hide a response after the server accepts a write.
> - Recovery must keep the original account, task and request key.
> - The merged connection foundation in #15754 handles reads and shared
outage state.
> - This change adds bounded write recovery and explicit actions when
recovery stops.

## Linked Issues or Issue Description

**What happened?**

Temporary failures could lose edits, report accepted writes as failures,
or require people to copy and send input again. A retry could target a
newly selected task or account. Restoring attachments could create a
second task.

**Expected behavior**

Keep the draft, its owner and its target. Retry only operations with a
server contract that prevents duplicate writes. Verify uncertain
results. Show conflicts and permanent failures, with an explicit resend
or cancel action.

**Steps to reproduce**

1. Save a task title during an outage, then open another task before
recovery.
2. Restore a task creation that needs files, selecting those files in
another order.
3. Lose a document or decision response, then interrupt the verification
read.
4. Switch accounts while a create, upload or connected-channel
publication is pending.
5. Type and erase a new-task draft before the first account lookup
completes, then reopen it.

This PR carries the write layer from #15769 and its review fixes. It
targets master after #15754 merged. Related test cleanup #16952 already
covers the unchanged copy-link toast test; this PR does not duplicate
that work.

## What Changed

- Add bounded autosave and submit jobs for supported writes, with
pending, conflict and manual retry states. Retain admitted autosaves
after navigation and preserve newer task revisions.
- Keep each job with its original account, task and operation. First
account resolution adopts admitted startup work; a later account change
cancels old work. Remount inline and document editors when their owner
or document subject changes.
- Preserve task-creation keys and immutable request snapshots through
file reattachment. Restore generated document keys before comparing
reselected files. Reject changed requests instead of creating a second
task.
- Check the original account scope before creates and each upload. Save
successful upload receipts before stopping on an account change.
Identify attachments by content digest and metadata.
- Verify uncertain document and decision results. Replay only plain,
keyed comments automatically; combined reassignment, reopen and
run-setting changes require receipt reconciliation or cancel. Settle
each request once when a receipt races its retry.
- Scope drafts and connected-channel publication reads to their owner.
Keep unowned older records unread and unreplayed, with an explicit
confirmed discard action after Activity inspection. Preserve typing
through the first session lookup, keep erased text erased, and report
browser persistence only when storage succeeds.
- Wait for the first account lookup before sending startup status
changes or decisions. Retry failed required lookups with a fixed limit
and surface exhaustion to the original action. Preserve uncertain
comment keys on account cancellation. Check the account generation
before a comment retry calls its sender and again immediately before
POST after asynchronous preparation. Retire only that request’s
optimistic echo on completion.
- Return an ordinary comment’s accepted same-company, same-task,
same-user receipt before workspace reopening, task status changes or
wakeups. Reused keys with changed text still conflict. Complete
reference and activity records through the same finalizer for initial
sends and accepted retries. It locks the task before its comment,
matching task and company deletion, comment removal and tombstoning,
rejects removed or tombstoned comments, repairs references and inserts a
missing activity record in one transaction, and publishes after commit.
- Remove reader-only record and comment-body size caps so accepted
browser writes remain readable, including JSON-escaped comment requests
in local and session storage. Update four existing Storybook fixtures to
use owned draft keys.
- Document the write contracts and add regression and real browser
recovery coverage.

- Add the exact reviewed-save recovery regression for both composer
implementations and reloads. Align receipt completion, both comment
deletion methods and company deletion with task deletion by locking
tasks first. Cover real task and company deletion races.

## Verification

- The exact reviewed-unknown-save regression fails in all four cases on
original commit `1ed0af4186`. It passes with this PR for both composers,
before and after reload. Cancel keeps the text and uploaded receipt. The
retained draft sends, and the next message also sends. Run `pnpm exec
vitest run --project @paperclipai/ui
ui/src/components/composer-recovery.test.tsx`.
- The new real PostgreSQL task-deletion race fails with SQLSTATE `40P01`
on parent commit `f3253a00c4`. The company-deletion race also fails with
`40P01` on `e8cf0e02dd`. All six receipt tests pass after the final
lock-order fixes. They cover company deletion, task deletion, comment
removal, tombstoning, concurrent cross-task references and interrupted
reference repair. Run `pnpm exec vitest run --project
@paperclipai/server
server/src/__tests__/issue-comment-receipt-postgres.test.ts`.
- The full UI run passed 9,656 of 9,659 tests across 816 files. Three
cases failed under that run: two large-tree timeouts and one
plugin-panel assertion. All 67 tests in those two files passed in an
isolated rerun. These failures remain recorded; this does not claim a
clean full UI run.
- `pnpm -r typecheck`, `pnpm build`, token gates and map checks pass on
the final change. The local full repository test command was started,
then stopped when the delivery moved to this existing PR. Fresh PR CI
must provide the full-suite gate.
- A local Storybook walkthrough used the real rich editor. Cancel kept
the restored text, Send cleared it after the simulated save, and a new
draft enabled Send again. Storybook simulates submission; it is not
staging acceptance.
- Earlier verification on `f3253a00c4` recorded five browser journeys
for title saves, cached-task offline recovery, startup recovery,
accepted comment replay and session lookup failure. Those results remain
prior-head evidence. No new staging deployment is claimed.

- On `e8cf0e02dd`, all CI checks passed after one browser-shard rerun.
Its first failure copied page text instead of YAML in an unrelated
agent-configuration test. On final commit `35131d4380`, Greptile is 5/5
with no unresolved review threads. The first CI attempt has two failures
outside this diff: runner close-attachment suspension and
scheduled-retry teardown. The scheduled-retry file passes all 14 tests
in isolation; the isolated runner test still fails locally. The single
standard CI rerun passed both jobs, and the aggregate verification gate
passed. All CI checks are green on `35131d4380`; Apex is 5/5 on that
same commit with no unresolved findings.

## Risks

- Automatic replay requires server duplicate prevention or result
verification. Uncertain combined mutations require receipt observation
or cancel and a fresh intentional send.
- Old unowned form drafts remain stored but are not assigned to an
account. Unowned channel records can be retired after Activity
inspection; this never cancels an accepted remote update.
- Browser storage and hashing can be unavailable. Storage failure is
reported honestly. Without a digest, replay can duplicate an upload
rather than silently drop a selected file.
- Detached autosaves remain bounded and check account ownership on each
attempt. Conflicts or exhaustion retain the draft for explicit recovery.
- No schema, credential or agent permission change is included. This PR
does not claim staging deployment or original-task acceptance.

## Model Used

Anthropic Claude Opus 5.5 (`claude-opus-5-5`) produced the original
implementation with tool use. OpenAI Codex, GPT-6 family, assisted with
restoration, integration, verification and review fixes. This Codex
session does not expose its exact serving model ID 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
- [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: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Amy (Opus) <claude@users.noreply.github.com>
Co-authored-by: Dotta <bippadotta@protonmail.com>
This commit is contained in:
authored and GitHub committed 2026-10-28 10:52:06 -07:00
1 parent a2fbce9305
commit d30c8f42b8
62 files changed
+6486 -733

No files matched your search

@@ -18,6 +18,15 @@ import {
saveDraftSubmission,
} from "../../lib/composer-draft";
import { CommentSubmissionUnknownError } from "../../lib/comment-submit-result";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { queryKeys } from "../../lib/queryKeys";
import { useAccountBoundMutation } from "../../hooks/useAccountBoundMutation";
// The session lookup never answers on its own; tests set the account directly.
vi.mock("../../api/auth", async (importOriginal) => {
const actual = await importOriginal<typeof import("../../api/auth")>();
return { ...actual, authApi: { ...actual.authApi, getSession: () => new Promise(() => {}) } };
});
/**
* MDXEditor-in-jsdom weight (mirrors MarkdownEditor.test.tsx): the real editor
@@ -365,10 +374,36 @@ describe("TaskChatComposer", () => {
expect(loadDraftSubmission(key)).toBeNull();
expect(localStorage.getItem(key)).toBeNull();
render(<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key} />);
expect(container.textContent).not.toContain("couldn’t confirm");
expect(container.textContent).not.toContain("Sending when reconnected…");
expect(editable().textContent).toBe("");
});
it.each([
{ reassignment: { assigneeAgentId: "old-agent", assigneeUserId: null } },
{ runSettings: { model: "old-model" } },
{ reopen: true },
])("keeps an uncertain composite send for reconciliation without resending task changes: %j", async (changes) => {
const key = "uncertain-composite";
const attemptId = "9af8228f-0be7-45ae-a104-6fbe0af6f1d3";
saveDraft(key, "Keep the comment");
saveDraftSubmission(key, { attemptId, reviewed: false, request: { body: "Keep the comment", ...changes }, requestOwner: "user-1" });
const onAdd = vi.fn();
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
render(<QueryClientProvider client={client}><TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key} /></QueryClientProvider>);
await flushAsync();
expect(container.textContent).toContain("We couldn’t confirm whether this message was sent.");
expect(container.textContent).not.toContain("Resend now");
expect(onAdd).not.toHaveBeenCalled();
const cancel = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Cancel")!;
flushSync(() => cancel.click());
await flushAsync();
expect(editable().textContent).toBe("Keep the comment");
expect(loadDraftSubmission(key)).toBeNull();
expect(onAdd).not.toHaveBeenCalled();
client.clear();
});
it("automatically reconciles a restored submission by its server receipt, not its text", async () => {
const key = "saved-receipt";
const attemptId = "9af8228f-0be7-45ae-a104-6fbe0af6f1d3";
@@ -386,6 +421,87 @@ describe("TaskChatComposer", () => {
expect(onAdd).not.toHaveBeenCalled();
});
it("keeps the original key after account cancellation of an accepted initial send", async () => {
const key = "accepted-account-roundtrip";
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
let accepted!: () => void;
const post = vi.fn<(body: string, requestId?: string) => Promise<void>>()
.mockImplementationOnce(() => new Promise<void>(resolve => { accepted = resolve; })).mockResolvedValue(undefined);
function OwnedComposer() {
const mutation = useAccountBoundMutation({ mutationFn: ({ body, requestId }: { body: string; requestId?: string }) => post(body, requestId) });
return <TaskChatComposer draftKey={key} workMode="standard"
onAdd={(body, _reopen, _reassign, _files, requestId) => mutation.mutateAsync({ body, requestId })} />;
}
render(<QueryClientProvider client={client}><OwnedComposer /></QueryClientProvider>);
typeText("Accepted before the account changed");
pressKey("Enter", { metaKey: true });
await flushAsync();
const requestId = post.mock.calls[0][1]!;
flushSync(() => {
client.setQueryData(queryKeys.auth.session, { user: { id: "user-2" } });
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
});
accepted();
await flushAsync();
expect(loadDraftSubmission(key)?.attemptId).toBe(requestId);
expect(editable().textContent).toBe("Accepted before the account changed");
const retry = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Resend now")!;
flushSync(() => retry.click());
await flushAsync();
expect(post).toHaveBeenCalledTimes(2);
expect(post.mock.calls[1][1]).toBe(requestId);
expect(loadDraftSubmission(key)).toBeNull();
client.clear();
});
it.each([false, true])("does not retry from a stale account render (returns to original=%s)", async (returns) => {
const key = "stale-account-retry";
const attemptId = "9af8228f-0be7-45ae-a104-6fbe0af6f1d3";
saveDraft(key, "Original account text");
saveDraftSubmission(key, { attemptId, reviewed: false, request: { body: "Original account text" }, requestOwner: "user-1" });
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
const onAdd = vi.fn().mockResolvedValue(undefined);
render(<QueryClientProvider client={client}><TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key} /></QueryClientProvider>);
await flushAsync();
const resend = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Resend now")!;
flushSync(() => {
client.setQueryData(queryKeys.auth.session, { user: { id: "user-2" } });
if (returns) client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
resend.click();
});
await flushAsync();
expect(onAdd).not.toHaveBeenCalled();
expect(loadDraftSubmission(key)?.attemptId).toBe(attemptId);
client.clear();
});
it.each(["success", "rejection"])("settles a receipt before its in-flight resend %s without cutting the next draft", async (outcome) => {
const key = "receipt-and-resend";
const attemptId = "9af8228f-0be7-45ae-a104-6fbe0af6f1d3";
saveDraft(key, "First request\n\nKeep this next draft");
saveDraftSubmission(key, { attemptId, reviewed: false, nextDraftOffset: 15, request: { body: "First request" }, requestOwner: "user-1" });
let finish!: () => void;
let fail!: (error: Error) => void;
const onAdd = vi.fn(() => new Promise<void>((resolve, reject) => { finish = resolve; fail = reject; }));
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
const show = (confirmedSubmissionIds = new Set<string>()) => render(<QueryClientProvider client={client}><TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key} confirmedSubmissionIds={confirmedSubmissionIds} /></QueryClientProvider>);
show(); await flushAsync();
const resend = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Resend now")!;
flushSync(() => resend.click()); await flushAsync();
expect(onAdd).toHaveBeenCalledTimes(1);
show(new Set([attemptId])); await flushAsync();
expect(editable().textContent).toBe("Keep this next draft");
if (outcome === "success") finish(); else fail(new Error("Late rejected resend"));
await flushAsync();
expect(container.textContent).not.toContain("Late rejected resend");
expect(editable().textContent).toBe("Keep this next draft");
expect(localStorage.getItem(key)).toBe("Keep this next draft");
client.clear();
});
it("preserves the next draft when an uncertain submission is later confirmed after reload", async () => {
const key = "uncertain-with-next-draft";
let rejectSend!: (error: Error) => void;
@@ -493,7 +609,7 @@ describe("TaskChatComposer", () => {
},
);
it("fences an unknown save in memory with disabled storage until a successful explicit review and local discard", async () => {
it("keeps an unconfirmed send in memory with disabled storage and resends it with the same request ID", async () => {
const storage = vi
.spyOn(Storage.prototype, "setItem")
.mockImplementation(() => {
@@ -501,55 +617,147 @@ describe("TaskChatComposer", () => {
});
const onAdd = vi
.fn()
.mockRejectedValue(new CommentSubmissionUnknownError());
const review = vi
.fn()
.mockRejectedValueOnce(new Error("Refresh unavailable"))
.mockRejectedValueOnce(new CommentSubmissionUnknownError())
.mockResolvedValue(undefined);
try {
renderComposer({
onAdd: onAdd,
workMode: "standard",
draftKey: "storage-disabled",
onReviewConversation: review,
});
typeText("Do not replay this unknown save");
typeText("Send this exactly once");
pressKey("Enter", { metaKey: true });
await flushAsync();
await flushAsync();
expect(sendButton().disabled).toBe(true);
expect(container.textContent).toContain(
"couldn’t confirm whether this comment was saved",
);
expect(container.textContent).toContain("Sending when reconnected…");
expect(container.textContent).not.toContain("Discard draft");
pressKey("Enter", { metaKey: true });
await flushAsync();
expect(onAdd).toHaveBeenCalledTimes(1);
const reviewButton = () =>
Array.from(container.querySelectorAll("button")).find(
(button) => button.textContent === "Review conversation",
)!;
flushSync(() => reviewButton().click());
await flushAsync();
expect(container.textContent).toContain(
"Couldn’t refresh the conversation",
);
expect(container.textContent).not.toContain(
"Discard draft and start new",
);
flushSync(() => reviewButton().click());
await flushAsync();
expect(review).toHaveBeenCalledTimes(2);
const discard = Array.from(container.querySelectorAll("button")).find(
(button) => button.textContent === "Discard draft and start new",
const resend = Array.from(container.querySelectorAll("button")).find(
(button) => button.textContent === "Resend now",
)!;
flushSync(() => discard.click());
flushSync(() => resend.click());
await flushAsync();
await flushAsync();
expect(onAdd).toHaveBeenCalledTimes(2);
// Same body and same client request ID, so the server dedupes.
expect(onAdd.mock.calls[1]?.[0]).toBe(onAdd.mock.calls[0]?.[0]);
expect(onAdd.mock.calls[1]?.[4]).toBe(onAdd.mock.calls[0]?.[4]);
expect(container.textContent).not.toContain("Sending when reconnected…");
expect(editable().textContent).toBe("");
expect(onAdd).toHaveBeenCalledTimes(1);
} finally {
storage.mockRestore();
}
});
it("gives an unconfirmed send back to the editor on Cancel without resending it", async () => {
const onAdd = vi.fn().mockRejectedValue(new CommentSubmissionUnknownError());
render(<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey="cancel-pending" />);
typeText("Keep my words");
pressKey("Enter", { metaKey: true });
await flushAsync();
await flushAsync();
expect(loadDraftSubmission("cancel-pending")?.request?.body).toBe("Keep my words");
const cancel = Array.from(container.querySelectorAll("button")).find(
(button) => button.textContent === "Cancel",
)!;
flushSync(() => cancel.click());
await flushAsync();
expect(container.textContent).not.toContain("Sending when reconnected…");
expect(editable().textContent).toBe("Keep my words");
expect(loadDraftSubmission("cancel-pending")).toBeNull();
expect(sendButton().disabled).toBe(false);
expect(onAdd).toHaveBeenCalledTimes(1);
});
it("puts the text back with readable copy when a resend is rejected", async () => {
const { ApiError } = await import("../../api/client");
const onAdd = vi
.fn()
.mockRejectedValueOnce(new CommentSubmissionUnknownError())
.mockRejectedValueOnce(new ApiError("Forbidden", 403, { error: "Forbidden" }));
render(<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey="rejected-resend" />);
typeText("Rejected later");
pressKey("Enter", { metaKey: true });
await flushAsync();
await flushAsync();
const resend = Array.from(container.querySelectorAll("button")).find(
(button) => button.textContent === "Resend now",
)!;
flushSync(() => resend.click());
await flushAsync();
await flushAsync();
expect(onAdd).toHaveBeenCalledTimes(2);
expect(container.textContent).not.toContain("Sending when reconnected…");
expect(editable().textContent).toBe("Rejected later");
expect(container.textContent).toContain("Forbidden");
expect(loadDraftSubmission("rejected-resend")).toBeNull();
});
it("resends a comment sent before the session loaded once the account is known", async () => {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const onAdd = vi
.fn()
.mockRejectedValueOnce(new CommentSubmissionUnknownError())
.mockResolvedValue(undefined);
render(
<QueryClientProvider client={client}>
<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey="owner-late" />
</QueryClientProvider>,
);
typeText("Sent before the session");
pressKey("Enter", { metaKey: true });
await flushAsync();
await flushAsync();
// Until the account is known the send cannot be replayed.
const resendButton = () => Array.from(container.querySelectorAll("button")).find(
(button) => button.textContent === "Resend now",
);
expect(resendButton()).toBeUndefined();
act(() => {
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
});
await flushAsync();
await flushAsync();
expect(loadDraftSubmission("owner-late")?.requestOwner).toBe("user-1");
expect(container.textContent).toContain("Sending when reconnected…");
flushSync(() => resendButton()!.click());
await flushAsync();
await flushAsync();
expect(onAdd).toHaveBeenCalledTimes(2);
expect(onAdd.mock.calls[1]?.[4]).toBe(onAdd.mock.calls[0]?.[4]);
expect(container.textContent).not.toContain("Sending when reconnected…");
client.clear();
});
it("never binds an account to a stored send that has no owner", async () => {
const key = "owner-unknown-stored";
saveDraft(key, "Stored without owner");
saveDraftSubmission(key, {
attemptId: "baf8228f-0be7-45ae-a104-6fbe0af6f1d3",
reviewed: false,
request: { body: "Stored without owner" },
});
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
const onAdd = vi.fn();
render(
<QueryClientProvider client={client}>
<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key} />
</QueryClientProvider>,
);
await flushAsync();
expect(Array.from(container.querySelectorAll("button")).some(
(button) => button.textContent === "Resend now",
)).toBe(false);
expect(loadDraftSubmission(key)?.requestOwner).toBeUndefined();
expect(onAdd).not.toHaveBeenCalled();
client.clear();
});
it("restores an in-flight submission as uncertain only for its exact task key", async () => {
const key = "uncertain-task-one";
const attemptId = "9af8228f-0be7-45ae-a104-6fbe0af6f1d3";
@@ -608,6 +816,29 @@ describe("TaskChatComposer", () => {
expect(onAttachImage).toHaveBeenCalledTimes(1);
});
it("keeps a failed upload and retries it only when asked", async () => {
const id = "9af8228f-0be7-45ae-a104-6fbe0af6f1d3";
const { ApiError } = await import("../../api/client");
const onAttachImage = vi
.fn()
.mockRejectedValueOnce(new ApiError("Unavailable", 503, { error: "tenant_app_unavailable" }))
.mockResolvedValue({ id, contentPath: `/api/attachments/${id}/content`, originalFilename: "notes.txt" });
render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" onAttachImage={onAttachImage} />);
pasteFiles([new File(["bytes"], "notes.txt", { type: "text/plain" })]);
await flushAsync();
expect(container.textContent).toContain("Paperclip is restarting or updating");
expect(container.textContent).not.toContain("tenant_app_unavailable");
await new Promise((resolve) => setTimeout(resolve, 50));
expect(onAttachImage).toHaveBeenCalledTimes(1);
const retry = container.querySelector<HTMLButtonElement>('button[aria-label="Retry notes.txt"]')!;
flushSync(() => retry.click());
await flushAsync();
expect(onAttachImage).toHaveBeenCalledTimes(2);
expect(container.querySelector('button[aria-label="Retry notes.txt"]')).toBeNull();
expect(container.textContent).not.toContain("Paperclip is restarting or updating");
expect(sendButton().disabled).toBe(false);
});
it("holds submission while an inline image upload is pending and binds its receipt", async () => {
const onAdd = vi.fn().mockResolvedValue(undefined);
const id = "5e5f9946-c706-4785-8988-d4d6f0f499ab";
+144 -82
View File
@@ -1,6 +1,8 @@
import { useCurrentAccountGuard } from "@/hooks/useAccountBoundMutation";
import { AgentAvatar } from "../AgentAvatar";
import {
useEffect,
useId,
useRef,
useState,
type ChangeEvent,
@@ -18,14 +20,22 @@ import {
saveDraft,
saveDraftAttachments,
loadDraftSubmission,
replayableRequest,
saveDraftSubmission,
clearDraftSubmission,
settleDraftSubmission,
type ComposerDraftSubmission,
type ComposerSendRequest,
} from "@/lib/composer-draft";
import { CommentSubmissionUnknownError } from "@/lib/comment-submit-result";
import { classifySendFailure, type SendOutcome } from "@/lib/pending-send";
import { describeError } from "@/api/errors";
import { useAutoResend } from "@/hooks/useDurableSubmit";
import { useDraftOwner } from "@/hooks/useDraftOwner";
import { useRequestOwnerBinding } from "@/hooks/useRequestOwnerBinding";
import { PendingSendNotice } from "@/components/PendingSendNotice";
import {
ArrowUp,
RotateCw,
Square,
ChevronDown,
CircleHelp,
@@ -110,6 +120,8 @@ interface TaskChatComposerProps {
details?: ReactNode;
contextBar?: ReactNode;
submitDisabled?: boolean;
/** Lock the editor, e.g. while a submitted create waits to resend. */
readOnly?: boolean;
privacy?: { private: boolean; inherited?: string; onChange: (value: boolean) => void };
onSelectFiles: (files: File[]) => void;
runSettings: ComposerRunSettings | null;
@@ -149,7 +161,6 @@ interface TaskChatComposerProps {
mobile?: boolean;
/** Storage key used to restore, persist, and clear this task's text draft. */
draftKey?: string;
onReviewConversation?: () => Promise<void>;
/** When set, the main composer temporarily edits this queued message. */
queuedEdit?: { commentId: string; body: string; stale?: boolean } | null;
onSaveQueuedEdit?: (commentId: string, body: string) => Promise<void>;
@@ -325,6 +336,11 @@ type ComposerAttachment = {
error?: string;
/** Set once uploaded; the submit path appends `[name](contentPath)` lines. */
contentPath?: string;
/**
* The picked file, kept after a failed upload so the chip can offer Retry.
* Uploads are not deduped by the server, so they never resend on their own.
*/
file?: File;
};
type QueuedEditBackup = {
@@ -403,7 +419,6 @@ export function TaskChatComposer({
issueStatus,
mobile = false,
draftKey,
onReviewConversation,
queuedEdit = null,
onSaveQueuedEdit,
onCancelQueuedEdit,
@@ -419,7 +434,6 @@ export function TaskChatComposer({
const [localBody, setBody] = useState(() => (draftKey ? loadDraft(draftKey) : ""));
const body = creation ? creation.value : localBody;
const [submitting, setSubmitting] = useState(false);
const [reviewError, setReviewError] = useState(false);
const [uncertainSubmission, setUncertainSubmission] =
useState<ComposerDraftSubmission | null>(() =>
draftKey ? loadDraftSubmission(draftKey) : null,
@@ -482,12 +496,20 @@ export function TaskChatComposer({
const editorRef = useRef<MarkdownEditorRef>(null);
const bodyRef = useRef(body);
bodyRef.current = body;
// Only the account that made a request may replay it.
const draftOwner = useDraftOwner();
const isCurrentAccount = useCurrentAccountGuard();
const pendingDraftRef = useRef<{
draftKey: string;
attemptId: string;
submittedBody: string;
submittedAttachmentIds: string[];
request: ComposerSendRequest;
requestOwner?: string;
} | null>(null);
const markRequestUnbound = useRequestOwnerBinding({
draftKey, owner: draftOwner, uncertainSubmission, setUncertainSubmission, pendingDraftRef,
});
function changeBody(value: string) {
bodyRef.current = value;
if (creation) {
@@ -507,6 +529,8 @@ export function TaskChatComposer({
attemptId: pending.attemptId, reviewed: false,
nextDraftOffset: pending.submittedBody.length + (value ? 2 : 0),
submittedAttachmentIds: pending.submittedAttachmentIds,
request: pending.request,
requestOwner: pending.requestOwner,
});
}
const draftTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -721,7 +745,8 @@ export function TaskChatComposer({
? {
...item,
status: "error",
error: err instanceof Error ? err.message : "Upload failed",
error: describeError(err, { action: "upload the file" }).body,
file,
}
: item,
),
@@ -776,7 +801,8 @@ export function TaskChatComposer({
? {
...item,
status: "error",
error: err instanceof Error ? err.message : "Upload failed",
error: describeError(err, { action: "upload the file" }).body,
file,
}
: item,
),
@@ -784,6 +810,14 @@ export function TaskChatComposer({
}
}
/** Retry a failed upload from its kept file; only ever on an explicit click. */
function retryUpload(attachment: ComposerAttachment) {
const file = attachment.file;
if (!file) return;
setAttachments((prev) => prev.filter((item) => item.id !== attachment.id));
void attachPickedFile(file);
}
/** Images picked from the + button go inline at the caret, like paste/drop. */
async function attachPickedFile(file: File) {
if (!file.type.startsWith("image/")) {
@@ -895,7 +929,7 @@ export function TaskChatComposer({
try {
await creation.onSubmit(bodyRef.current, pendingMode, runSettings);
} catch (error) {
setActionError(error instanceof Error ? error.message : "Failed to create task. Try again.");
setActionError(describeError(error, { action: "create the task" }).body);
} finally {
submittingRef.current = false;
setSubmitting(false);
@@ -1022,6 +1056,8 @@ export function TaskChatComposer({
setBody("");
setSubmitting(true);
let attemptId: string | null = null;
let request: ComposerSendRequest | null = null;
const requestOwner = draftOwner;
try {
if (queuedEdit) {
if (!onSaveQueuedEdit) return;
@@ -1039,10 +1075,7 @@ export function TaskChatComposer({
return;
}
attemptId = crypto.randomUUID();
if (draftKey) {
saveDraft(draftKey, submittedBody);
saveDraftSubmission(draftKey, { attemptId, reviewed: false });
}
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.
const attachmentIds = [
@@ -1059,8 +1092,19 @@ export function TaskChatComposer({
.map((item) => item.attachmentId!),
),
];
// 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.
request = {
body: fullBody,
...(reopen === undefined ? {} : { reopen }),
...(reassignment ? { reassignment } : {}),
...(attachmentIds.length ? { attachmentIds } : {}),
...(runSettings ? { runSettings: runSettings as unknown as Record<string, unknown> } : {}),
};
if (draftKey) {
pendingDraftRef.current = { draftKey, attemptId, submittedBody, submittedAttachmentIds: attachmentIds };
saveDraft(draftKey, submittedBody);
saveDraftSubmission(draftKey, { attemptId, reviewed: false, request, requestOwner });
pendingDraftRef.current = { draftKey, attemptId, submittedBody, submittedAttachmentIds: attachmentIds, request, requestOwner };
changeBody(bodyRef.current);
}
if (runSettings) {
@@ -1084,11 +1128,15 @@ export function TaskChatComposer({
} catch (error) {
if (mountedTaskKey.current !== draftKey) return;
const nextDraft = bodyRef.current;
if (attemptId && error instanceof CommentSubmissionUnknownError) {
// Not delivered, or not known to be: keep it and resend with the same
// ID when the connection allows. The server dedupes by that ID.
if (attemptId && request && classifySendFailure(error) === "pending") {
const uncertain = {
attemptId, reviewed: false,
nextDraftOffset: submittedBody.length + (nextDraft ? 2 : 0),
submittedAttachmentIds: submittedAttachments.flatMap(item => item.attachmentId ? [item.attachmentId] : []),
request,
requestOwner,
};
setUncertainSubmission(uncertain);
if (draftKey && loadDraftSubmission(draftKey)?.attemptId === attemptId)
@@ -1113,45 +1161,77 @@ export function TaskChatComposer({
}
}
useEffect(() => {
if (!uncertainSubmission || !confirmedSubmissionIds?.has(uncertainSubmission.attemptId)) return;
const nextDraft = uncertainSubmission.nextDraftOffset === undefined
? "" : bodyRef.current.slice(uncertainSubmission.nextDraftOffset);
if (draftKey) settleDraftSubmission(draftKey, uncertainSubmission.attemptId, nextDraft);
/** A confirmed receipt for the retained send: drop its text, keep any next draft. */
const settledSubmissionIds = useRef(new Set<string>());
function settleUncertainSubmission(submission: ComposerDraftSubmission) {
const settlementKey = JSON.stringify([draftKey, submission.attemptId]);
if (settledSubmissionIds.current.has(settlementKey)) return;
settledSubmissionIds.current.add(settlementKey);
const nextDraft = submission.nextDraftOffset === undefined
? "" : bodyRef.current.slice(submission.nextDraftOffset);
if (draftKey) settleDraftSubmission(draftKey, submission.attemptId, nextDraft);
setUncertainSubmission(null);
setActionError(null);
bodyRef.current = nextDraft;
setBody(nextDraft);
const submittedIds = uncertainSubmission.submittedAttachmentIds;
const submittedIds = submission.submittedAttachmentIds;
setAttachments(current => submittedIds
? current.filter(item => !item.attachmentId || !submittedIds.includes(item.attachmentId))
: []);
}, [confirmedSubmissionIds, draftKey, uncertainSubmission]);
async function reviewUncertainSubmission() {
if (!uncertainSubmission) return;
setReviewError(false);
try {
if (!onReviewConversation) throw new Error("Review unavailable");
await onReviewConversation();
if (mountedTaskKey.current !== draftKey) return;
const reviewed = { ...uncertainSubmission, reviewed: true };
setUncertainSubmission(reviewed);
if (
draftKey &&
loadDraftSubmission(draftKey)?.attemptId === reviewed.attemptId
)
saveDraftSubmission(draftKey, reviewed);
} catch {
setReviewError(true);
}
}
function discardUncertainDraft() {
if (!uncertainSubmission?.reviewed) return;
if (draftKey) clearDraft(draftKey, uncertainSubmission.attemptId);
bodyRef.current = "";
setBody("");
setAttachments([]);
useEffect(() => {
if (!uncertainSubmission || !confirmedSubmissionIds?.has(uncertainSubmission.attemptId)) return;
settleUncertainSubmission(uncertainSubmission);
}, [confirmedSubmissionIds, draftKey, uncertainSubmission]);
async function resendUncertainSubmission(): Promise<SendOutcome> {
if (!isCurrentAccount()) return "pending";
const submission = uncertainSubmission;
const request = replayableRequest(submission, draftOwner);
if (!submission || !request || !onAdd) return "rejected";
const taskKey = draftKey;
const args = [
request.body,
request.reopen,
request.reassignment,
request.attachmentIds,
submission.attemptId,
] as const;
try {
if (request.runSettings) await onAdd(...args, request.runSettings as unknown as ComposerRunSettings);
else await onAdd(...args);
} catch (error) {
if (!isCurrentAccount()) return "pending";
const failure = classifySendFailure(error);
if (settledSubmissionIds.current.has(JSON.stringify([taskKey, submission.attemptId]))) return failure;
if (failure === "rejected") {
// A definitive answer: the text is already back in the editor.
if (taskKey) clearDraftSubmission(taskKey, submission.attemptId);
if (mountedTaskKey.current === taskKey) {
setUncertainSubmission(null);
setActionError(describeError(error, { action: "send this message" }).body);
}
}
return failure;
}
if (mountedTaskKey.current === taskKey) settleUncertainSubmission(submission);
else if (taskKey) settleDraftSubmission(taskKey, submission.attemptId);
return "sent";
}
const resendSourceId = useId();
const autoResend = useAutoResend({
sourceId: `task-chat-composer:${resendSourceId}`,
active: Boolean(replayableRequest(uncertainSubmission, draftOwner)) && !submitting,
resend: resendUncertainSubmission,
});
/** Stop resending; the text stays in the editor to edit or send again. */
function cancelUncertainSubmission() {
if (!uncertainSubmission) return;
settledSubmissionIds.current.add(JSON.stringify([draftKey, uncertainSubmission.attemptId]));
if (draftKey) clearDraftSubmission(draftKey, uncertainSubmission.attemptId);
setUncertainSubmission(null);
}
@@ -1290,43 +1370,16 @@ export function TaskChatComposer({
>
{creation?.header}
{uncertainSubmission ? (
<div
role="alert"
className="mb-3 space-y-2 rounded-md border border-border bg-muted p-3 text-sm"
>
<p>
We couldn’t confirm whether this comment was saved. It may already
be in the conversation. Review it before starting another draft.
</p>
<Button
type="button"
variant="outline"
size="sm"
onClick={reviewUncertainSubmission}
>
Review conversation
</Button>
{reviewError ? (
<p>Couldn’t refresh the conversation. Try reviewing it again.</p>
) : null}
{uncertainSubmission.reviewed ? (
<>
<p>
Discarding this draft does not remove any saved comment or
uploaded file.
</p>
<Button
type="button"
variant="outline"
size="sm"
onClick={discardUncertainDraft}
>
Discard draft and start new
</Button>
</>
) : null}
</div>
) : null}
<PendingSendNotice
className="mb-3"
noun="message"
persisted={Boolean(draftKey && loadDraftSubmission(draftKey)?.attemptId === uncertainSubmission.attemptId && replayableRequest(loadDraftSubmission(draftKey), draftOwner))}
resending={autoResend.resending}
stalled={autoResend.stalled}
onResendNow={replayableRequest(uncertainSubmission, draftOwner) ? autoResend.resendNow : undefined}
onCancel={cancelUncertainSubmission}
/>
) : null}
{!takeoverVisible && (pendingTakeover || takeover) ? (
<button
type="button"
@@ -1359,7 +1412,7 @@ export function TaskChatComposer({
? (disabledReason ?? "Composer disabled")
: effectivePlaceholder
}
readOnly={disabled || !!uncertainSubmission || Boolean(creation && submitting)}
readOnly={disabled || !!uncertainSubmission || Boolean(creation && (submitting || creation.readOnly))}
mentions={mentions}
actionCommands={creation ? [] : conversationMode ? [{
id: "action:new", kind: "action", command: "new", name: "New session",
@@ -1434,6 +1487,15 @@ export function TaskChatComposer({
</AttachmentDescription>
</AttachmentContent>
<AttachmentActions>
{attachment.status === "error" && attachment.file ? (
<AttachmentAction
aria-label={`Retry ${attachment.name}`}
disabled={!!uncertainSubmission}
onClick={() => retryUpload(attachment)}
>
<RotateCw aria-hidden />
</AttachmentAction>
) : null}
<AttachmentAction
aria-label={`Remove ${attachment.name}`}
disabled={!!uncertainSubmission}