From bb253c6a995162d31b9fa3cbde400795190fefc4 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:49:57 -0600 Subject: [PATCH] fix(ui): save new tasks in the background (#20831) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip lets people manage AI agents and their tasks. > - The New task composer is the entry point for new work. > - The composer currently waits for the server to save a task before it closes. > - A slow request prevents the person from starting the next task. > - This change closes the composer as soon as it keeps the submitted request. > - Separate request records keep retries and files safe while another draft is open. > - The person can submit the next task without waiting for the first save. ## Linked Issues or Issue Description **What happened?** The New task composer stays open until task creation and file uploads finish. A slow save blocks the next task. **Expected behavior** Enter closes the composer at once. The save continues in the background. A failed save restores the request. A later draft stays intact. **Steps to reproduce** 1. Open New task and enter a request. 2. Delay the create response. 3. Submit the request. The current composer stays open until the response arrives. **Paperclip version or commit** Reproduced on source commit `a4e89288ec`. **Deployment mode** Board UI built from source. The save behavior does not depend on the server deployment mode. Related transport work: #13428. The open PR and issue searches did not find a duplicate for background New task saves. ## What Changed - Add an account-scoped queue around the existing durable submit hook. Keep each request and creation key before closing the composer. Send queued requests in order. - Keep submitted draft settings and files separate from the next draft. Resume keyed requests after a reload. Keep legacy recovery records readable. - Reopen a failed draft when the composer is free. If another draft is open, show a retry action beside it. An earlier receipt cannot clear the later draft or cause late navigation. - Add regression tests for slow saves, consecutive tasks, rejections, reloads, file ownership, and account lookup. Update the product and development docs. ## Verification - Red/green: the slow-response regression failed before the fix because the composer did not close. It passes after the fix. A second red/green case proves that missing files from an earlier task cannot change the next draft's parent or goal. - Final focused run: `pnpm exec vitest run ui/src/hooks/useBackgroundSubmitQueue.test.tsx ui/src/components/NewIssueDialog.test.tsx ui/src/hooks/useDurableSubmit.test.tsx ui/src/hooks/useStagedIssueFiles.test.tsx ui/src/lib/pending-send.test.ts ui/src/components/task-chat/TaskChatComposer.test.tsx` — 6 files and 316 tests passed on Linux with Node 25.9.0. - `pnpm --filter @paperclipai/ui typecheck` passed. `git diff --check` passed. - An earlier `pnpm verify` run selected 544 test files and overlapped the last edits. It reported the new account-lookup file-scoping assertion before the worker guard was complete. The stale run was stopped. The final focused run passes that case. Do not use the earlier run as proof for the final revision. - Store each queued request in its own browser entry. A submission or receipt in one tab cannot erase another tab's queued tasks. A red/green two-tab regression proves recovery after reload. Legacy queue migration also passes. - Follow-up recovery checks: a saved rejection cannot replace a newer saved draft or a fresh launch. Edits survive close, reopen, and reload. A retry keeps its original hidden workspace context and request key. The new regressions failed before the fixes and pass after them. - Updated the branch from `master`. This includes the SDK pin repair in #20834 and the span test repair in #21149, which address the two original CI failures. The SDK input drift check now reports no stale pins. - CI must provide broad checks for the final commit. Browser and release suites were not run; this change does not modify those suites. The dependency preflight installed packages and built the shared and plugin SDK outputs. Its later Runner step could not run because Cargo is absent in this UI workspace. ## Risks - Requests now close the composer before the server confirms a save. A failed request must stay visible and recoverable. The tests cover rejection, retry, reload, and a newer draft. - The queue and file snapshots use browser storage. If storage is unavailable, requests remain in memory and a reload can require the files again. - Server creation, authorization, and duplicate-request handling retain their existing APIs. No database migration is required. - The queue sends requests in order. An uncertain first save can delay later server saves while the person continues to compose. ## Model Used - OpenAI GPT-6 through Codex, with reasoning, shell tools, and code execution. The exact service model ID and context window are not exposed in this run. ## 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 --- DESIGN.md | 6 + doc/DEVELOPING.md | 11 + doc/PRODUCT.md | 6 + ui/src/components/NewIssueDialog.test.tsx | 330 ++++++++++++++++- ui/src/components/NewIssueDialog.tsx | 344 ++++++++++++------ .../hooks/useBackgroundSubmitQueue.test.tsx | 91 +++++ ui/src/hooks/useBackgroundSubmitQueue.ts | 163 +++++++++ 7 files changed, 829 insertions(+), 122 deletions(-) create mode 100644 ui/src/hooks/useBackgroundSubmitQueue.test.tsx create mode 100644 ui/src/hooks/useBackgroundSubmitQueue.ts diff --git a/DESIGN.md b/DESIGN.md index afb31fde548..707a877b75e 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -53,6 +53,12 @@ The New task form opens immediately. Load its code with the board and fill agent and project choices in place as their requests finish. Keep text entered while those requests are pending. +Submitting a new task closes and clears its composer immediately. Save the +submitted text, settings, and files separately while the request runs in the +background. A failed save reopens that draft with an actionable error. If the +person has started another draft, keep that draft and offer recovery for the +failed request. A background receipt must not clear or close a later draft. + ## Mobile navigation and text fields The fixed bottom navigation uses an opaque surface so scrolling content cannot diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 8ebe43e238d..6091d53f375 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -4863,6 +4863,17 @@ under its original key; it is never relabelled as a provider refusal. Legacy unowned form drafts remain in browser storage but are not restored into another account. Storybook fixtures seed the same account-specific keys. +New-task submissions use `useBackgroundSubmitQueue` around `useDurableSubmit`. +The account-scoped queue retains each request's original key and draft snapshot +before the composer closes. The worker sends requests in order. A request with an +uncertain receipt retains its key; a rejection restores the submitted draft or +offers a retry beside a newer draft. Submitted files use separate IndexedDB keys +for the account, company, and request, so finishing an older save cannot remove +newer files. Each submitted request has its own local-storage entry. A write or +receipt in one tab cannot replace another tab's queued requests. Legacy queue +arrays migrate to separate entries before the shared array is removed. Legacy +single-request recovery records remain readable. + New-task staged file bytes are stored in IndexedDB for the account and company. Writes merge the selected files with the current saved list in one read/write transaction. Removal and successful creation delete only the files that the diff --git a/doc/PRODUCT.md b/doc/PRODUCT.md index 196180e4593..82397c60a51 100644 --- a/doc/PRODUCT.md +++ b/doc/PRODUCT.md @@ -152,6 +152,12 @@ adds a new line. Settings → Experimental → **Command/Ctrl+Enter to Submit** restores the previous behavior, where Enter adds a new line and Command/Ctrl+Enter submits. +New-task submission closes the composer immediately and saves in the background. +The person can start another task while earlier requests are pending. A failed +save restores its submitted draft and files. If another draft is open, it stays +intact and offers a retry for the saved request. Each request retains its own +creation key through retries and reloads. + ### Routine responsibility The routine Overview shows its responsible user beside Default agent. People with diff --git a/ui/src/components/NewIssueDialog.test.tsx b/ui/src/components/NewIssueDialog.test.tsx index 6ab66bf031e..500039b5577 100644 --- a/ui/src/components/NewIssueDialog.test.tsx +++ b/ui/src/components/NewIssueDialog.test.tsx @@ -31,6 +31,7 @@ const dialogState = vi.hoisted(() => ({ newIssueOpen: true, newIssueDefaults: {} as Record, closeNewIssue: vi.fn(), + openNewIssue: vi.fn(), })); const dialogContentState = vi.hoisted(() => ({ @@ -384,6 +385,7 @@ describe("NewIssueDialog", () => { dialogState.newIssueOpen = true; dialogState.newIssueDefaults = {}; dialogState.closeNewIssue.mockReset(); + dialogState.openNewIssue.mockReset(); dialogContentState.onEscapeKeyDown = null; dialogContentState.onPointerDownOutside = null; toastState.pushToast.mockReset(); @@ -1507,7 +1509,7 @@ describe("NewIssueDialog", () => { { name: "description only", defaults: { description: "Pending task" } }, { name: "explicit title", defaults: { title: "Pending task" } }, { name: "sub-task", defaults: { description: "Pending task", parentId: "parent-1", parentTitle: "Parent task" } }, - ])("keeps the composer layout stable while submitting a task with $name", async ({ defaults }) => { + ])("dismisses immediately while saving a task with $name", async ({ defaults }) => { mockIssuesApi.create.mockReturnValue(new Promise(() => undefined)); dialogState.newIssueDefaults = defaults; @@ -1518,7 +1520,6 @@ describe("NewIssueDialog", () => { .find((button) => button.getAttribute("data-testid") === "task-chat-composer-send"); expect(submitButton).not.toBeUndefined(); const composer = container.querySelector(".paperclip-task-chat-composer")!; - const sections = Array.from(composer.children); await act(async () => { submitButton!.dispatchEvent(new MouseEvent("click", { bubbles: true })); @@ -1526,9 +1527,9 @@ describe("NewIssueDialog", () => { await flush(); expect(mockIssuesApi.create).toHaveBeenCalledTimes(1); - expect(Array.from(composer.children)).toEqual(sections); - expect(submitButton?.querySelector(".animate-spin")).not.toBeNull(); - expect(submitButton?.getAttribute("aria-busy")).toBe("true"); + expect(dialogState.closeNewIssue).toHaveBeenCalledOnce(); + expect(submitButton?.querySelector(".animate-spin")).toBeNull(); + expect(submitButton?.getAttribute("aria-busy")).not.toBe("true"); expect(container.textContent).not.toContain("Creating issue"); act(() => root.unmount()); @@ -1542,7 +1543,7 @@ describe("NewIssueDialog", () => { .find((button) => button.getAttribute("aria-label") === "Create task")!; act(() => submit().click()); - await waitForAssertion(() => expect(dialogState.closeNewIssue).toHaveBeenCalledTimes(1)); + await waitForAssertion(() => expect(toastState.pushToast).toHaveBeenCalledOnce()); const firstPayload = mockIssuesApi.create.mock.calls[0][1]; expect(firstPayload).toMatchObject({ title: "Connect Circleback through Composio", @@ -1561,7 +1562,7 @@ describe("NewIssueDialog", () => { act(() => root.render()); await flush(); act(() => submit().click()); - await waitForAssertion(() => expect(dialogState.closeNewIssue).toHaveBeenCalledTimes(2)); + await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledTimes(2)); const secondPayload = mockIssuesApi.create.mock.calls[1][1]; expect(secondPayload.title).toBe(firstPayload.title); expect(secondPayload.allowDuplicate).toBe(true); @@ -1578,7 +1579,7 @@ describe("NewIssueDialog", () => { await flush(); act(() => Array.from(container.querySelectorAll("button")) .find(button => button.getAttribute("aria-label") === "Create task")!.click()); - await waitForAssertion(() => expect(dialogState.closeNewIssue).toHaveBeenCalledTimes(1)); + await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledOnce()); expect(mockIssuesApi.create.mock.calls[0][1].idempotencyKey) .toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); act(() => root.unmount()); @@ -1594,7 +1595,7 @@ describe("NewIssueDialog", () => { const submit = Array.from(container.querySelectorAll("button")) .find((button) => button.getAttribute("aria-label") === "Create task")!; act(() => submit.click()); - await waitForAssertion(() => expect(dialogState.closeNewIssue).toHaveBeenCalledTimes(1)); + await waitForAssertion(() => expect(toastState.pushToast).toHaveBeenCalledOnce()); expect(mockIssuesApi.create.mock.calls[0][1]).not.toHaveProperty("navigateOnCreate"); if (navigateOnCreate) { expect(navigateMock).toHaveBeenCalledExactlyOnceWith("/PAP/issues/PAP-2"); @@ -1627,7 +1628,8 @@ describe("NewIssueDialog", () => { act(() => submit().click()); await waitForAssertion(() => expect(container.textContent).toContain("Request failed")); const firstPayload = mockIssuesApi.create.mock.calls[0][1]; - expect(dialogState.closeNewIssue).not.toHaveBeenCalled(); + expect(dialogState.closeNewIssue).toHaveBeenCalledOnce(); + expect(dialogState.openNewIssue).toHaveBeenCalledOnce(); expect(toastState.pushToast).not.toHaveBeenCalled(); expect(navigateMock).not.toHaveBeenCalled(); @@ -1973,7 +1975,7 @@ describe("NewIssueDialog", () => { expect(mutation?.state.status).toMatch(/^(success|error)$/); }); expect(mockIssuesApi.uploadAttachment).toHaveBeenCalledTimes(during === "create" ? 0 : 1); - expect(dialogState.closeNewIssue).not.toHaveBeenCalled(); + expect(dialogState.closeNewIssue).toHaveBeenCalledOnce(); expect(localStorage.getItem("paperclip:issue-draft:pending-create:user-1")).toContain(key); expect(container.textContent).not.toContain("Account A in-flight task"); } finally { act(() => root.unmount()); queryClient.clear(); } @@ -2541,6 +2543,304 @@ describe("NewIssueDialog", () => { act(() => root.unmount()); }); + it("closes and accepts a second task before the first create returns", async () => { + let finishFirst!: (value: unknown) => void; + mockIssuesApi.create.mockImplementationOnce(() => new Promise(resolve => { finishFirst = resolve; })); + dialogState.newIssueDefaults = { description: "First task" }; + const { root, queryClient } = renderDialog(container); + await flush(); + await act(async () => { container.querySelector('[aria-label="Create task"]')!.click(); }); + await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledOnce()); + expect(dialogState.closeNewIssue).toHaveBeenCalledOnce(); + + dialogState.newIssueDefaults = { description: "Second task" }; + act(() => { root.render(); }); + await flush(); + const send = container.querySelector('[aria-label="Create task"]')!; + expect(send.disabled).toBe(false); + await act(async () => { send.click(); }); + expect(dialogState.closeNewIssue).toHaveBeenCalledTimes(2); + + dialogState.newIssueDefaults = { description: "Third task still being written" }; + act(() => { root.render(); }); + await flush(); + await act(async () => { finishFirst({ id: "first", identifier: "PAP-10", companyId: "company-1" }); }); + await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledTimes(2)); + await flush(); + expect(mockIssuesApi.create.mock.calls[1][1].description).toBe("Second task"); + expect(mockIssuesApi.create.mock.calls[1][1].idempotencyKey).not.toBe(mockIssuesApi.create.mock.calls[0][1].idempotencyKey); + expect(container.querySelector('textarea[aria-label="Describe a task…"]')?.value).toBe("Third task still being written"); + expect(dialogState.closeNewIssue).toHaveBeenCalledTimes(2); + act(() => root.unmount()); + }); + + it("keeps the next draft and its image when a background create fails", async () => { + let rejectFirst!: (error: Error) => void; + mockIssuesApi.create.mockImplementationOnce(() => new Promise((_resolve, reject) => { rejectFirst = reject; })); + dialogState.newIssueDefaults = { description: "Failed first task", navigateOnCreate: true }; + const { root, queryClient } = renderDialog(container); + await flush(); + await act(async () => { container.querySelector('[aria-label="Create task"]')!.click(); }); + await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledOnce()); + const key = mockIssuesApi.create.mock.calls[0][1].idempotencyKey; + dialogState.newIssueDefaults = { description: "Next draft" }; + act(() => { root.render(); }); + await flush(); + const input = container.querySelector('input[type="file"]')!; + const nextFile = new File(["next"], "next.png", { type: "image/png" }); + Object.defineProperty(input, "files", { configurable: true, value: [nextFile] }); + await act(async () => { input.dispatchEvent(new Event("change", { bubbles: true })); }); + await act(async () => { rejectFirst(new Error("Save failed")); }); + await waitForAssertion(() => expect(container.textContent).toContain("Save failed")); + expect(container.querySelector('textarea[aria-label="Describe a task…"]')?.value).toBe("Next draft"); + expect(container.querySelector('img[alt="next.png"]')).not.toBeNull(); + expect(dialogState.openNewIssue).not.toHaveBeenCalled(); + const retry = Array.from(container.querySelectorAll("button")).find(button => button.textContent?.startsWith("Retry saved task:"))!; + await act(async () => { retry.click(); }); + await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledTimes(2)); + expect(mockIssuesApi.create.mock.calls[1][1]).toMatchObject({ description: "Failed first task", idempotencyKey: key }); + await flush(); + expect(container.querySelector('textarea[aria-label="Describe a task…"]')?.value).toBe("Next draft"); + expect(container.querySelector('img[alt="next.png"]')).not.toBeNull(); + expect(mockIssuesApi.uploadAttachment).not.toHaveBeenCalled(); + expect(navigateMock).not.toHaveBeenCalled(); + expect(dialogState.closeNewIssue).toHaveBeenCalledOnce(); + act(() => root.unmount()); + }); + + it("restores two queued tasks and their separate files after a reload", async () => { + mockIssuesApi.create.mockImplementationOnce(() => new Promise(() => {})); + mockIssuesApi.uploadAttachment.mockResolvedValue({}); + dialogState.newIssueDefaults = { description: "First queued task" }; + const first = renderDialog(container); + const files = [new File(["first"], "same.png", { type: "image/png" }), new File(["second"], "same.png", { type: "image/png" })]; + for (let index = 0; index < 2; index++) { + if (index) { + dialogState.newIssueDefaults = { description: "Second queued task" }; + act(() => { first.root.render(); }); + } + await flush(); + const input = container.querySelector('input[type="file"]')!; + Object.defineProperty(input, "files", { configurable: true, value: [files[index]] }); + await act(async () => { input.dispatchEvent(new Event("change", { bubbles: true })); }); + await act(async () => { container.querySelector('[aria-label="Create task"]')!.click(); }); + await flush(); + } + const queuedKeys = Object.keys(localStorage).filter(key => key.startsWith("paperclip:issue-draft:pending-create:queue:user-1:request:")); + const queued = queuedKeys.map(key => JSON.parse(localStorage.getItem(key)!)); + expect(queued.map((item: { payload: { data: { description: string } } }) => item.payload.data.description)).toEqual(["First queued task", "Second queued task"]); + act(() => first.root.unmount()); + first.queryClient.clear(); + dialogState.newIssueOpen = false; + dialogState.newIssueDefaults = {}; + const reloaded = renderDialog(container); + await waitForAssertion(() => expect(mockIssuesApi.uploadAttachment).toHaveBeenCalledTimes(2)); + expect(mockIssuesApi.create.mock.calls.slice(1).map(call => call[1].idempotencyKey)).toEqual(queued.map((item: { idempotencyKey: string }) => item.idempotencyKey)); + expect(mockIssuesApi.uploadAttachment.mock.calls.map(call => call[2])).toEqual(files); + await waitForAssertion(() => expect(queuedKeys.map(key => localStorage.getItem(key))).toEqual([null, null])); + expect(dialogState.openNewIssue).not.toHaveBeenCalled(); + expect(dialogState.closeNewIssue).toHaveBeenCalledTimes(2); + act(() => reloaded.root.unmount()); + }); + + it("reopens a rejected task with its settings and files after a reload", async () => { + mockIssuesApi.create.mockRejectedValueOnce(new Error("Save was rejected")); + dialogState.newIssueDefaults = { description: "Restore this request", parentId: "parent-1", goalId: "goal-1", workMode: "planning", assigneeAgentId: "agent-1" }; + const first = renderDialog(container); + await flush(); + const file = new File(["reference"], "reference.png", { type: "image/png" }); + const input = container.querySelector('input[type="file"]')!; + Object.defineProperty(input, "files", { configurable: true, value: [file] }); + await act(async () => { input.dispatchEvent(new Event("change", { bubbles: true })); }); + await act(async () => { container.querySelector('[aria-label="Create sub-task"]')!.click(); }); + await waitForAssertion(() => expect(dialogState.openNewIssue).toHaveBeenCalledOnce()); + const key = mockIssuesApi.create.mock.calls[0][1].idempotencyKey; + act(() => first.root.unmount()); + first.queryClient.clear(); + dialogState.newIssueDefaults = {}; + dialogState.openNewIssue.mockClear(); + const reloaded = renderDialog(container); + await waitForAssertion(() => expect(container.querySelector('img[alt="reference.png"]')).not.toBeNull()); + expect(container.querySelector('textarea[aria-label="Describe a task…"]')?.value).toBe("Restore this request"); + expect(container.textContent).toContain("Save was rejected"); + expect(mockIssuesApi.create).toHaveBeenCalledOnce(); + await act(async () => { container.querySelector('[aria-label="Create sub-task"]')!.click(); }); + await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledTimes(2)); + expect(mockIssuesApi.create.mock.calls[1][1]).toMatchObject({ parentId: "parent-1", goalId: "goal-1", workMode: "planning", idempotencyKey: key, assigneeAgentId: "agent-1" }); + act(() => reloaded.root.unmount()); + }); + + it.each([false, true])("keeps a newer saved draft when a rejected create reloads (open: %s)", async (open) => { + mockIssuesApi.create.mockRejectedValueOnce(new Error("Earlier save failed")); + dialogState.newIssueDefaults = { description: "Earlier request" }; + const first = renderDialog(container); + await flush(); + await act(async () => { container.querySelector('[aria-label="Create task"]')!.click(); }); + await waitForAssertion(() => expect(dialogState.openNewIssue).toHaveBeenCalledOnce()); + act(() => first.root.unmount()); + first.queryClient.clear(); + const nextDraft = { + description: "Newer saved work", title: "", status: "backlog", priority: "high", + assigneeValue: "", reviewerValue: "", approverValue: "", projectId: "project-1", + assigneeModelOverride: "", assigneeThinkingEffort: "", assigneeChrome: false, workMode: "planning", + }; + localStorage.setItem("paperclip:issue-draft:user-1", JSON.stringify(nextDraft)); + dialogState.newIssueDefaults = {}; + dialogState.newIssueOpen = open; + dialogState.openNewIssue.mockClear(); + const reloaded = renderDialog(container); + await flush(); + expect(JSON.parse(localStorage.getItem("paperclip:issue-draft:user-1")!).description).toBe("Newer saved work"); + expect(dialogState.openNewIssue).not.toHaveBeenCalled(); + if (!open) { + dialogState.newIssueOpen = true; + act(() => reloaded.root.render()); + await flush(); + } + expect(container.querySelector('textarea[aria-label="Describe a task…"]')?.value).toBe("Newer saved work"); + expect(container.textContent).toContain("Retry saved task:"); + act(() => reloaded.root.unmount()); + }); + + it("keeps a fresh launch when a recovered draft reloads", async () => { + mockIssuesApi.create.mockRejectedValueOnce(new Error("Save failed")); + dialogState.newIssueDefaults = { description: "Old recovered text" }; + const first = renderDialog(container); + await flush(); + await act(async () => { container.querySelector('[aria-label="Create task"]')!.click(); }); + await waitForAssertion(() => expect(dialogState.openNewIssue).toHaveBeenCalledOnce()); + act(() => first.root.unmount()); + first.queryClient.clear(); + dialogState.openNewIssue.mockClear(); + dialogState.newIssueDefaults = { description: "Fresh launch", parentId: "new-parent" }; + const reloaded = renderDialog(container); + await flush(); + expect(dialogState.openNewIssue).not.toHaveBeenCalled(); + expect(container.querySelector('textarea[aria-label="Describe a task…"]')?.value).toBe("Fresh launch"); + expect(container.textContent).toContain("Retry saved task:"); + act(() => reloaded.root.unmount()); + }); + + it("keeps edits when a recovered task is closed, reopened, and reloaded", async () => { + mockIssuesApi.create.mockRejectedValueOnce(new Error("Save failed")); + dialogState.newIssueDefaults = { description: "Original recovered text" }; + const { root, queryClient } = renderDialog(container); + const render = () => root.render(); + await flush(); + await act(async () => { container.querySelector('[aria-label="Create task"]')!.click(); }); + await waitForAssertion(() => expect(dialogState.openNewIssue).toHaveBeenCalledOnce()); + await typeTextareaValue(container.querySelector('textarea[aria-label="Describe a task…"]')!, "Edited recovery text"); + await act(async () => { await new Promise(resolve => setTimeout(resolve, 850)); }); + dialogState.newIssueOpen = false; + dialogState.newIssueDefaults = {}; + act(render); + dialogState.newIssueOpen = true; + act(render); + await flush(); + expect(container.querySelector('textarea[aria-label="Describe a task…"]')?.value).toBe("Edited recovery text"); + act(() => root.unmount()); + queryClient.clear(); + const reloaded = renderDialog(container); + await flush(); + expect(container.querySelector('textarea[aria-label="Describe a task…"]')?.value).toBe("Edited recovery text"); + act(() => reloaded.root.unmount()); + }); + + it("uses fresh launch defaults after a recovered task is closed", async () => { + mockIssuesApi.create.mockRejectedValueOnce(new Error("Save failed")); + dialogState.newIssueDefaults = { description: "Old recovered task", parentId: "old-parent", goalId: "old-goal" }; + const { root, queryClient } = renderDialog(container); + const render = () => root.render(); + await flush(); + await act(async () => { container.querySelector('[aria-label="Create sub-task"]')!.click(); }); + await waitForAssertion(() => expect(dialogState.openNewIssue).toHaveBeenCalledOnce()); + const oldKey = mockIssuesApi.create.mock.calls[0][1].idempotencyKey; + dialogState.newIssueOpen = false; + dialogState.newIssueDefaults = {}; + act(render); + dialogState.newIssueOpen = true; + dialogState.newIssueDefaults = { description: "New launch", parentId: "new-parent", goalId: "new-goal" }; + act(render); + await flush(); + expect(container.querySelector('textarea[aria-label="Describe a task…"]')?.value).toBe("New launch"); + await act(async () => { container.querySelector('[aria-label="Create sub-task"]')!.click(); }); + await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledTimes(2)); + expect(mockIssuesApi.create.mock.calls[1][1]).toMatchObject({ description: "New launch", parentId: "new-parent", goalId: "new-goal" }); + expect(mockIssuesApi.create.mock.calls[1][1].idempotencyKey).not.toBe(oldKey); + act(() => root.unmount()); + }); + + it("keeps hidden workspace launch context when retrying a rejected create", async () => { + mockIssuesApi.create.mockRejectedValueOnce(new Error("Save failed")); + mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: true }); + dialogState.newIssueDefaults = { + description: "Workspace task", projectId: "project-1", projectWorkspaceId: "source-context", executionWorkspaceId: "workspace-context", + }; + const { root, queryClient } = renderDialog(container, ["workspaces.isolation"]); + await flush(); + await act(async () => { container.querySelector('[aria-label="Create task"]')!.click(); }); + await waitForAssertion(() => expect(dialogState.openNewIssue).toHaveBeenCalledOnce()); + const original = mockIssuesApi.create.mock.calls[0][1]; + // The real dialog clears launch defaults when it closes and reopens. + dialogState.newIssueDefaults = {}; + act(() => root.render()); + await flush(); + await act(async () => { container.querySelector('[aria-label="Create task"]')!.click(); }); + await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledTimes(2)); + expect(mockIssuesApi.create.mock.calls[1][1]).toMatchObject({ + idempotencyKey: original.idempotencyKey, projectWorkspaceId: "source-context", + executionWorkspaceId: "workspace-context", executionWorkspacePreference: "reuse_existing", + }); + act(() => root.unmount()); + }); + + it("keeps the newer parent context when an earlier restored task has missing files", async () => { + mockIssuesApi.create.mockImplementationOnce(() => new Promise(() => {})); + dialogState.newIssueDefaults = { description: "Original task", parentId: "old-parent", goalId: "old-goal" }; + const first = renderDialog(container); + await flush(); + const input = container.querySelector('input[type="file"]')!; + Object.defineProperty(input, "files", { configurable: true, value: [new File(["image"], "missing.png", { type: "image/png" })] }); + await act(async () => { input.dispatchEvent(new Event("change", { bubbles: true })); }); + await act(async () => { container.querySelector('[aria-label="Create sub-task"]')!.click(); }); + await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledOnce()); + const originalKey = mockIssuesApi.create.mock.calls[0][1].idempotencyKey; + act(() => first.root.unmount()); + first.queryClient.clear(); + storedFiles.clear(); + dialogState.newIssueDefaults = { description: "Newer task", parentId: "new-parent", goalId: "new-goal" }; + const reloaded = renderDialog(container); + await waitForAssertion(() => expect(container.textContent).toContain("missing.png")); + expect(container.querySelector('textarea[aria-label="Describe a task…"]')?.value).toBe("Newer task"); + await act(async () => { container.querySelector('[aria-label="Create sub-task"]')!.click(); }); + await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledTimes(2)); + expect(mockIssuesApi.create.mock.calls[1][1]).toMatchObject({ description: "Newer task", parentId: "new-parent", goalId: "new-goal" }); + expect(mockIssuesApi.create.mock.calls[1][1].idempotencyKey).not.toBe(originalKey); + act(() => reloaded.root.unmount()); + }); + + it("accepts a task before account lookup and binds its queued files to the resolved account", async () => { + let finishSession!: (value: unknown) => void; + mockAuthApi.getSession.mockImplementationOnce(() => new Promise(resolve => { finishSession = resolve; })); + mockIssuesApi.uploadAttachment.mockResolvedValue({}); + dialogState.newIssueDefaults = { description: "Submitted before account lookup" }; + const { root } = renderDialog(container); + await flush(); + const file = new File(["image"], "reference.png", { type: "image/png" }); + const input = container.querySelector('input[type="file"]')!; + Object.defineProperty(input, "files", { configurable: true, value: [file] }); + await act(async () => { input.dispatchEvent(new Event("change", { bubbles: true })); }); + await act(async () => { container.querySelector('[aria-label="Create task"]')!.click(); }); + expect(dialogState.closeNewIssue).toHaveBeenCalledOnce(); + expect(mockIssuesApi.create).not.toHaveBeenCalled(); + expect([...storedFiles.keys()]).toEqual([]); + await act(async () => { finishSession({ user: { id: "user-1" } }); }); + await waitForAssertion(() => expect(mockIssuesApi.uploadAttachment).toHaveBeenCalledWith("company-1", "issue-2", file)); + expect(mockIssuesApi.create.mock.calls[0][1].description).toBe("Submitted before account lookup"); + expect([...storedFiles.keys()].every(key => JSON.parse(key)[0] === "user-1")).toBe(true); + act(() => root.unmount()); + }); + it("retains a failed creation draft and allows retry through the composer", async () => { mockIssuesApi.create.mockRejectedValueOnce(new Error("Service unavailable")); dialogState.newIssueDefaults = { description: "Keep this request for retry" }; @@ -2550,9 +2850,11 @@ describe("NewIssueDialog", () => { await act(async () => { send.click(); }); await waitForAssertion(() => expect(container.querySelector('[role="alert"]')?.textContent).toContain("Service unavailable")); expect(container.querySelector('textarea[aria-label="Describe a task…"]')?.value).toBe("Keep this request for retry"); - expect(dialogState.closeNewIssue).not.toHaveBeenCalled(); - await act(async () => { send.click(); }); - await waitForAssertion(() => expect(dialogState.closeNewIssue).toHaveBeenCalledOnce()); + expect(dialogState.closeNewIssue).toHaveBeenCalledOnce(); + expect(dialogState.openNewIssue).toHaveBeenCalledOnce(); + await act(async () => { container.querySelector('[aria-label="Create task"]')!.click(); }); + await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledTimes(2)); + expect(dialogState.closeNewIssue).toHaveBeenCalledTimes(2); expect(mockIssuesApi.create).toHaveBeenCalledTimes(2); act(() => root.unmount()); }); diff --git a/ui/src/components/NewIssueDialog.tsx b/ui/src/components/NewIssueDialog.tsx index 62bc012474d..f55c57a1971 100644 --- a/ui/src/components/NewIssueDialog.tsx +++ b/ui/src/components/NewIssueDialog.tsx @@ -44,14 +44,14 @@ import { mergeComposerRunSettings, type ComposerRunSettings } from "./task-chat/ import { useSidebar } from "../context/SidebarContext"; import { InlineBanner } from "./InlineBanner"; import { PendingSendNotice } from "./PendingSendNotice"; -import { useDurableSubmit } from "../hooks/useDurableSubmit"; +import { useBackgroundSubmitQueue } from "../hooks/useBackgroundSubmitQueue"; import { describeError, type ErrorDescription } from "../api/errors"; -import { clearPendingSend, pendingSendKeyFor, readPendingSend, writePendingSend, PendingSendAccountChangedError } from "../lib/pending-send"; +import { clearPendingSend, pendingSendKeyFor, readPendingSend, writePendingSend, PendingSendAccountChangedError, type PendingSend } from "../lib/pending-send"; import { useDraftOwner, useDraftOwnerReader } from "../hooks/useDraftOwner"; import { InlineEntitySelector, type InlineEntityOption } from "./InlineEntitySelector"; import { getTrustPreset } from "../lib/trust-policy-ui"; import { useStagedIssueFiles } from "../hooks/useStagedIssueFiles"; -import type { StagedIssueFile } from "../lib/staged-issue-files"; +import { readStagedIssueFiles, writeStagedIssueFiles, type StagedIssueFile } from "../lib/staged-issue-files"; import { isImageAttachment } from "./task-chat/task-chat-attachments"; const DRAFT_KEY = "paperclip:issue-draft"; @@ -62,7 +62,7 @@ const PENDING_CREATE_KEY = "paperclip:issue-draft:pending-create"; * The create request keeps file names for reconciliation. File bytes are stored * separately in the account- and company-scoped browser draft. */ -type PendingCreate = { fingerprint: string; data: Record; stagedFileNames?: string[] }; +type PendingCreate = { fingerprint: string; data: Record; stagedFileNames?: string[]; draft?: IssueDraft; requiresOriginalFiles?: boolean }; function isPendingCreate(value: unknown): value is PendingCreate { if (!value || typeof value !== "object" || Array.isArray(value)) return false; @@ -71,6 +71,8 @@ function isPendingCreate(value: unknown): value is PendingCreate { typeof row.fingerprint === "string" && !!row.data && typeof row.data === "object" && !Array.isArray(row.data) && typeof (row.data as Record).companyId === "string" && + (row.requiresOriginalFiles === undefined || typeof row.requiresOriginalFiles === "boolean") && + (row.draft === undefined || (isRecord(row.draft) && typeof row.draft.title === "string" && typeof row.draft.description === "string")) && (row.stagedFileNames === undefined || (Array.isArray(row.stagedFileNames) && row.stagedFileNames.every((name) => typeof name === "string"))) ); @@ -181,6 +183,7 @@ function useVisualViewportLayout(enabled: boolean) { } interface IssueDraft { + pendingCreateKey?: string; isPrivate?: boolean; title: string; description: string; @@ -447,7 +450,7 @@ export function NewIssueDialog() { function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) { const { visible: workspaceIsolationControlsVisible } = useWorkspaceIsolationControls(); - const { newIssueOpen, newIssueDefaults: sharedDefaults, closeNewIssue } = useDialog(); + const { newIssueOpen, newIssueDefaults: sharedDefaults, closeNewIssue, openNewIssue } = useDialog(); const newIssueDefaults = useMemo(() => ignoreDefaults ? {} as typeof sharedDefaults : sharedDefaults, [ignoreDefaults, sharedDefaults]); const readOwner = useDraftOwnerReader(); const active = useRef(true); @@ -494,14 +497,23 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) // sent or cancelled, whatever the files and fields look like when resubmitted. const createRequestRef = useRef<{ fingerprint: string; idempotencyKey: string; recovering?: boolean; payload?: PendingCreate } | null>(null); const draftOwner = useDraftOwner(); + const [recoveredCreate, setRecoveredCreate] = useState | null>(null); + const recoveryDefaultsRef = useRef(null); + const visibleRequestKey = useRef(null); + const navigationRequestKey = useRef(null); + useEffect(() => { if (newIssueOpen) navigationRequestKey.current = null; }, [newIssueOpen, newIssueDefaults]); + const submittedFileWrites = useRef(new Map>()); const { files: stagedFiles, setFiles: setStagedFiles, restoring: filesRestoring, error: filesStorageError } = useStagedIssueFiles(draftOwner, effectiveCompanyId); - const [restoredLaunch, setRestoredLaunch] = useState<{ owner: string | undefined; parentId?: string; goalId?: string } | null>(null); + const [restoredLaunch, setRestoredLaunch] = useState<({ owner: string | undefined } & Pick) | null>(null); const savedLaunch = restoredLaunch?.owner === draftOwner ? restoredLaunch : null; const parentId = savedLaunch ? savedLaunch.parentId : newIssueDefaults.parentId; const goalId = savedLaunch ? savedLaunch.goalId : newIssueDefaults.goalId; const restoreLaunch = (payload: PendingCreate) => setRestoredLaunch({ owner: draftOwner, ...(typeof payload.data.parentId === "string" ? { parentId: payload.data.parentId } : {}), ...(typeof payload.data.goalId === "string" ? { goalId: payload.data.goalId } : {}), + ...(typeof payload.data.projectId === "string" ? { projectId: payload.data.projectId } : {}), + ...(typeof payload.data.projectWorkspaceId === "string" ? { projectWorkspaceId: payload.data.projectWorkspaceId } : {}), + ...(typeof payload.data.executionWorkspaceId === "string" ? { executionWorkspaceId: payload.data.executionWorkspaceId } : {}), }); const awaitingFilesKey = draftOwner !== undefined ? pendingSendKeyFor(CREATE_AWAITING_FILES_KEY, draftOwner) : null; @@ -629,9 +641,9 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) }); assertVerifiedOwner(); - return { issue, companyId, failures, navigateOnCreate }; + return { issue, companyId, failures, navigateOnCreate, requestKey: data.idempotencyKey }; }, - onSuccess: ({ issue, companyId, failures, navigateOnCreate }) => { + onSuccess: ({ issue, companyId, failures, navigateOnCreate, requestKey }) => { assertCurrentOwner(); trackRecentProject(issue.projectId ?? "", companyId); if (issue.assigneeAgentId) trackRecentAssignee(issue.assigneeAgentId, companyId); @@ -642,7 +654,6 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) queryClient.invalidateQueries({ queryKey: queryKeys.issues.listTouchedByMe(companyId) }); queryClient.invalidateQueries({ queryKey: queryKeys.issues.listUnreadTouchedByMe(companyId) }); queryClient.invalidateQueries({ queryKey: queryKeys.sidebarBadges(companyId) }); - if (draftTimer.current) clearTimeout(draftTimer.current); const prefix = (companies.find((company) => company.id === companyId)?.issuePrefix ?? "").trim(); const issueRef = issue.identifier ?? issue.id; const openIssueAction = prefix @@ -662,19 +673,13 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) action: openIssueAction, }); } - clearDraft(draftOwner); - reset(); - closeNewIssue(); - if (navigateOnCreate) navigate(openIssueAction?.href ?? `/issues/${issueRef}`); + if (navigateOnCreate && navigationRequestKey.current === requestKey) navigate(openIssueAction?.href ?? `/issues/${issueRef}`); }, }); // Issue create is keyed: the server replays the original issue for a known // idempotency key, so an outage or a lost response resends safely. const stagedFilesByKey = useRef(new Map()); - // The composer shows a rejection of the first attempt; later (automatic or - // Resend now) rejections show here. - const firstAttemptKey = useRef(null); const [resendError, setResendError] = useState(null); // Once the account is known, a create still waiting for its files keeps its // key and asks for the files again. @@ -692,15 +697,67 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) const names = awaiting.payload.stagedFileNames; if (names?.length) setResendError((current) => current ?? stagedFilesMissingDescription(names)); }, [awaitingFilesKey]); - const durableCreate = useDurableSubmit({ + const stagedFilesStorageKey = (key: string, companyId: unknown) => JSON.stringify([draftOwner, companyId, "submitted-task", key]); + const restoreBackgroundCreate = (pending: PendingSend, error: ErrorDescription | null) => { + if (!active.current || readOwner() !== draftOwner) return; + if (visibleRequestKey.current === pending.idempotencyKey) { + setResendError(error); + return; + } + // Queue recovery can run before the form's initialization effect. Inspect + // persisted text and launch defaults as well as the mounted field refs. + const savedDraft = loadDraft(draftOwner); + const sameDraft = savedDraft?.pendingCreateKey === pending.idempotencyKey; + const differentLaunch = (["title", "description", "parentId", "goalId", "projectId"] as const).some(key => + newIssueDefaults[key] !== undefined && (key === "title" || key === "description" + ? newIssueDefaults[key]?.trim() !== String(pending.payload.data[key] ?? "").trim() + : newIssueDefaults[key] !== pending.payload.data[key])); + const hasOtherDraft = differentLaunch || (!sameDraft && (titleRef.current.trim() || descriptionRef.current.trim() + || savedDraft?.title.trim() || savedDraft?.description.trim())); + if (pending.payload.data.companyId !== effectiveCompanyId || hasOtherDraft) { + pushToast({ title: "A task could not be saved", body: "Open New task to recover the saved request.", tone: "warn" }); + return; + } + if (pending.payload.draft) { + if (draftTimer.current) clearTimeout(draftTimer.current); + visibleRequestKey.current = pending.idempotencyKey; + setRecoveredCreate(pending); + recoveryDefaultsRef.current = newIssueDefaults; + createRequestRef.current = { fingerprint: pending.payload.fingerprint, idempotencyKey: pending.idempotencyKey, payload: pending.payload, + recovering: pending.payload.requiresOriginalFiles || (createRequestRef.current?.idempotencyKey === pending.idempotencyKey && createRequestRef.current.recovering) }; + const files = stagedFilesByKey.current.get(pending.idempotencyKey); + if (!files && pending.payload.stagedFileNames?.length) { + void readStagedIssueFiles(stagedFilesStorageKey(pending.idempotencyKey, pending.payload.data.companyId)).then(saved => { + if (active.current && visibleRequestKey.current === pending.idempotencyKey) setStagedFiles(saved); + }).catch(() => {}); + } + restoreLaunch(pending.payload); + if (draftOwner !== undefined) saveDraft(draftOwner, { ...(sameDraft ? savedDraft : pending.payload.draft), pendingCreateKey: pending.idempotencyKey }); + setStagedFiles(stagedFilesByKey.current.get(pending.idempotencyKey) ?? []); + openNewIssue(); + } + setResendError(error); + }; + const durableCreate = useBackgroundSubmitQueue({ sourceId: "new-issue-dialog", storageKey: PENDING_CREATE_KEY, isPayload: isPendingCreate, action: "create the task", send: async (payload, idempotencyKey) => { - const stagedFiles = stagedFilesByKey.current.get(idempotencyKey); + await submittedFileWrites.current.get(idempotencyKey); + let stagedFiles = stagedFilesByKey.current.get(idempotencyKey); + if (stagedFiles?.length && payload.draft && !submittedFileWrites.current.has(idempotencyKey)) { + await writeStagedIssueFiles(stagedFilesStorageKey(idempotencyKey, payload.data.companyId), stagedFiles, []).catch(() => {}); + } + if (!stagedFiles && payload.draft && payload.stagedFileNames?.length) { + stagedFiles = await readStagedIssueFiles(stagedFilesStorageKey(idempotencyKey, payload.data.companyId)).catch(() => []); + if (!active.current) throw new PendingSendAccountChangedError(); + if (stagedFiles.length !== payload.stagedFileNames.length) stagedFiles = undefined; + else stagedFilesByKey.current.set(idempotencyKey, stagedFiles); + } // Never create a restored task without the files it was submitted with. if (!stagedFiles && payload.stagedFileNames?.length) { + payload.requiresOriginalFiles = true; throw new StagedFilesMissingError(payload.stagedFileNames); } const result = await createIssue.mutateAsync({ @@ -708,12 +765,24 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) stagedFiles: stagedFiles ?? [], idempotencyKey, }); + if (payload.draft && stagedFiles?.length) { + await writeStagedIssueFiles(stagedFilesStorageKey(idempotencyKey, payload.data.companyId), [], stagedFiles.map(file => file.id)).catch(() => {}); + } stagedFilesByKey.current.delete(idempotencyKey); + submittedFileWrites.current.delete(idempotencyKey); clearCreateUploadReceipts(idempotencyKey); return result; }, + onSent: (_result, pending) => { + if (visibleRequestKey.current !== pending.idempotencyKey) return; + if (draftTimer.current) clearTimeout(draftTimer.current); + clearDraft(draftOwner); + reset(); + closeNewIssue(); + }, + onAttention: restoreBackgroundCreate, onRejected: (error, description, pending) => { - if (error instanceof StagedFilesMissingError) { + if (error instanceof StagedFilesMissingError && !pending.payload.draft) { // Reattaching the same files resubmits under the original key, so a // create that already reached the server is replayed, not duplicated. createRequestRef.current = { @@ -725,11 +794,14 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) restoreLaunch(pending.payload); if (awaitingFilesKey) writePendingSend(awaitingFilesKey, pending); } - if (pending.idempotencyKey !== firstAttemptKey.current) setResendError(description); + if (!pending.payload.draft || visibleRequestKey.current === pending.idempotencyKey) setResendError(description); }, }); // A create restored after reload without its files cannot be sent; say so // now rather than after the first resend delay. Nothing reaches the network. + const visiblePending = durableCreate.pending && (!durableCreate.pending.payload.draft || visibleRequestKey.current === durableCreate.pending.idempotencyKey) + ? durableCreate.pending : null; + const submittingRecoveredCreate = Boolean(visiblePending && durableCreate.status === "sending"); const pendingCreate = durableCreate.pending; const { resendNow: resendCreateNow } = durableCreate; useEffect(() => { @@ -738,6 +810,22 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) } }, [pendingCreate, resendCreateNow]); + function discardCreate(idempotencyKey: string, payload?: PendingCreate) { + durableCreate.discard(idempotencyKey); + const files = stagedFilesByKey.current.get(idempotencyKey); + const write = submittedFileWrites.current.get(idempotencyKey); + stagedFilesByKey.current.delete(idempotencyKey); + submittedFileWrites.current.delete(idempotencyKey); + clearCreateUploadReceipts(idempotencyKey); + if (draftOwner !== undefined && payload?.draft && payload.stagedFileNames?.length) { + const storageKey = stagedFilesStorageKey(idempotencyKey, payload.data.companyId); + void Promise.resolve(write).then(async () => { + const saved = files ?? await readStagedIssueFiles(storageKey); + await writeStagedIssueFiles(storageKey, [], saved.map(file => file.id)); + }).catch(() => {}); + } + } + // Debounced draft saving const scheduleSave = useCallback((draft: IssueDraft) => { if (draftOwner === undefined && (unboundFormDraft.current || draft.title.trim() || draft.description.trim())) unboundFormDraft.current = draft; @@ -765,6 +853,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) const nextTitle = overrides.title ?? titleRef.current; const nextDescription = overrides.description ?? descriptionRef.current; scheduleSave({ + pendingCreateKey: visibleRequestKey.current ?? undefined, title: nextTitle, description: nextDescription, status, @@ -812,6 +901,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) const handleDescriptionChange = useCallback( (nextDescription: string) => { + navigationRequestKey.current = null; descriptionRef.current = nextDescription; setDescription(nextDescription); @@ -845,6 +935,61 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) queueDraftSave, ]); + function restoreSubmittedDraft(draft: IssueDraft, defaults: typeof newIssueDefaults = {}) { + defaultAssigneePendingRef.current = false; + defaultProjectPendingRef.current = false; + const nextWorkMode = isIssueWorkMode(draft.workMode) ? draft.workMode : "standard"; + const restoredProjectId = defaults.projectId ?? draft.projectId; + const restoredProject = orderedProjects.find((project) => project.id === restoredProjectId); + const hasExplicitProjectWorkspaceId = defaults.projectWorkspaceId !== undefined; + const hasExplicitExecutionWorkspaceId = defaults.executionWorkspaceId !== undefined; + const hasExplicitExecutionWorkspaceMode = defaults.executionWorkspaceMode !== undefined; + setIsPrivate(draft.isPrivate ?? false); + setIssueText(draft.title, draft.description); + setComposerSettings(draft.composerSettings ?? null); + setStatus(draft.status || "todo"); + setPriority(draft.priority); + setAssigneeValue( + defaults.assigneeAgentId || defaults.assigneeUserId + ? assigneeValueFromSelection(defaults) + : (draft.assigneeValue ?? draft.assigneeId ?? ""), + ); + setReviewerValue(draft.reviewerValue ?? ""); + setApproverValue(draft.approverValue ?? ""); + + setWatchdogAgentId(draft.watchdogAgentId ?? ""); + setWatchdogInstructions(draft.watchdogInstructions ?? ""); + + setProjectId(restoredProjectId); + setProjectWorkspaceId( + hasExplicitProjectWorkspaceId + ? (defaults.projectWorkspaceId ?? "") + : (draft.projectWorkspaceId ?? defaultProjectWorkspaceIdForProject(restoredProject)), + ); + setAssigneeModelLane(draft.assigneeModelLane ?? "primary"); + setAssigneeModelOverride(draft.assigneeModelOverride ?? ""); + setAssigneeThinkingEffort(draft.assigneeThinkingEffort ?? ""); + setAssigneeChrome(draft.assigneeChrome ?? false); + setExecutionWorkspaceMode( + hasExplicitExecutionWorkspaceId || hasExplicitExecutionWorkspaceMode + ? defaultExecutionWorkspaceModeForIssueDefaults(defaults, restoredProject) + : (draft.executionWorkspaceMode ?? + (draft.useIsolatedExecutionWorkspace + ? "isolated_workspace" + : defaultExecutionWorkspaceModeForProject(restoredProject))), + ); + setWorkMode(nextWorkMode); + setSelectedExecutionWorkspaceId( + hasExplicitExecutionWorkspaceId + ? (defaults.executionWorkspaceId ?? "") + : (draft.selectedExecutionWorkspaceId ?? ""), + ); + executionWorkspaceDefaultProjectId.current = + hasExplicitProjectWorkspaceId || hasExplicitExecutionWorkspaceId || draft.projectWorkspaceId || restoredProject + ? restoredProjectId || null + : null; + } + // Restore draft or apply defaults when dialog opens useEffect(() => { if (!newIssueOpen) { @@ -853,7 +998,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) defaultProjectPendingRef.current = false; return; } - const initializationKey = `${draftOwner ?? "unknown"}:${effectiveCompanyId ?? ""}:${JSON.stringify(newIssueDefaults)}`; + const initializationKey = `${draftOwner ?? "unknown"}:${effectiveCompanyId ?? ""}:${JSON.stringify(newIssueDefaults)}:${recoveredCreate?.idempotencyKey ?? ""}`; if (initializationKeyRef.current === initializationKey) return; initializationKeyRef.current = initializationKey; if (draftTimer.current) { @@ -862,6 +1007,16 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) } executionWorkspaceDefaultProjectId.current = null; + // A later explicit launch starts its own draft. A plain reopen restores + // the saved fields below, including edits made after the first recovery. + if (recoveredCreate && newIssueDefaults !== recoveryDefaultsRef.current + && Object.keys(newIssueDefaults).length > 0) { + setRecoveredCreate(null); + visibleRequestKey.current = null; + createRequestRef.current = null; + setRestoredLaunch(null); + setResendError(null); + } if (draftOwner !== undefined && unboundFormDraft.current) { if (unboundFormDraft.current.title.trim() || unboundFormDraft.current.description.trim()) saveDraft(draftOwner, unboundFormDraft.current); @@ -929,58 +1084,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) ? defaultProjectId || null : null; } else if (draft && (draft.title.trim() || draft.description.trim())) { - defaultAssigneePendingRef.current = false; - defaultProjectPendingRef.current = false; - const nextWorkMode = isIssueWorkMode(draft.workMode) ? draft.workMode : "standard"; - const restoredProjectId = newIssueDefaults.projectId ?? draft.projectId; - const restoredProject = orderedProjects.find((project) => project.id === restoredProjectId); - const hasExplicitProjectWorkspaceId = newIssueDefaults.projectWorkspaceId !== undefined; - const hasExplicitExecutionWorkspaceId = newIssueDefaults.executionWorkspaceId !== undefined; - const hasExplicitExecutionWorkspaceMode = newIssueDefaults.executionWorkspaceMode !== undefined; - setIsPrivate(draft.isPrivate ?? false); - setIssueText(draft.title, draft.description); - setComposerSettings(draft.composerSettings ?? null); - setStatus(draft.status || "todo"); - setPriority(draft.priority); - setAssigneeValue( - newIssueDefaults.assigneeAgentId || newIssueDefaults.assigneeUserId - ? assigneeValueFromSelection(newIssueDefaults) - : (draft.assigneeValue ?? draft.assigneeId ?? ""), - ); - setReviewerValue(draft.reviewerValue ?? ""); - setApproverValue(draft.approverValue ?? ""); - - setWatchdogAgentId(draft.watchdogAgentId ?? ""); - setWatchdogInstructions(draft.watchdogInstructions ?? ""); - - setProjectId(restoredProjectId); - setProjectWorkspaceId( - hasExplicitProjectWorkspaceId - ? (newIssueDefaults.projectWorkspaceId ?? "") - : (draft.projectWorkspaceId ?? defaultProjectWorkspaceIdForProject(restoredProject)), - ); - setAssigneeModelLane(draft.assigneeModelLane ?? "primary"); - setAssigneeModelOverride(draft.assigneeModelOverride ?? ""); - setAssigneeThinkingEffort(draft.assigneeThinkingEffort ?? ""); - setAssigneeChrome(draft.assigneeChrome ?? false); - setExecutionWorkspaceMode( - hasExplicitExecutionWorkspaceId || hasExplicitExecutionWorkspaceMode - ? defaultExecutionWorkspaceModeForIssueDefaults(newIssueDefaults, restoredProject) - : (draft.executionWorkspaceMode ?? - (draft.useIsolatedExecutionWorkspace - ? "isolated_workspace" - : defaultExecutionWorkspaceModeForProject(restoredProject))), - ); - setWorkMode(nextWorkMode); - setSelectedExecutionWorkspaceId( - hasExplicitExecutionWorkspaceId - ? (newIssueDefaults.executionWorkspaceId ?? "") - : (draft.selectedExecutionWorkspaceId ?? ""), - ); - executionWorkspaceDefaultProjectId.current = - hasExplicitProjectWorkspaceId || hasExplicitExecutionWorkspaceId || draft.projectWorkspaceId || restoredProject - ? restoredProjectId || null - : null; + restoreSubmittedDraft(draft, newIssueDefaults); } else { setWorkMode(isIssueWorkMode(newIssueDefaults.workMode) ? newIssueDefaults.workMode : "standard"); const defaultProjectId = newIssueDefaults.projectId ?? ""; @@ -1008,7 +1112,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) ? defaultProjectId || null : null; } - }, [newIssueOpen, newIssueDefaults, orderedProjects, effectiveCompanyId, setIssueText, draftOwner]); + }, [newIssueOpen, newIssueDefaults, orderedProjects, effectiveCompanyId, setIssueText, draftOwner, recoveredCreate]); // Cleanup timer on unmount useEffect(() => { @@ -1019,6 +1123,8 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) function reset() { unboundFormDraft.current = null; + setRecoveredCreate(null); visibleRequestKey.current = null; + setResendError(null); createRequestRef.current = null; setRestoredLaunch(null); if (awaitingFilesKey) clearPendingSend(awaitingFilesKey); setIssueText("", ""); @@ -1053,7 +1159,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) async function handleSubmit(body: string, mode: IssueWorkMode, settings: ComposerRunSettings | null) { const currentTitle = titleRef.current.trim(); const currentDescription = body.trim(); - if (!effectiveCompanyId || filesRestoring || (!currentTitle && !currentDescription) || createIssue.isPending || durableCreate.pending || worktreeSelectionIncomplete || parentPrivacyUnresolved) return; + if (!effectiveCompanyId || filesRestoring || (!currentTitle && !currentDescription) || visiblePending || worktreeSelectionIncomplete || parentPrivacyUnresolved) return; const inheritedOverrides = buildAssigneeAdapterOverrides({ adapterType: assigneeAdapterType, lane: assigneeChrome ? "custom" : assigneeModelLane, @@ -1077,16 +1183,17 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) const executionWorkspaceSettings = executionWorkspacePolicy?.enabled ? { mode: requestedExecutionWorkspaceMode } : null; + const workspaceLaunch = savedLaunch ?? newIssueDefaults; const requestedProjectWorkspaceId = !workspaceIsolationControlsVisible - ? (newIssueDefaults.projectId === projectId ? newIssueDefaults.projectWorkspaceId : undefined) + ? (workspaceLaunch.projectId === projectId ? workspaceLaunch.projectWorkspaceId : undefined) : canChooseWorktrees && executionWorkspaceMode === "reuse_existing" && selectedReusableExecutionWorkspace ? selectedReusableExecutionWorkspace.projectWorkspaceId : projectWorkspaceId; // A task launched from a workspace (or its parent task) keeps that explicit // context. Draft-only choices are ignored while the selector is hidden. const contextualWorkspaceId = - !workspaceIsolationControlsVisible && newIssueDefaults.projectId === projectId - ? newIssueDefaults.executionWorkspaceId + !workspaceIsolationControlsVisible && workspaceLaunch.projectId === projectId + ? workspaceLaunch.executionWorkspaceId : undefined; const executionPolicy = buildExecutionPolicy({ reviewerValues: reviewerValue ? [reviewerValue] : [], @@ -1134,11 +1241,16 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) const createFiles = request?.recovering ? restoreStagedDocumentKeys(stagedFiles, request.payload?.fingerprint) : stagedFiles; const fingerprint = JSON.stringify({ ...createData, stagedFiles: createFiles.map(stagedFileIdentity).sort() }); if (!request || (!request.recovering && request.fingerprint !== fingerprint)) { + if (request) discardCreate(request.idempotencyKey, request.payload); request = { fingerprint, idempotencyKey: createUuid() }; createRequestRef.current = request; } let createPayload: PendingCreate = { fingerprint, data: { ...createData, allowDuplicate: true, navigateOnCreate: newIssueDefaults.navigateOnCreate === true }, + draft: { title: currentTitle, description: currentDescription, status, priority, assigneeValue, + reviewerValue, approverValue, watchdogAgentId, watchdogInstructions, projectId, projectWorkspaceId, + assigneeModelLane, assigneeModelOverride, assigneeThinkingEffort, assigneeChrome, + executionWorkspaceMode, selectedExecutionWorkspaceId, workMode: mode, isPrivate: effectivePrivate, composerSettings: settings }, ...(stagedFiles.length ? { stagedFileNames: stagedFiles.map(file => file.file.name) } : {}), }; if (request.recovering) { @@ -1167,18 +1279,17 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) } request.payload = createPayload; const { idempotencyKey } = request; + navigationRequestKey.current = idempotencyKey; stagedFilesByKey.current.set(idempotencyKey, createFiles); - firstAttemptKey.current = idempotencyKey; - setResendError(null); - let result; - try { - result = await durableCreate.submit(createPayload, { idempotencyKey }); - } finally { - firstAttemptKey.current = null; + if (draftOwner !== undefined && createFiles.length) { + submittedFileWrites.current.set(idempotencyKey, + writeStagedIssueFiles(stagedFilesStorageKey(idempotencyKey, createPayload.data.companyId), createFiles, []).catch(() => {})); } - // A transient failure keeps the request and shows the pending notice; a - // rejection goes back to the composer with readable copy. - if (result.kind === "rejected") throw result.error; + durableCreate.enqueue(createPayload, idempotencyKey); + if (draftTimer.current) clearTimeout(draftTimer.current); + clearDraft(draftOwner); + reset(); + closeNewIssue(); } function handleKeyDown(e: React.KeyboardEvent) { @@ -1190,7 +1301,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) } function stageFiles(files: File[]) { - if (files.length === 0 || filesRestoring || createIssue.isPending || durableCreate.pending) return; + if (files.length === 0 || filesRestoring || visiblePending) return; setStagedFiles((current) => { const next = [...current]; for (const file of files) { @@ -1373,11 +1484,17 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) chrome: assigneeChrome, }); + const otherFailedCreates = durableCreate.rejected.filter(item => item.idempotencyKey !== visibleRequestKey.current && item.payload.data.companyId === effectiveCompanyId); + const otherPending = durableCreate.pending && durableCreate.status !== "sending" && !visiblePending && durableCreate.pending.payload.data.companyId === effectiveCompanyId ? durableCreate.pending : null; + const otherCreates: Array & { rejection?: ErrorDescription }> = [ + ...otherFailedCreates, ...(otherPending ? [otherPending] : []), + ]; + return ( { - if (!open && !createIssue.isPending) closeNewIssue(); + if (!open && !submittingRecoveredCreate) closeNewIssue(); }} > nextWorkMode(current)); - } else if (createIssue.isPending) event.preventDefault(); + } else if (submittingRecoveredCreate) event.preventDefault(); }} onPointerDownOutside={(event) => { const target = event.detail.originalEvent.target as HTMLElement | null; if ( - createIssue.isPending || + submittingRecoveredCreate || target?.closest("[data-radix-popper-content-wrapper], [data-paperclip-floating-ui]") ) { event.preventDefault(); @@ -1417,7 +1534,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) 0 || otherPending || resendError ? (
- {durableCreate.pending && durableCreate.status !== "sending" ? ( + {otherCreates.map(item => ( +
+

{item.rejection ? `${item.rejection.title}. ${item.rejection.body}` : "This task is waiting to be saved."}

+ +
+ ))} + {visiblePending && durableCreate.status !== "sending" ? ( { // The draft (title and description) is still saved; only the send stops. const cancelledKey = durableCreate.pending?.idempotencyKey; - const cancelled = durableCreate.cancel(); + const cancelled = durableCreate.pending?.payload; + if (cancelledKey) discardCreate(cancelledKey, cancelled); if (cancelled) { - createRequestRef.current = null; setRestoredLaunch(null); + createRequestRef.current = null; visibleRequestKey.current = null; setRecoveredCreate(null); setRestoredLaunch(null); if (awaitingFilesKey) clearPendingSend(awaitingFilesKey, cancelledKey); if (cancelledKey) clearCreateUploadReceipts(cancelledKey); } }} /> ) : null} - {resendError && !durableCreate.pending ? ( + {resendError && !visiblePending ? (

{resendError.title}. {resendError.body}

- {createRequestRef.current?.recovering ? : null}
) : null} @@ -1503,7 +1631,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) aria-label="Task title" value={title} // The waiting request is what gets created; later edits would be lost. - disabled={createIssue.isPending || Boolean(durableCreate.pending)} + disabled={submittingRecoveredCreate || Boolean(visiblePending)} className="w-full bg-transparent text-sm text-foreground outline-none" onChange={(event) => { titleRef.current = event.target.value; @@ -1575,7 +1703,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) size="icon-xs" className="shrink-0 text-muted-foreground" onClick={() => removeStagedFile(file.id)} - disabled={createIssue.isPending} + disabled={submittingRecoveredCreate} title="Remove document" > @@ -1609,7 +1737,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) size="icon-xs" className="shrink-0 text-muted-foreground" onClick={() => removeStagedFile(file.id)} - disabled={createIssue.isPending} + disabled={submittingRecoveredCreate} title="Remove attachment" > @@ -1667,8 +1795,8 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) ) : null} ), - submitDisabled: filesRestoring || worktreeSelectionIncomplete || parentPrivacyUnresolved || Boolean(durableCreate.pending), - readOnly: filesRestoring || Boolean(durableCreate.pending), + submitDisabled: filesRestoring || worktreeSelectionIncomplete || parentPrivacyUnresolved || Boolean(visiblePending), + readOnly: filesRestoring || Boolean(visiblePending), contextBar: ( <> void refetchWorktrees()} - disabled={createIssue.isPending} + disabled={submittingRecoveredCreate} mobile={isMobile} contentStyle={entityPickerViewportStyle} /> diff --git a/ui/src/hooks/useBackgroundSubmitQueue.test.tsx b/ui/src/hooks/useBackgroundSubmitQueue.test.tsx new file mode 100644 index 00000000000..9930523baa3 --- /dev/null +++ b/ui/src/hooks/useBackgroundSubmitQueue.test.tsx @@ -0,0 +1,91 @@ +// @vitest-environment jsdom + +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { ConnectivityProvider, createConnectivityStore } from "@/lib/connectivity"; +import { pendingSendKeyFor } from "@/lib/pending-send"; +import { DETACHED_DRAFT_OWNER } from "./useDraftOwner"; +import { useBackgroundSubmitQueue } from "./useBackgroundSubmitQueue"; + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +type Payload = { body: string }; +const isPayload = (value: unknown): value is Payload => + !!value && typeof value === "object" && typeof (value as Payload).body === "string"; +const KEY = "test:background-send"; +const stores: Array> = []; +const roots = new Set(); + +beforeEach(() => localStorage.clear()); +afterEach(() => { + act(() => { for (const root of roots) root.unmount(); }); + roots.clear(); + for (const store of stores) store.dispose(); + stores.length = 0; + document.body.innerHTML = ""; +}); + +function mountTab(send: (payload: Payload, key: string) => Promise) { + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + roots.add(root); + const store = createConnectivityStore({ browserOnline: true, probe: async () => ({ reachable: true, retryAfterMs: null }) }); + stores.push(store); + let current!: ReturnType>; + function Harness() { + current = useBackgroundSubmitQueue({ sourceId: `tab-${stores.indexOf(store)}`, storageKey: KEY, isPayload, send, onAttention: () => {} }); + return null; + } + act(() => root.render()); + return { + get queue() { return current; }, + unmount() { act(() => root.unmount()); roots.delete(root); }, + }; +} + +it("retains another tab's queued tasks through submission, completion, and reload", async () => { + const firstSend = vi.fn<(payload: Payload, key: string) => Promise>().mockImplementation(() => new Promise(() => {})); + let finishOther!: (result: string) => void; + const otherSend = vi.fn<(payload: Payload, key: string) => Promise>() + .mockImplementation(() => new Promise(resolve => { finishOther = resolve; })); + const first = mountTab(firstSend); + const other = mountTab(otherSend); + await act(async () => { + first.queue.enqueue({ body: "First slow save" }, "first-key"); + first.queue.enqueue({ body: "Second waiting task" }, "second-key"); + }); + expect(firstSend).toHaveBeenCalledOnce(); + await act(async () => { other.queue.enqueue({ body: "Other tab's task" }, "other-key"); }); + await act(async () => { finishOther("saved"); }); + first.unmount(); + other.unmount(); + + const reloadedSend = vi.fn<(payload: Payload, key: string) => Promise>().mockResolvedValue("saved"); + await act(async () => { mountTab(reloadedSend); }); + expect(reloadedSend.mock.calls.map(([payload, key]) => [payload.body, key])).toEqual([ + ["First slow save", "first-key"], ["Second waiting task", "second-key"], + ]); +}); + +it("migrates the previous queue format and restores rejected requests without sending them", async () => { + const storageKey = pendingSendKeyFor(`${KEY}:queue`, DETACHED_DRAFT_OWNER); + const rejection = { title: "Task failed", body: "Fix the saved request.", retryable: false }; + localStorage.setItem(storageKey, JSON.stringify([ + { payload: { body: "Legacy rejected task" }, idempotencyKey: "legacy-key", createdAt: 1, rejection }, + ])); + const send = vi.fn<(payload: Payload, key: string) => Promise>().mockResolvedValue("saved"); + const first = mountTab(send); + expect(first.queue.rejected[0]).toMatchObject({ idempotencyKey: "legacy-key", rejection }); + expect(send).not.toHaveBeenCalled(); + first.unmount(); + const reloaded = mountTab(send); + expect(reloaded.queue.rejected[0]).toMatchObject({ idempotencyKey: "legacy-key", rejection }); + await act(async () => { reloaded.queue.enqueue({ body: "Legacy rejected task" }, "legacy-key"); }); + expect(send).toHaveBeenCalledWith({ body: "Legacy rejected task" }, "legacy-key"); + reloaded.unmount(); + const afterReceipt = mountTab(send); + expect(afterReceipt.queue.rejected).toEqual([]); + expect(send).toHaveBeenCalledOnce(); +}); diff --git a/ui/src/hooks/useBackgroundSubmitQueue.ts b/ui/src/hooks/useBackgroundSubmitQueue.ts new file mode 100644 index 00000000000..1cc5a437494 --- /dev/null +++ b/ui/src/hooks/useBackgroundSubmitQueue.ts @@ -0,0 +1,163 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import type { ErrorDescription } from "@/api/errors"; +import { classifySendFailure, PendingSendAccountChangedError, pendingSendKeyFor, type PendingSend } from "@/lib/pending-send"; +import { useDraftOwner } from "./useDraftOwner"; +import { usePendingWritesReporter } from "@/lib/connectivity"; +import { useDurableSubmit, type DurableSubmitOptions } from "./useDurableSubmit"; + +type QueuedSubmit = PendingSend & { rejection?: ErrorDescription }; + +export function useBackgroundSubmitQueue(options: DurableSubmitOptions & { + onAttention: (record: PendingSend, error: ErrorDescription | null) => void; +}) { + const owner = useDraftOwner(); + const storageKey = options.storageKey && owner !== undefined + ? pendingSendKeyFor(`${options.storageKey}:queue`, owner) : null; + const optionsRef = useRef(options); + optionsRef.current = options; + const recordKey = (key: string, id: string) => `${key}:request:${encodeURIComponent(id)}`; + const readQueue = (): QueuedSubmit[] => { + if (!storageKey) return []; + try { + const storage = options.storage === "session" ? sessionStorage : localStorage; + const isRecord = (item: unknown): item is QueuedSubmit => !!item && typeof item === "object" + && typeof (item as QueuedSubmit).idempotencyKey === "string" + && typeof (item as QueuedSubmit).createdAt === "number" + && options.isPayload((item as QueuedSubmit).payload); + const records = new Map>(); + try { + const legacy: unknown = JSON.parse(storage.getItem(storageKey) ?? "[]"); + if (Array.isArray(legacy)) for (const item of legacy) { + if (isRecord(item)) records.set(item.idempotencyKey, item); + } + } catch {} + // Each request owns one atomic storage entry. A tab can update or remove + // its request without replacing requests submitted in another tab. + const keys = Array.from({ length: storage.length }, (_, index) => storage.key(index)); + for (const key of keys) { + if (!key?.startsWith(`${storageKey}:request:`)) continue; + try { + const item: unknown = JSON.parse(storage.getItem(key) ?? "null"); + if (isRecord(item) && key === recordKey(storageKey, item.idempotencyKey)) records.set(item.idempotencyKey, item); + } catch {} + } + return [...records.values()].sort((a, b) => a.createdAt - b.createdAt); + } catch { return []; } + }; + const [queue, setQueue] = useState(readQueue); + const queueRef = useRef(queue); + const loadedKey = useRef(storageKey); + const [round, setRound] = useState(0); + const draining = useRef(false); + const noticedKey = useRef(null); + const noticedRejections = useRef(new Set()); + const active = useRef(true); + useEffect(() => { active.current = true; return () => { active.current = false; }; }, []); + + const replaceQueue = useCallback((next: QueuedSubmit[]) => { + const previous = queueRef.current; + queueRef.current = next; + setQueue(next); + try { + if (loadedKey.current) { + const storage = optionsRef.current.storage === "session" ? sessionStorage : localStorage; + const previousByKey = new Map(previous.map(item => [item.idempotencyKey, item])); + const nextKeys = new Set(next.map(item => item.idempotencyKey)); + for (const item of next) { + if (previousByKey.get(item.idempotencyKey) !== item) { + storage.setItem(recordKey(loadedKey.current, item.idempotencyKey), JSON.stringify(item)); + } + } + for (const item of previous) { + if (!nextKeys.has(item.idempotencyKey)) storage.removeItem(recordKey(loadedKey.current, item.idempotencyKey)); + } + } + } catch {} + }, []); + + useEffect(() => { + if (loadedKey.current !== storageKey) { + const unbound = loadedKey.current === null ? queueRef.current : []; + loadedKey.current = storageKey; + queueRef.current = []; + replaceQueue([...readQueue(), ...unbound]); + } + if (!storageKey) return; + try { + const storage = options.storage === "session" ? sessionStorage : localStorage; + if (storage.getItem(storageKey) === null) return; + // Retire the old shared array only after every legacy request has its + // own entry. A storage failure leaves the legacy backup available. + for (const item of readQueue()) storage.setItem(recordKey(storageKey, item.idempotencyKey), JSON.stringify(item)); + storage.removeItem(storageKey); + } catch {} + }, [storageKey, replaceQueue]); + + const durable = useDurableSubmit({ + ...options, + send: async (payload, idempotencyKey) => { + try { + return await optionsRef.current.send(payload, idempotencyKey); + } catch (error) { + if (active.current && !(error instanceof PendingSendAccountChangedError) + && classifySendFailure(error) === "pending" && noticedKey.current !== idempotencyKey) { + noticedKey.current = idempotencyKey; + optionsRef.current.onAttention(queueRef.current.find(item => item.idempotencyKey === idempotencyKey) + ?? { payload, idempotencyKey, createdAt: Date.now() }, null); + } + throw error; + } + }, + onSent: (result, record) => { + if (!active.current) return; + replaceQueue(queueRef.current.filter(item => item.idempotencyKey !== record.idempotencyKey)); + optionsRef.current.onSent?.(result, record); + }, + onRejected: (error, description, record) => { + if (!active.current) return; + replaceQueue(queueRef.current.map(item => item.idempotencyKey === record.idempotencyKey + ? { ...item, payload: record.payload, rejection: description } : item)); + optionsRef.current.onRejected?.(error, description, record); + noticedRejections.current.add(record.idempotencyKey); + optionsRef.current.onAttention(record, description); + }, + }); + + useEffect(() => { + if (owner === undefined || durable.pending || draining.current) return; + const next = queue.find(item => !item.rejection); + if (!next) return; + draining.current = true; + void durable.submit(next.payload, { idempotencyKey: next.idempotencyKey }).finally(() => { + draining.current = false; + if (active.current) setRound(value => value + 1); + }); + }, [owner, queue, durable.pending, durable.submit, round]); + + useEffect(() => { + for (const record of queue) { + if (!record.rejection || noticedRejections.current.has(record.idempotencyKey)) continue; + noticedRejections.current.add(record.idempotencyKey); + optionsRef.current.onAttention(record, record.rejection); + } + }, [queue]); + + usePendingWritesReporter(`${options.sourceId}:queue`, queue.filter(item => + !item.rejection && item.idempotencyKey !== durable.pending?.idempotencyKey).length); + + const enqueue = useCallback((payload: T, idempotencyKey: string) => { + if (noticedKey.current === idempotencyKey) noticedKey.current = null; + noticedRejections.current.delete(idempotencyKey); + replaceQueue([ + ...queueRef.current.filter(item => item.idempotencyKey !== idempotencyKey), + { payload, idempotencyKey, createdAt: Date.now() }, + ]); + }, [replaceQueue]); + + const discard = useCallback((idempotencyKey: string) => { + if (durable.pending?.idempotencyKey === idempotencyKey) durable.cancel(); + replaceQueue(queueRef.current.filter(item => item.idempotencyKey !== idempotencyKey)); + }, [durable.pending, durable.cancel, replaceQueue]); + + return { ...durable, enqueue, discard, rejected: queue.filter(item => item.rejection) }; +}