mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-07 16:35:48 +01:00
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:
62 files changed
+6486
-733
No files matched your search
@@ -2,7 +2,14 @@
|
||||
|
||||
import { act, forwardRef, useImperativeHandle, useRef, type ReactNode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
|
||||
const mockSession = vi.hoisted(() => ({ userId: "user-1", pending: null as Promise<{ user: { id: string } } | null> | null }));
|
||||
vi.mock("../api/auth", () => ({
|
||||
authApi: { getSession: () => mockSession.pending ?? Promise.resolve({ user: { id: mockSession.userId } }) },
|
||||
}));
|
||||
|
||||
vi.mock("./MarkdownEditor", () => ({
|
||||
MarkdownEditor: forwardRef<
|
||||
@@ -32,6 +39,14 @@ vi.mock("./MarkdownBody", () => ({
|
||||
|
||||
import { InlineEditor, queueContainedBlurCommit } from "./InlineEditor";
|
||||
|
||||
/** Render as a signed-in user: stored drafts belong to one account. */
|
||||
function signedIn(userId: string, node: ReactNode) {
|
||||
mockSession.userId = userId;
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
client.setQueryData(queryKeys.auth.session, { user: { id: userId } });
|
||||
return <QueryClientProvider client={client}>{node}</QueryClientProvider>;
|
||||
}
|
||||
|
||||
/** Enter multiline edit mode by clicking the preview surface. */
|
||||
function enterMultilineEdit(container: HTMLDivElement) {
|
||||
const preview = container.querySelector<HTMLDivElement>('[data-testid="multiline-md-preview"]');
|
||||
@@ -111,6 +126,203 @@ describe("InlineEditor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a single-line edit open with no unhandled rejection when the save fails", async () => {
|
||||
const unhandled = vi.fn();
|
||||
window.addEventListener("unhandledrejection", unhandled);
|
||||
process.on("unhandledRejection", unhandled);
|
||||
const onSave = vi.fn().mockRejectedValue(new Error("Title is too long"));
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<InlineEditor value="hello" onSave={onSave} />);
|
||||
});
|
||||
act(() => {
|
||||
container.querySelector("span")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
const textarea = container.querySelector("textarea")!;
|
||||
act(() => setNativeTextareaValue(textarea, "hello world"));
|
||||
await act(async () => {
|
||||
textarea.blur();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
});
|
||||
expect(onSave).toHaveBeenCalledWith("hello world");
|
||||
// The text stays in the editor instead of snapping back to the old value.
|
||||
expect(container.querySelector("textarea")?.value).toBe("hello world");
|
||||
expect(unhandled).not.toHaveBeenCalled();
|
||||
window.removeEventListener("unhandledrejection", unhandled);
|
||||
process.off("unhandledRejection", unhandled);
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("restores an unsaved edit and saves it when the server value has not moved", async () => {
|
||||
localStorage.setItem("paperclip:inline-draft:v2:user-1:issue-1:description", JSON.stringify({ version: 1, draft: "Typed before reload", base: "Original" }));
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
const root = createRoot(container);
|
||||
await act(async () => {
|
||||
root.render(signedIn("user-1", <InlineEditor value="Original" multiline draftKey="issue-1:description" onSave={onSave} />));
|
||||
});
|
||||
expect(container.querySelector<HTMLTextAreaElement>('[data-testid="multiline-md-mock"]')?.value).toBe("Typed before reload");
|
||||
expect(onSave).toHaveBeenCalledWith("Typed before reload");
|
||||
act(() => root.unmount());
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it("restores the next task's stored edit without remounting the editor", async () => {
|
||||
localStorage.setItem("paperclip:inline-draft:v2:user-1:issue-b:description", JSON.stringify({ version: 1, draft: "Recovered B", base: "Original B" }));
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||||
const saveA = vi.fn().mockResolvedValue(undefined);
|
||||
const saveB = vi.fn().mockResolvedValue(undefined);
|
||||
const root = createRoot(container);
|
||||
const renderTask = (id: string, onSave: typeof saveA) => root.render(
|
||||
<QueryClientProvider client={client}>
|
||||
<InlineEditor value={`Original ${id.toUpperCase()}`} multiline draftKey={`issue-${id}:description`} onSave={onSave} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
try {
|
||||
await act(async () => renderTask("a", saveA));
|
||||
await act(async () => renderTask("b", saveB));
|
||||
expect(container.querySelector<HTMLTextAreaElement>('[data-testid="multiline-md-mock"]')?.value).toBe("Recovered B");
|
||||
expect(saveB).toHaveBeenCalledWith("Recovered B");
|
||||
expect(saveA).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
localStorage.clear();
|
||||
client.clear();
|
||||
}
|
||||
});
|
||||
|
||||
it("restores an unsaved edit without overwriting a newer server value", async () => {
|
||||
localStorage.setItem("paperclip:inline-draft:v2:user-1:issue-2:description", JSON.stringify({ version: 1, draft: "My old edit", base: "Original" }));
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
const root = createRoot(container);
|
||||
await act(async () => {
|
||||
root.render(signedIn("user-1", <InlineEditor value="Changed by an agent" multiline draftKey="issue-2:description" onSave={onSave} />));
|
||||
});
|
||||
expect(container.querySelector<HTMLTextAreaElement>('[data-testid="multiline-md-mock"]')?.value).toBe("My old edit");
|
||||
expect(onSave).not.toHaveBeenCalled();
|
||||
act(() => root.unmount());
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it("neither shows nor saves another account's unsaved edit", async () => {
|
||||
localStorage.setItem("paperclip:inline-draft:v2:user-1:issue-3:description", JSON.stringify({ version: 1, draft: "Unpublished by user 1", base: "Original" }));
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
const root = createRoot(container);
|
||||
await act(async () => {
|
||||
root.render(signedIn("user-2", <InlineEditor value="Original" multiline draftKey="issue-3:description" onSave={onSave} />));
|
||||
});
|
||||
expect(container.textContent).not.toContain("Unpublished by user 1");
|
||||
expect(container.querySelector<HTMLTextAreaElement>('[data-testid="multiline-md-mock"]')?.value ?? "").not.toBe("Unpublished by user 1");
|
||||
expect(onSave).not.toHaveBeenCalled();
|
||||
act(() => root.unmount());
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it.each(["user-1", "signed-out"])("keeps typing through the first session lookup (%s)", async (owner) => {
|
||||
localStorage.clear();
|
||||
localStorage.setItem(`paperclip:inline-draft:v2:${owner}:initial-session`, JSON.stringify({ version: 1, draft: "Earlier saved draft", base: "Original" }));
|
||||
let finish!: (session: { user: { id: string } } | null) => void;
|
||||
mockSession.pending = new Promise(resolve => { finish = resolve; });
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () => root.render(
|
||||
<QueryClientProvider client={client}>
|
||||
<InlineEditor value="Original" draftKey="initial-session" onSave={onSave} />
|
||||
</QueryClientProvider>,
|
||||
));
|
||||
act(() => container.querySelector("span")!.click());
|
||||
const input = container.querySelector("textarea")!;
|
||||
act(() => setNativeTextareaValue(input, "Typing while session loads"));
|
||||
await act(async () => {
|
||||
finish(owner === "signed-out" ? null : { user: { id: owner } });
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
});
|
||||
expect(container.querySelector("textarea")).toBe(input);
|
||||
expect(input.value).toBe("Typing while session loads");
|
||||
await vi.waitFor(async () => {
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); });
|
||||
expect(localStorage.getItem(`paperclip:inline-draft:v2:${owner}:initial-session`)).toContain("Typing while session loads");
|
||||
});
|
||||
expect(onSave).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
client.clear();
|
||||
localStorage.clear();
|
||||
mockSession.pending = null;
|
||||
}
|
||||
});
|
||||
|
||||
it("does not restore typing cancelled before the first session lookup", async () => {
|
||||
localStorage.clear();
|
||||
localStorage.setItem("paperclip:inline-draft:v2:user-1:cancel-before-session", JSON.stringify({ version: 1, draft: "Original", base: "Original" }));
|
||||
let finish!: (session: { user: { id: string } }) => void;
|
||||
mockSession.pending = new Promise(resolve => { finish = resolve; });
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () => root.render(
|
||||
<QueryClientProvider client={client}>
|
||||
<InlineEditor value="Original" draftKey="cancel-before-session" onSave={vi.fn()} />
|
||||
</QueryClientProvider>,
|
||||
));
|
||||
act(() => container.querySelector("span")!.click());
|
||||
act(() => setNativeTextareaValue(container.querySelector("textarea")!, "Cancelled private text"));
|
||||
act(() => container.querySelector("textarea")!.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })));
|
||||
await act(async () => {
|
||||
finish({ user: { id: "user-1" } });
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
});
|
||||
expect(container.textContent).not.toContain("Cancelled private text");
|
||||
await vi.waitFor(async () => {
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); });
|
||||
expect(localStorage.getItem("paperclip:inline-draft:v2:user-1:cancel-before-session")).toBeNull();
|
||||
});
|
||||
} finally {
|
||||
act(() => root.unmount()); client.clear(); localStorage.clear(); mockSession.pending = null;
|
||||
}
|
||||
});
|
||||
|
||||
it.each([false, true])("isolates a mounted private edit after an account change (multiline=%s)", async (multiline) => {
|
||||
mockSession.userId = "user-1";
|
||||
localStorage.clear();
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () => root.render(
|
||||
<QueryClientProvider client={client}>
|
||||
<InlineEditor value="Original" multiline={multiline} defaultEditing={multiline} draftKey="private-switch" onSave={onSave} />
|
||||
</QueryClientProvider>,
|
||||
));
|
||||
if (!multiline) act(() => container.querySelector("span")!.click());
|
||||
act(() => setNativeTextareaValue(container.querySelector("textarea")!, "Private account A draft"));
|
||||
const storedA = localStorage.getItem("paperclip:inline-draft:v2:user-1:private-switch");
|
||||
expect(storedA).toContain("Private account A draft");
|
||||
mockSession.userId = "user-2";
|
||||
await act(async () => {
|
||||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-2" } });
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
});
|
||||
expect(container.querySelector("textarea")?.value ?? "").not.toContain("Private account A draft");
|
||||
expect(container.textContent).not.toContain("Private account A draft");
|
||||
expect(localStorage.getItem("paperclip:inline-draft:v2:user-1:private-switch")).toBe(storedA);
|
||||
expect(localStorage.getItem("paperclip:inline-draft:v2:user-2:private-switch")).toBeNull();
|
||||
expect(onSave).not.toHaveBeenCalled();
|
||||
if (!multiline) act(() => container.querySelector("span")!.click());
|
||||
act(() => setNativeTextareaValue(container.querySelector("textarea")!, "Account B edit"));
|
||||
expect(localStorage.getItem("paperclip:inline-draft:v2:user-2:private-switch")).toContain("Account B edit");
|
||||
expect(localStorage.getItem("paperclip:inline-draft:v2:user-2:private-switch")).not.toContain("Private account A draft");
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
client.clear();
|
||||
localStorage.clear();
|
||||
mockSession.userId = "user-1";
|
||||
}
|
||||
});
|
||||
|
||||
it("does not call onSave when nullable is false/omitted and the field is cleared", () => {
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
const root = createRoot(container);
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { useState, useRef, useEffect, useCallback } from "react";
|
||||
import { useState, useRef, useEffect, useCallback, useId } from "react";
|
||||
import { cn } from "../lib/utils";
|
||||
import { MarkdownBody, type MarkdownExternalReferenceMap } from "./MarkdownBody";
|
||||
import { MarkdownEditor, type MarkdownEditorRef, type MentionOption } from "./MarkdownEditor";
|
||||
import { useAutosaveIndicator } from "../hooks/useAutosaveIndicator";
|
||||
import { useDurableAutosave } from "../hooks/useDurableAutosave";
|
||||
import { useDraftOwner } from "../hooks/useDraftOwner";
|
||||
import { loadStructuredDraft, saveStructuredDraft } from "../lib/composer-draft";
|
||||
|
||||
type StoredInlineDraft = { version: 1; draft: string; base: string };
|
||||
import { FoldCurtain } from "./FoldCurtain";
|
||||
|
||||
interface InlineEditorProps {
|
||||
@@ -31,6 +35,11 @@ interface InlineEditorProps {
|
||||
defaultEditing?: boolean;
|
||||
/** Notified when the multiline editor swaps between display and edit mode. */
|
||||
onEditingChange?: (editing: boolean) => void;
|
||||
/**
|
||||
* Keep unsaved edits in browser storage under this key, so a reload or an
|
||||
* outage does not lose them. A stored edit is restored and saved on mount.
|
||||
*/
|
||||
draftKey?: string;
|
||||
}
|
||||
|
||||
/** Shared padding so display and edit modes occupy the exact same box. */
|
||||
@@ -55,7 +64,15 @@ export function queueContainedBlurCommit(container: HTMLDivElement, onCommit: ()
|
||||
};
|
||||
}
|
||||
|
||||
export function InlineEditor({
|
||||
export function InlineEditor(props: InlineEditorProps) {
|
||||
const draftOwner = useDraftOwner();
|
||||
const [scope, setScope] = useState({ owner: draftOwner, generation: 0 });
|
||||
const generation = scope.generation + (scope.owner !== undefined && scope.owner !== draftOwner ? 1 : 0);
|
||||
if (scope.owner !== draftOwner) setScope({ owner: draftOwner, generation });
|
||||
return <OwnedInlineEditor key={generation} {...props} draftOwner={draftOwner} />;
|
||||
}
|
||||
|
||||
function OwnedInlineEditor({
|
||||
value,
|
||||
onSave,
|
||||
as: Tag = "span",
|
||||
@@ -70,11 +87,14 @@ export function InlineEditor({
|
||||
externalReferences,
|
||||
defaultEditing = false,
|
||||
onEditingChange,
|
||||
}: InlineEditorProps) {
|
||||
draftKey,
|
||||
draftOwner,
|
||||
}: InlineEditorProps & { draftOwner: string | undefined }) {
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [multilineEditing, setMultilineEditing] = useState(multiline && defaultEditing);
|
||||
const [multilineFocused, setMultilineFocused] = useState(false);
|
||||
const [draft, setDraft] = useState(value);
|
||||
const unownedDraft = useRef<StoredInlineDraft | null>(null);
|
||||
const lastPropValueRef = useRef(value);
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null);
|
||||
const markdownRef = useRef<MarkdownEditorRef>(null);
|
||||
@@ -83,12 +103,46 @@ export function InlineEditor({
|
||||
const pendingFocusFrameRef = useRef<number | null>(null);
|
||||
const justEnteredEditRef = useRef(multiline && defaultEditing);
|
||||
const hasBeenFocusedRef = useRef(false);
|
||||
const {
|
||||
state: autosaveState,
|
||||
markDirty,
|
||||
reset,
|
||||
runSave,
|
||||
} = useAutosaveIndicator();
|
||||
const autosave = useDurableAutosave<string>({
|
||||
sourceId: `inline-editor:${useId()}`,
|
||||
targetKey: draftKey ?? undefined,
|
||||
save: async (next) => {
|
||||
await onSave(next);
|
||||
},
|
||||
});
|
||||
const { markDirty, reset, run: runAutosave } = autosave;
|
||||
const autosaveState = autosave.status;
|
||||
const autosaveStateRef = useRef(autosaveState);
|
||||
autosaveStateRef.current = autosaveState;
|
||||
|
||||
// Unsaved edits are stored with the value they were based on, so a restored
|
||||
// edit never silently overwrites a newer server value, and per signed-in
|
||||
// account, so another account in this browser never sees or saves them.
|
||||
const storageKey = draftKey && draftOwner !== undefined ? `paperclip:inline-draft:v2:${draftOwner}:${draftKey}` : null;
|
||||
const clearStoredDraft = useCallback(() => {
|
||||
if (!storageKey) return;
|
||||
try {
|
||||
localStorage.removeItem(storageKey);
|
||||
} catch {
|
||||
// Unavailable storage holds nothing to clear.
|
||||
}
|
||||
}, [storageKey]);
|
||||
|
||||
// Any path that lands the edit (blur, autosave, a resend after an outage)
|
||||
// updates `value`; the stored copy is then no longer needed.
|
||||
useEffect(() => {
|
||||
if (!storageKey) return;
|
||||
const stored = loadStructuredDraft<StoredInlineDraft | null>(storageKey, null);
|
||||
if (stored && typeof stored.draft === "string" && stored.draft.trim() === value.trim()) clearStoredDraft();
|
||||
}, [clearStoredDraft, storageKey, value]);
|
||||
|
||||
const changeDraft = useCallback((next: string) => {
|
||||
setDraft(next);
|
||||
if (draftOwner === undefined) unownedDraft.current = { version: 1, draft: next, base: value };
|
||||
if (!storageKey) return;
|
||||
if (next.trim() === value.trim()) clearStoredDraft();
|
||||
else saveStructuredDraft(storageKey, { version: 1, draft: next, base: value } satisfies StoredInlineDraft);
|
||||
}, [clearStoredDraft, draftOwner, storageKey, value]);
|
||||
|
||||
useEffect(() => {
|
||||
const previousValue = lastPropValueRef.current;
|
||||
@@ -101,6 +155,36 @@ export function InlineEditor({
|
||||
});
|
||||
}, [value, multiline, multilineFocused]);
|
||||
|
||||
// An edit that never saved (reload, crash, outage) comes back. It saves on
|
||||
// its own only when the server value is still the one it was based on;
|
||||
// otherwise it waits in the editor for the user.
|
||||
const restoredDraftRef = useRef<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (!storageKey || restoredDraftRef.current === storageKey) return;
|
||||
restoredDraftRef.current = storageKey;
|
||||
if (unownedDraft.current) {
|
||||
if (draft.trim() !== value.trim()) saveStructuredDraft(storageKey, { ...unownedDraft.current, draft });
|
||||
else clearStoredDraft();
|
||||
unownedDraft.current = null;
|
||||
return;
|
||||
}
|
||||
const stored = loadStructuredDraft<StoredInlineDraft | null>(storageKey, null);
|
||||
if (!stored || stored.version !== 1 || typeof stored.draft !== "string" || typeof stored.base !== "string") return;
|
||||
if (stored.draft.trim() === value.trim()) {
|
||||
clearStoredDraft();
|
||||
return;
|
||||
}
|
||||
setDraft(stored.draft);
|
||||
if (multiline) {
|
||||
setMultilineEditing(true);
|
||||
onEditingChange?.(true);
|
||||
} else {
|
||||
setEditing(true);
|
||||
}
|
||||
if (stored.base === value) void runAutosave(stored.draft.trim());
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [storageKey]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (autosaveDebounceRef.current) {
|
||||
@@ -162,6 +246,7 @@ export function InlineEditor({
|
||||
}
|
||||
if (!multiline || !multilineEditing) return;
|
||||
if (!hasBeenFocusedRef.current) return;
|
||||
// Waiting or failed saves keep the editor open, so the text stays visible.
|
||||
if (autosaveState !== "idle") return;
|
||||
hasBeenFocusedRef.current = false;
|
||||
setMultilineEditing(false);
|
||||
@@ -169,37 +254,39 @@ export function InlineEditor({
|
||||
}, [multiline, multilineEditing, multilineFocused, autosaveState, onEditingChange]);
|
||||
|
||||
|
||||
// A single-line edit that waited for the connection closes once it saves.
|
||||
useEffect(() => {
|
||||
if (multiline || !editing || autosaveState !== "saved") return;
|
||||
if (document.activeElement === inputRef.current) return;
|
||||
setEditing(false);
|
||||
}, [autosaveState, editing, multiline]);
|
||||
|
||||
/** Save the draft if it changed. Never rejects; a failed save keeps the text. */
|
||||
const commit = useCallback(async (nextValue = draft) => {
|
||||
const valueToSave = nextValue.trim();
|
||||
const valueChanged = valueToSave !== value;
|
||||
const shouldSave = nullable
|
||||
? valueChanged
|
||||
: Boolean(valueToSave && valueChanged);
|
||||
if (shouldSave) {
|
||||
await Promise.resolve(onSave(valueToSave));
|
||||
} else {
|
||||
if (!shouldSave) {
|
||||
setDraft(value);
|
||||
if (draftKey) clearStoredDraft();
|
||||
if (!multiline) setEditing(false);
|
||||
return;
|
||||
}
|
||||
if (!multiline) {
|
||||
setEditing(false);
|
||||
}
|
||||
}, [draft, multiline, nullable, onSave, value]);
|
||||
const result = await runAutosave(valueToSave);
|
||||
// A single-line edit stays open until it is saved, so its text is not lost.
|
||||
if (!multiline && result.kind === "saved") setEditing(false);
|
||||
}, [clearStoredDraft, draft, draftKey, multiline, nullable, runAutosave, value]);
|
||||
|
||||
/** Multiline blur/submit: show autosave indicator when persisting */
|
||||
const finalizeMultilineBlurOrSubmit = useCallback(() => {
|
||||
const trimmed = draft.trim();
|
||||
if (trimmed === value) {
|
||||
if (trimmed === value || (!trimmed && !nullable)) {
|
||||
reset();
|
||||
void commit();
|
||||
return;
|
||||
}
|
||||
if (!trimmed && !nullable) {
|
||||
reset();
|
||||
void commit();
|
||||
return;
|
||||
}
|
||||
void runSave(() => commit());
|
||||
}, [commit, draft, nullable, reset, runSave, value]);
|
||||
void commit();
|
||||
}, [commit, draft, nullable, reset, value]);
|
||||
|
||||
const cancelPendingBlurCommit = useCallback(() => {
|
||||
if (blurCommitFrameRef.current === null) return;
|
||||
@@ -230,6 +317,7 @@ export function InlineEditor({
|
||||
}
|
||||
reset();
|
||||
setDraft(value);
|
||||
if (draftKey) clearStoredDraft();
|
||||
if (multiline) {
|
||||
setMultilineFocused(false);
|
||||
setMultilineEditing(false);
|
||||
@@ -250,7 +338,7 @@ export function InlineEditor({
|
||||
const trimmed = draft.trim();
|
||||
// Nullable: empty draft can still be a real edit (clearing); only skip debounce when unchanged or empty is invalid.
|
||||
if (trimmed === value || (!trimmed && !nullable)) {
|
||||
if (autosaveState !== "saved") {
|
||||
if (autosaveStateRef.current !== "saved") {
|
||||
reset();
|
||||
}
|
||||
return;
|
||||
@@ -260,7 +348,7 @@ export function InlineEditor({
|
||||
clearTimeout(autosaveDebounceRef.current);
|
||||
}
|
||||
autosaveDebounceRef.current = setTimeout(() => {
|
||||
void runSave(() => commit(trimmed));
|
||||
void commit(trimmed);
|
||||
}, AUTOSAVE_DEBOUNCE_MS);
|
||||
|
||||
return () => {
|
||||
@@ -268,7 +356,7 @@ export function InlineEditor({
|
||||
clearTimeout(autosaveDebounceRef.current);
|
||||
}
|
||||
};
|
||||
}, [autosaveState, commit, draft, markDirty, multiline, multilineFocused, nullable, reset, runSave, value]);
|
||||
}, [commit, draft, markDirty, multiline, multilineFocused, nullable, reset, value]);
|
||||
|
||||
if (multiline) {
|
||||
const previewValue = autosaveState === "saved" || autosaveState === "idle" ? draft : value;
|
||||
@@ -353,7 +441,7 @@ export function InlineEditor({
|
||||
<MarkdownEditor
|
||||
ref={markdownRef}
|
||||
value={draft}
|
||||
onChange={setDraft}
|
||||
onChange={changeDraft}
|
||||
placeholder={placeholder}
|
||||
bordered={false}
|
||||
className="bg-transparent"
|
||||
@@ -372,15 +460,11 @@ export function InlineEditor({
|
||||
autosaveState === "error" ? "text-destructive" : "text-muted-foreground",
|
||||
autosaveState === "idle" ? "opacity-0" : "opacity-100",
|
||||
)}
|
||||
role={autosaveState === "error" ? "alert" : "status"}
|
||||
>
|
||||
{autosaveState === "saving"
|
||||
? "Autosaving..."
|
||||
: autosaveState === "saved"
|
||||
? "Saved"
|
||||
: autosaveState === "error"
|
||||
? "Could not save"
|
||||
: "Idle"}
|
||||
{autosave.label ?? "Idle"}
|
||||
</span>
|
||||
{autosaveState === "stalled" ? <button type="button" className="ml-2 text-xs text-foreground underline" onClick={autosave.resendNow}>Retry saving</button> : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -394,7 +478,7 @@ export function InlineEditor({
|
||||
value={draft}
|
||||
rows={1}
|
||||
onChange={(e) => {
|
||||
setDraft(e.target.value);
|
||||
changeDraft(e.target.value);
|
||||
autoSize(e.target);
|
||||
}}
|
||||
onBlur={() => {
|
||||
@@ -415,6 +499,7 @@ export function InlineEditor({
|
||||
const DisplayTag = value && multiline ? "div" : Tag;
|
||||
|
||||
return (
|
||||
<>
|
||||
<DisplayTag
|
||||
className={cn(
|
||||
"cursor-pointer rounded hover:bg-accent/50 transition-colors overflow-hidden",
|
||||
@@ -426,5 +511,7 @@ export function InlineEditor({
|
||||
>
|
||||
{value || placeholder}
|
||||
</DisplayTag>
|
||||
{autosaveState === "stalled" ? <button type="button" className="text-xs text-foreground underline" onClick={autosave.resendNow}>Retry saving</button> : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -12,10 +12,13 @@ import { flushSync } from "react-dom";
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Agent } from "@paperclipai/shared";
|
||||
import { CommentSubmissionUnknownError } from "../lib/comment-submit-result";
|
||||
import { loadDraft, preserveDraftInTab, settleDraftSubmission } from "../lib/composer-draft";
|
||||
import { loadDraft, saveDraft, saveDraftSubmission, loadDraftSubmission, preserveDraftInTab, settleDraftSubmission } from "../lib/composer-draft";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
import { useAccountBoundMutation } from "../hooks/useAccountBoundMutation";
|
||||
import {
|
||||
IssueAssigneePausedNotice,
|
||||
IssueChatThread,
|
||||
@@ -80,6 +83,12 @@ const {
|
||||
shouldPreserveComposerViewportMock: vi.fn(),
|
||||
}));
|
||||
|
||||
// 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(() => {}) } };
|
||||
});
|
||||
|
||||
vi.mock("@assistant-ui/react", () => ({
|
||||
AssistantRuntimeProvider: ({ children }: { children: ReactNode }) => (
|
||||
<div>{children}</div>
|
||||
@@ -2900,13 +2909,156 @@ describe("IssueChatThread", () => {
|
||||
)?.value).toBe(nextDraft);
|
||||
expect(localStorage.getItem(key)).toBe(nextDraft);
|
||||
expect(localStorage.getItem(`${key}:submission:v1`)).toBeNull();
|
||||
expect(container.textContent).not.toContain("We couldn’t confirm");
|
||||
expect(container.textContent).not.toContain("Sending when reconnected…");
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
}
|
||||
expect(localStorage.getItem(key)).toBe(nextDraft);
|
||||
});
|
||||
|
||||
it("keeps the original key after account cancellation of an accepted initial send", async () => {
|
||||
const key = "accepted-thread-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 OwnedThread() {
|
||||
const mutation = useAccountBoundMutation({ mutationFn: ({ body, requestId }: { body: string; requestId?: string }) => post(body, requestId) });
|
||||
return <IssueChatThread comments={[]} currentUserId="user-1" linkedRuns={[]} timelineEvents={[]} liveRuns={[]}
|
||||
draftKey={key} enableLiveTranscriptPolling={false}
|
||||
onAdd={(body, _reopen, _reassign, _files, requestId) => mutation.mutateAsync({ body, requestId })} />;
|
||||
}
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () => root.render(<QueryClientProvider client={client}><MemoryRouter><OwnedThread /></MemoryRouter></QueryClientProvider>));
|
||||
const editor = () => container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Issue chat editor"]')!;
|
||||
act(() => {
|
||||
Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value")!.set!.call(editor(), "Accepted before the account changed");
|
||||
editor().dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
const button = (label: string) => Array.from(container.querySelectorAll("button")).find(item => item.textContent === label)!;
|
||||
await act(async () => button("Send").click());
|
||||
const requestId = post.mock.calls[0][1]!;
|
||||
act(() => {
|
||||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-2" } });
|
||||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||||
});
|
||||
await act(async () => accepted());
|
||||
expect(loadDraftSubmission(key)?.attemptId).toBe(requestId);
|
||||
expect(editor().value).toBe("Accepted before the account changed");
|
||||
await act(async () => button("Resend now").click());
|
||||
expect(post).toHaveBeenCalledTimes(2);
|
||||
expect(post.mock.calls[1][1]).toBe(requestId);
|
||||
expect(loadDraftSubmission(key)).toBeNull();
|
||||
} finally { act(() => root.unmount()); client.clear(); }
|
||||
});
|
||||
|
||||
it.each([false, true])("does not retry a stale account render (returns to original=%s)", async (returns) => {
|
||||
const key = "stale-thread-account";
|
||||
const attemptId = "9af8228f-0be7-45ae-a104-6fbe0af6f1d3";
|
||||
saveDraft(key, "Account A text");
|
||||
saveDraftSubmission(key, { attemptId, reviewed: false, request: { body: "Account A 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);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () => root.render(<QueryClientProvider client={client}><MemoryRouter>
|
||||
<IssueChatThread comments={[]} currentUserId="user-1" linkedRuns={[]} timelineEvents={[]} liveRuns={[]}
|
||||
onAdd={onAdd} draftKey={key} enableLiveTranscriptPolling={false} />
|
||||
</MemoryRouter></QueryClientProvider>));
|
||||
const resend = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Resend now")!;
|
||||
await act(async () => {
|
||||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-2" } });
|
||||
if (returns) client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||||
resend.click();
|
||||
});
|
||||
expect(onAdd).not.toHaveBeenCalled();
|
||||
expect(loadDraftSubmission(key)?.attemptId).toBe(attemptId);
|
||||
} finally { act(() => root.unmount()); client.clear(); }
|
||||
});
|
||||
|
||||
it("resends an unconfirmed comment with the same request ID and keeps the next draft", async () => {
|
||||
const key = "resend-unconfirmed-comment";
|
||||
let rejectSend!: (error: Error) => void;
|
||||
const onAdd = vi.fn()
|
||||
.mockReturnValueOnce(new Promise<void>((_, reject) => { rejectSend = reject; }))
|
||||
.mockResolvedValue(undefined);
|
||||
const root = createRoot(container);
|
||||
const editor = () => container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Issue chat editor"]')!;
|
||||
const type = (value: string) => act(() => {
|
||||
Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value")!.set!.call(editor(), value);
|
||||
editor().dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
const button = (label: string) => Array.from(container.querySelectorAll("button")).find(item => item.textContent === label) as HTMLButtonElement;
|
||||
try {
|
||||
await act(async () => root.render(
|
||||
<MemoryRouter>
|
||||
<IssueChatThread comments={[]} currentUserId="user-1" linkedRuns={[]} timelineEvents={[]} liveRuns={[]}
|
||||
onAdd={onAdd} draftKey={key} enableLiveTranscriptPolling={false} />
|
||||
</MemoryRouter>,
|
||||
));
|
||||
type("Typed during the outage");
|
||||
await act(async () => button("Send").click());
|
||||
type("Next thought");
|
||||
await act(async () => rejectSend(new CommentSubmissionUnknownError()));
|
||||
expect(container.textContent).toContain("Sending when reconnected…");
|
||||
expect(JSON.parse(localStorage.getItem(`${key}:submission:v1`)!).request.body).toBe("Typed during the outage");
|
||||
await act(async () => button("Resend now").click());
|
||||
expect(onAdd).toHaveBeenCalledTimes(2);
|
||||
expect(onAdd.mock.calls[1]![0]).toBe("Typed during the outage");
|
||||
expect(onAdd.mock.calls[1]![4]).toBe(onAdd.mock.calls[0]![4]);
|
||||
expect(container.textContent).not.toContain("Sending when reconnected…");
|
||||
expect(editor().value).toBe("Next thought");
|
||||
expect(localStorage.getItem(`${key}:submission:v1`)).toBeNull();
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
}
|
||||
});
|
||||
|
||||
it("resends a comment sent before the session loaded once the account is known", async () => {
|
||||
const key = "resend-before-session";
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const onAdd = vi.fn()
|
||||
.mockRejectedValueOnce(new CommentSubmissionUnknownError())
|
||||
.mockResolvedValue(undefined);
|
||||
const root = createRoot(container);
|
||||
const editor = () => container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Issue chat editor"]')!;
|
||||
const button = (label: string) => Array.from(container.querySelectorAll("button")).find(item => item.textContent === label) as HTMLButtonElement | undefined;
|
||||
try {
|
||||
await act(async () => root.render(
|
||||
<QueryClientProvider client={client}>
|
||||
<MemoryRouter>
|
||||
<IssueChatThread comments={[]} currentUserId="user-1" linkedRuns={[]} timelineEvents={[]} liveRuns={[]}
|
||||
onAdd={onAdd} draftKey={key} enableLiveTranscriptPolling={false} />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
));
|
||||
act(() => {
|
||||
Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value")!.set!.call(editor(), "Sent before the session");
|
||||
editor().dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
await act(async () => button("Send")!.click());
|
||||
// Until the account is known the send cannot be replayed.
|
||||
expect(button("Resend now")).toBeUndefined();
|
||||
|
||||
await act(async () => {
|
||||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
});
|
||||
expect(JSON.parse(localStorage.getItem(`${key}:submission:v1`)!).requestOwner).toBe("user-1");
|
||||
expect(container.textContent).toContain("Sending when reconnected…");
|
||||
await act(async () => button("Resend now")!.click());
|
||||
expect(onAdd).toHaveBeenCalledTimes(2);
|
||||
expect(onAdd.mock.calls[1]![4]).toBe(onAdd.mock.calls[0]![4]);
|
||||
expect(container.textContent).not.toContain("Sending when reconnected…");
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
client.clear();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["submission write", "all storage"])(
|
||||
"unlocks a confirmed in-memory submission after failed %s",
|
||||
async (failure) => {
|
||||
@@ -2944,10 +3096,10 @@ describe("IssueChatThread", () => {
|
||||
const attemptId = onAdd.mock.calls[0]![4] as string;
|
||||
type("The full next draft");
|
||||
await act(async () => rejectSend(new CommentSubmissionUnknownError()));
|
||||
expect(container.textContent).toContain("We couldn’t confirm");
|
||||
expect(container.textContent).toContain("Sending when reconnected…");
|
||||
await act(async () => root.render(element(attemptId)));
|
||||
expect(editor().value).toBe("The full next draft");
|
||||
expect(container.textContent).not.toContain("We couldn’t confirm");
|
||||
expect(container.textContent).not.toContain("Sending when reconnected…");
|
||||
expect(send().disabled).toBe(false);
|
||||
await act(async () => send().click());
|
||||
expect(onAdd.mock.calls[1]![0]).toBe("The full next draft");
|
||||
@@ -3000,7 +3152,7 @@ describe("IssueChatThread", () => {
|
||||
await act(async () => root.render(element(true)));
|
||||
const editor = () => container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Issue chat editor"]')!;
|
||||
expect(editor().value).toBe(localText);
|
||||
expect(container.textContent).not.toContain("We couldn’t confirm");
|
||||
expect(container.textContent).not.toContain("Sending when reconnected…");
|
||||
if (scenario === "unavailable recovery storage") expect(container.textContent).toContain("copy your text before leaving");
|
||||
if (scenario.includes("with new attachments")) expect(container.textContent).toContain("another-tab.txt");
|
||||
if (scenario === "foreign pending receipt") {
|
||||
@@ -3455,7 +3607,7 @@ describe("IssueChatThread", () => {
|
||||
expect(localStorage.getItem(`${key}:submission:v1`)).toBeNull();
|
||||
expect(localStorage.getItem(`${key}:attachments:v1`)).toContain(attachmentId);
|
||||
expect(container.textContent).toContain("next-draft.txt");
|
||||
expect(container.textContent).not.toContain("We couldn’t confirm");
|
||||
expect(container.textContent).not.toContain("Sending when reconnected…");
|
||||
await act(async () => root.unmount());
|
||||
await act(async () => resolveSend());
|
||||
expect(localStorage.getItem(key)).toBe("Newer unsent draft");
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useCurrentAccountGuard } from "../hooks/useAccountBoundMutation";
|
||||
import { resolveIssueChatHumanAuthor } from "@/lib/issue-chat-human-author";
|
||||
import { useCurrentWorkspaceRetry, useWorkspaceBaseRefRecovery, useWorkspaceRetry } from "./WorkspaceBaseRefRecovery";
|
||||
import { WorkspaceBaseRefRecoveryNotice } from "./WorkspaceBaseRefRecoveryNotice";
|
||||
@@ -76,12 +77,20 @@ import {
|
||||
loadDraftAttachments,
|
||||
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 { useAutoResend } from "../hooks/useDurableSubmit";
|
||||
import { useDraftOwner } from "../hooks/useDraftOwner";
|
||||
import { useRequestOwnerBinding } from "../hooks/useRequestOwnerBinding";
|
||||
import { PendingSendNotice } from "./PendingSendNotice";
|
||||
import { describeError } from "../api/errors";
|
||||
import {
|
||||
buildIssueChatMessages,
|
||||
formatDurationWords,
|
||||
@@ -236,6 +245,7 @@ import {
|
||||
} from "@/components/ui/popover";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
RotateCw,
|
||||
AlertTriangle,
|
||||
ArrowRight,
|
||||
Brain,
|
||||
@@ -515,7 +525,6 @@ export interface IssueChatComposerHandle {
|
||||
interface IssueChatComposerProps {
|
||||
onSend: IssueChatThreadProps["onAdd"];
|
||||
confirmedSubmissionIds: ReadonlySet<string>;
|
||||
onReviewConversation?: () => Promise<void>;
|
||||
onStop?: () => Promise<void>;
|
||||
stopPending?: boolean;
|
||||
stopScope?: "leaf" | "subtree";
|
||||
@@ -627,7 +636,6 @@ interface IssueChatThreadProps {
|
||||
clientRequestId?: string,
|
||||
runSettings?: ComposerRunSettings,
|
||||
) => Promise<void>;
|
||||
onReviewConversation?: () => Promise<void>;
|
||||
onCancelRun?: () => Promise<void>;
|
||||
stopPending?: boolean;
|
||||
stopScope?: "leaf" | "subtree";
|
||||
@@ -990,6 +998,11 @@ type ComposerAttachmentItem = {
|
||||
inline: boolean;
|
||||
contentPath?: string;
|
||||
error?: 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;
|
||||
};
|
||||
|
||||
function hasFilePayload(evt: ReactDragEvent<HTMLDivElement>) {
|
||||
@@ -4651,7 +4664,6 @@ const IssueChatComposer = forwardRef<
|
||||
{
|
||||
onSend,
|
||||
confirmedSubmissionIds,
|
||||
onReviewConversation,
|
||||
onStop,
|
||||
stopPending,
|
||||
stopScope = "leaf",
|
||||
@@ -4694,11 +4706,13 @@ const IssueChatComposer = forwardRef<
|
||||
// the stored draft. The effect below handles subsequent task-key changes.
|
||||
const [body, setBody] = useState(() => (draftKey ? loadDraft(draftKey) : ""));
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [reviewError, setReviewError] = useState(false);
|
||||
const [uncertainSubmission, setUncertainSubmission] =
|
||||
useState<ComposerDraftSubmission | null>(() =>
|
||||
draftKey ? loadDraftSubmission(draftKey) : null,
|
||||
);
|
||||
// Attempts this composer resent and saw confirmed; they settle exactly like
|
||||
// a receipt that arrives through the thread.
|
||||
const [resentSubmissionIds, setResentSubmissionIds] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const mountedTaskKey = useRef(draftKey);
|
||||
useEffect(() => {
|
||||
mountedTaskKey.current = draftKey;
|
||||
@@ -4710,12 +4724,20 @@ const IssueChatComposer = forwardRef<
|
||||
const bodyRef = useRef(body);
|
||||
bodyRef.current = body;
|
||||
const reconciledSubmissionRef = useRef<{ draftKey: string | undefined; attemptId: string } | null>(null);
|
||||
// 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(update: string | ((current: string) => string)) {
|
||||
const value = typeof update === "function" ? update(bodyRef.current) : update;
|
||||
bodyRef.current = value;
|
||||
@@ -4732,6 +4754,8 @@ const IssueChatComposer = forwardRef<
|
||||
attemptId: pending.attemptId, reviewed: false,
|
||||
nextDraftOffset: pending.submittedBody.length + (value ? 2 : 0),
|
||||
submittedAttachmentIds: pending.submittedAttachmentIds,
|
||||
request: pending.request,
|
||||
requestOwner: pending.requestOwner,
|
||||
});
|
||||
}
|
||||
const submittingRef = useRef(submitting);
|
||||
@@ -4847,7 +4871,10 @@ const IssueChatComposer = forwardRef<
|
||||
// A server receipt for this exact request settles a restored submission.
|
||||
// Text equality is not delivery proof: users may intentionally repeat text.
|
||||
useEffect(() => {
|
||||
if (!uncertainSubmission || !confirmedSubmissionIds.has(uncertainSubmission.attemptId)) return;
|
||||
if (
|
||||
!uncertainSubmission ||
|
||||
!(confirmedSubmissionIds.has(uncertainSubmission.attemptId) || resentSubmissionIds.has(uncertainSubmission.attemptId))
|
||||
) return;
|
||||
const { attemptId } = uncertainSubmission;
|
||||
const reconciled = reconciledSubmissionRef.current;
|
||||
if (reconciled && reconciled.draftKey === draftKey && reconciled.attemptId === attemptId) return;
|
||||
@@ -4891,7 +4918,48 @@ const IssueChatComposer = forwardRef<
|
||||
setBody(nextDraft);
|
||||
bodyRef.current = nextDraft;
|
||||
setComposerAttachments(nextAttachments);
|
||||
}, [confirmedSubmissionIds, draftKey, sharedDraftKey, uncertainSubmission]);
|
||||
}, [confirmedSubmissionIds, draftKey, resentSubmissionIds, sharedDraftKey, uncertainSubmission]);
|
||||
|
||||
async function resendUncertainSubmission(): Promise<SendOutcome> {
|
||||
if (!isCurrentAccount()) return "pending";
|
||||
const submission = uncertainSubmission;
|
||||
const request = replayableRequest(submission, draftOwner);
|
||||
if (!submission || !request) return "rejected";
|
||||
const taskKey = draftKey;
|
||||
const args = [
|
||||
request.body,
|
||||
request.reopen,
|
||||
request.reassignment,
|
||||
request.attachmentIds,
|
||||
submission.attemptId,
|
||||
] as const;
|
||||
try {
|
||||
if (request.runSettings) await onSend(...args, request.runSettings as unknown as ComposerRunSettings);
|
||||
else await onSend(...args);
|
||||
} catch (error) {
|
||||
if (!isCurrentAccount()) return "pending";
|
||||
const failure = classifySendFailure(error);
|
||||
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);
|
||||
}
|
||||
return failure;
|
||||
}
|
||||
if (mountedTaskKey.current === taskKey) {
|
||||
setResentSubmissionIds((current) => new Set([...current, submission.attemptId]));
|
||||
} else if (taskKey) {
|
||||
settleDraftSubmission(taskKey, submission.attemptId);
|
||||
}
|
||||
return "sent";
|
||||
}
|
||||
|
||||
const resendSourceId = useId();
|
||||
const autoResend = useAutoResend({
|
||||
sourceId: `issue-chat-composer:${resendSourceId}`,
|
||||
active: Boolean(replayableRequest(uncertainSubmission, draftOwner)) && !submitting,
|
||||
resend: resendUncertainSubmission,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
@@ -5050,6 +5118,8 @@ const IssueChatComposer = forwardRef<
|
||||
bodyRef.current = "";
|
||||
setBody("");
|
||||
let attemptId: string | null = null;
|
||||
let request: ComposerSendRequest | null = null;
|
||||
const requestOwner = draftOwner;
|
||||
try {
|
||||
if (workModeChanged && onWorkModeChange) {
|
||||
await onWorkModeChange(pendingWorkMode);
|
||||
@@ -5061,10 +5131,20 @@ const IssueChatComposer = forwardRef<
|
||||
return;
|
||||
}
|
||||
attemptId = crypto.randomUUID();
|
||||
if (requestOwner === undefined) markRequestUnbound(attemptId);
|
||||
// The exact request is stored before it is sent, so a lost response or
|
||||
// an outage can resend it with the same ID instead of losing it.
|
||||
request = {
|
||||
body: submittedBody,
|
||||
...(reopen === undefined ? {} : { reopen }),
|
||||
...(reassignment ? { reassignment } : {}),
|
||||
...(attachmentIds.length ? { attachmentIds } : {}),
|
||||
...(runSettings ? { runSettings: runSettings as unknown as Record<string, unknown> } : {}),
|
||||
};
|
||||
if (draftKey) {
|
||||
saveDraft(draftKey, trimmed);
|
||||
saveDraftSubmission(draftKey, { attemptId, reviewed: false });
|
||||
pendingDraftRef.current = { draftKey, attemptId, submittedBody: trimmed, submittedAttachmentIds: attachmentIds };
|
||||
saveDraftSubmission(draftKey, { attemptId, reviewed: false, request, requestOwner });
|
||||
pendingDraftRef.current = { draftKey, attemptId, submittedBody: trimmed, submittedAttachmentIds: attachmentIds, request, requestOwner };
|
||||
changeBody(bodyRef.current);
|
||||
}
|
||||
// assistant-ui thread.append is fire-and-forget. Await the actual Board
|
||||
@@ -5090,11 +5170,15 @@ const IssueChatComposer = forwardRef<
|
||||
} 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: trimmed.length + (nextDraft ? 2 : 0),
|
||||
submittedAttachmentIds: attachmentIds,
|
||||
request,
|
||||
requestOwner,
|
||||
};
|
||||
setUncertainSubmission(uncertain);
|
||||
if (draftKey && loadDraftSubmission(draftKey)?.attemptId === attemptId)
|
||||
@@ -5197,7 +5281,8 @@ const IssueChatComposer = forwardRef<
|
||||
? {
|
||||
...item,
|
||||
status: "error",
|
||||
error: err instanceof Error ? err.message : "Upload failed",
|
||||
error: describeError(err, { action: "upload the file" }).body,
|
||||
file,
|
||||
}
|
||||
: item,
|
||||
),
|
||||
@@ -5205,6 +5290,14 @@ const IssueChatComposer = forwardRef<
|
||||
}
|
||||
}
|
||||
|
||||
/** Retry a failed upload from its kept file; only ever on an explicit click. */
|
||||
function retryUpload(attachment: ComposerAttachmentItem) {
|
||||
const file = attachment.file;
|
||||
if (!file) return;
|
||||
setComposerAttachments((current) => current.filter((item) => item.id !== attachment.id));
|
||||
void attachFile(file);
|
||||
}
|
||||
|
||||
async function handleAttachFile(evt: ChangeEvent<HTMLInputElement>) {
|
||||
const file = evt.target.files?.[0];
|
||||
if (!file) return;
|
||||
@@ -5422,67 +5515,19 @@ const IssueChatComposer = forwardRef<
|
||||
</p>
|
||||
) : null}
|
||||
{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={async () => {
|
||||
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);
|
||||
}
|
||||
}}
|
||||
>
|
||||
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={() => {
|
||||
if (draftKey)
|
||||
clearDraft(draftKey, uncertainSubmission.attemptId);
|
||||
bodyRef.current = "";
|
||||
setBody("");
|
||||
setComposerAttachments([]);
|
||||
setUncertainSubmission(null);
|
||||
}}
|
||||
>
|
||||
Discard draft and start new
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
<PendingSendNotice
|
||||
className="mb-3"
|
||||
noun="comment"
|
||||
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={() => {
|
||||
// Stop resending; the text stays in the editor to edit or send again.
|
||||
if (draftKey) clearDraftSubmission(draftKey, uncertainSubmission.attemptId);
|
||||
setUncertainSubmission(null);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<MarkdownEditor
|
||||
ref={editorRef}
|
||||
@@ -5568,6 +5613,18 @@ const IssueChatComposer = forwardRef<
|
||||
<span className="shrink-0 text-muted-foreground">
|
||||
{statusLabel}
|
||||
</span>
|
||||
{attachment.status === "error" && attachment.file ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label={`Retry ${attachment.name}`}
|
||||
disabled={!!uncertainSubmission}
|
||||
onClick={() => retryUpload(attachment)}
|
||||
>
|
||||
<RotateCw className="h-3.5 w-3.5" aria-hidden />
|
||||
</Button>
|
||||
) : null}
|
||||
{!attachment.inline || attachment.status !== "attached" ? (
|
||||
<Button
|
||||
type="button"
|
||||
@@ -5799,7 +5856,6 @@ export function IssueChatThread({
|
||||
userProfileMap,
|
||||
onVote,
|
||||
onAdd,
|
||||
onReviewConversation,
|
||||
onCancelRun,
|
||||
stopPending,
|
||||
stopScope,
|
||||
@@ -6798,7 +6854,6 @@ export function IssueChatThread({
|
||||
<IssueChatComposer
|
||||
ref={composerRef}
|
||||
onSend={sendComposerComment}
|
||||
onReviewConversation={onReviewConversation}
|
||||
onImageUpload={imageUploadHandler}
|
||||
onAttachImage={onAttachImage}
|
||||
draftKey={draftKey}
|
||||
|
||||
@@ -24,6 +24,8 @@ const mockIssuesApi = vi.hoisted(() => ({
|
||||
|
||||
const markdownEditorMockState = vi.hoisted(() => ({
|
||||
emitMountEmptyChange: false,
|
||||
/** Typed into the editor on mount, for forms the test cannot type into. */
|
||||
emitMountValue: null as string | null,
|
||||
}));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -48,13 +50,14 @@ vi.mock("../api/issues", () => ({
|
||||
issuesApi: mockIssuesApi,
|
||||
}));
|
||||
|
||||
vi.mock("../hooks/useAutosaveIndicator", () => ({
|
||||
useAutosaveIndicator: () => ({
|
||||
state: "idle",
|
||||
markDirty: vi.fn(),
|
||||
reset: vi.fn(),
|
||||
runSave: async (save: () => Promise<unknown>) => save(),
|
||||
}),
|
||||
const mockSession = vi.hoisted(() => ({ userId: "user-1", unreachable: false }));
|
||||
vi.mock("../api/auth", () => ({
|
||||
authApi: {
|
||||
getSession: async () => {
|
||||
if (mockSession.unreachable) throw new Error("Service unavailable");
|
||||
return { user: { id: mockSession.userId } };
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/router", () => ({
|
||||
@@ -92,6 +95,10 @@ vi.mock("./MarkdownEditor", async () => {
|
||||
contentClassName?: string;
|
||||
}) => {
|
||||
React.useEffect(() => {
|
||||
if (markdownEditorMockState.emitMountValue !== null) {
|
||||
onChange?.(markdownEditorMockState.emitMountValue);
|
||||
return;
|
||||
}
|
||||
if (!markdownEditorMockState.emitMountEmptyChange) return;
|
||||
onChange?.("");
|
||||
}, []);
|
||||
@@ -293,6 +300,8 @@ describe("IssueDocumentsSection", () => {
|
||||
window.localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
markdownEditorMockState.emitMountEmptyChange = false;
|
||||
markdownEditorMockState.emitMountValue = null;
|
||||
mockSession.unreachable = false;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -872,6 +881,220 @@ describe("IssueDocumentsSection", () => {
|
||||
queryClient.clear();
|
||||
});
|
||||
|
||||
it("does not restore another account's unsaved edit", async () => {
|
||||
const document = createIssueDocument({ body: "Server body" });
|
||||
const issue = createIssue();
|
||||
window.localStorage.setItem(
|
||||
`paperclip:document-draft:v2:user-2:${issue.id}:plan`,
|
||||
JSON.stringify({ key: "plan", title: "Plan", body: "Someone else's draft", baseRevisionId: "revision-4", isNew: false }),
|
||||
);
|
||||
mockIssuesApi.listDocuments.mockResolvedValue([document]);
|
||||
const root = createRoot(container);
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<IssueDocumentsSection issue={issue} canDeleteDocuments={false} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await flush();
|
||||
await flush();
|
||||
expect(container.textContent).toContain("Server body");
|
||||
expect(container.textContent).not.toContain("Someone else's draft");
|
||||
expect(mockIssuesApi.upsertDocument).not.toHaveBeenCalled();
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
queryClient.clear();
|
||||
window.localStorage.clear();
|
||||
});
|
||||
|
||||
it("drops a mounted editor's private draft when the signed-in account changes", async () => {
|
||||
const issue = createIssue();
|
||||
const document = createIssueDocument({ body: "Server plan" });
|
||||
mockIssuesApi.listDocuments.mockResolvedValue([document]);
|
||||
window.localStorage.setItem(`paperclip:document-draft:v2:user-1:${issue.id}:plan`, JSON.stringify({
|
||||
key: "plan", title: document.title ?? "", body: "Private unpublished text", baseRevisionId: "revision-4", isNew: false,
|
||||
}));
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity }, mutations: { retry: false } } });
|
||||
queryClient.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||||
const root = createRoot(container);
|
||||
await act(async () => { root.render(<QueryClientProvider client={queryClient}><IssueDocumentsSection issue={issue} canDeleteDocuments={false} /></QueryClientProvider>); });
|
||||
await flush(); await flush();
|
||||
expect(container.textContent).toContain("Private unpublished text");
|
||||
await act(async () => { queryClient.setQueryData(queryKeys.auth.session, { user: { id: "user-2" } }); });
|
||||
await flush();
|
||||
expect(window.localStorage.getItem(`paperclip:document-draft:v2:user-2:${issue.id}:plan`)).toBeNull();
|
||||
expect(container.textContent).not.toContain("Private unpublished text");
|
||||
act(() => root.unmount()); queryClient.clear();
|
||||
});
|
||||
it("restores task B without copying task A's mounted document draft", async () => {
|
||||
const a = createIssue();
|
||||
const b = { ...a, id: "task-b", identifier: "DOC-2" };
|
||||
const document = createIssueDocument({ body: "Server plan" });
|
||||
mockIssuesApi.listDocuments.mockResolvedValue([document]);
|
||||
const key = (id: string) => `paperclip:document-draft:v2:user-1:${id}:plan`;
|
||||
const stored = (body: string) => JSON.stringify({ key: "plan", title: "Plan", body, baseRevisionId: "revision-4", isNew: false });
|
||||
localStorage.setItem(key(a.id), stored("Task A private edit"));
|
||||
const originalB = stored("Task B private edit");
|
||||
localStorage.setItem(key(b.id), originalB);
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity }, mutations: { retry: false } } });
|
||||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||||
client.setQueryData(queryKeys.issues.documents(a.id), [document]);
|
||||
client.setQueryData(queryKeys.issues.documents(b.id), [document]);
|
||||
const root = createRoot(container);
|
||||
const show = (issue: Issue) => root.render(<QueryClientProvider client={client}><IssueDocumentsSection issue={issue} canDeleteDocuments={false} /></QueryClientProvider>);
|
||||
try {
|
||||
await act(async () => show(a)); await flush();
|
||||
expect(container.textContent).toContain("Task A private edit");
|
||||
await act(async () => show(b)); await flush();
|
||||
expect(container.textContent).not.toContain("Task A private edit");
|
||||
expect(container.textContent).toContain("Task B private edit");
|
||||
expect(localStorage.getItem(key(b.id))).toBe(originalB);
|
||||
} finally { act(() => root.unmount()); client.clear(); localStorage.clear(); }
|
||||
});
|
||||
|
||||
it("keeps the known account's drafts while a session refetch fails", async () => {
|
||||
const document = createIssueDocument({ body: "Server body" });
|
||||
const issue = createIssue();
|
||||
window.localStorage.setItem(
|
||||
`paperclip:document-draft:v2:user-1:${issue.id}:plan`,
|
||||
JSON.stringify({ key: "plan", title: "Plan", body: "Typed before the outage", baseRevisionId: "revision-4", isNew: false }),
|
||||
);
|
||||
mockIssuesApi.listDocuments.mockResolvedValue([document]);
|
||||
mockSession.unreachable = true;
|
||||
const root = createRoot(container);
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
|
||||
// Signed in earlier; the refetch on mount fails but the query keeps its data.
|
||||
queryClient.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } }, { updatedAt: 0 });
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<IssueDocumentsSection issue={issue} canDeleteDocuments={false} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await flush();
|
||||
await flush();
|
||||
expect(queryClient.getQueryState(queryKeys.auth.session)?.status).toBe("error");
|
||||
expect(container.textContent).toContain("Typed before the outage");
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
queryClient.clear();
|
||||
window.localStorage.clear();
|
||||
});
|
||||
|
||||
it("restores an unsaved edit after reload and treats a 409 with our own text as saved", async () => {
|
||||
const { ApiError } = await import("../api/client");
|
||||
const document = createIssueDocument({ body: "Server body" });
|
||||
const issue = createIssue();
|
||||
// An edit typed before a reload; its save may have landed with a lost response.
|
||||
window.localStorage.setItem(
|
||||
`paperclip:document-draft:v2:user-1:${issue.id}:plan`,
|
||||
JSON.stringify({ key: "plan", title: "Plan", body: "Edited during the outage", baseRevisionId: "revision-4", isNew: false }),
|
||||
);
|
||||
const saved = createIssueDocument({ body: "Edited during the outage", latestRevisionId: "revision-5" });
|
||||
// The refetch after saving returns the server's current copy.
|
||||
mockIssuesApi.listDocuments.mockResolvedValueOnce([document]).mockResolvedValue([saved]);
|
||||
mockIssuesApi.upsertDocument.mockRejectedValue(
|
||||
new ApiError("Document was updated by someone else", 409, { error: "Document was updated by someone else" }),
|
||||
);
|
||||
mockIssuesApi.getDocument.mockResolvedValue(saved);
|
||||
const root = createRoot(container);
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<IssueDocumentsSection issue={issue} canDeleteDocuments={false} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await flush();
|
||||
await flush();
|
||||
expect(container.textContent).toContain("Edited during the outage");
|
||||
|
||||
// Autosave debounce.
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1_100));
|
||||
});
|
||||
await flush();
|
||||
|
||||
expect(mockIssuesApi.upsertDocument).toHaveBeenCalledWith(issue.id, "plan", expect.objectContaining({
|
||||
body: "Edited during the outage",
|
||||
baseRevisionId: "revision-4",
|
||||
}));
|
||||
expect(container.textContent).not.toContain("Out of date");
|
||||
expect(window.localStorage.getItem(`paperclip:document-draft:v2:user-1:${issue.id}:plan`)).toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
queryClient.clear();
|
||||
});
|
||||
|
||||
it("treats a 409 on a new document whose saved copy is ours as created", async () => {
|
||||
const { ApiError } = await import("../api/client");
|
||||
const issue = createIssue();
|
||||
// An earlier create landed but its response was lost; the key now exists.
|
||||
const saved = createIssueDocument({ key: "notes", title: null, body: "Notes body", latestRevisionId: "revision-1" });
|
||||
mockIssuesApi.listDocuments.mockResolvedValueOnce([]).mockResolvedValue([saved]);
|
||||
mockIssuesApi.upsertDocument.mockRejectedValue(
|
||||
new ApiError("Document already exists", 409, { error: "Document already exists" }),
|
||||
);
|
||||
mockIssuesApi.getDocument.mockResolvedValue(saved);
|
||||
markdownEditorMockState.emitMountValue = "Notes body";
|
||||
const root = createRoot(container);
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<IssueDocumentsSection issue={issue} canDeleteDocuments={false} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await flush();
|
||||
|
||||
const newDocument = Array.from(container.querySelectorAll("button"))
|
||||
.find((button) => button.textContent?.includes("New document"))!;
|
||||
await act(async () => {
|
||||
newDocument.click();
|
||||
});
|
||||
const keyInput = container.querySelector<HTMLInputElement>('input[placeholder="Document key"]')!;
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(keyInput, "notes");
|
||||
keyInput.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
const create = Array.from(container.querySelectorAll("button"))
|
||||
.find((button) => button.textContent?.includes("Create document"))!;
|
||||
await act(async () => {
|
||||
create.click();
|
||||
});
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
expect(mockIssuesApi.upsertDocument).toHaveBeenCalledWith(issue.id, "notes", expect.objectContaining({
|
||||
body: "Notes body",
|
||||
baseRevisionId: null,
|
||||
}));
|
||||
expect(mockIssuesApi.getDocument).toHaveBeenCalledWith(issue.id, "notes");
|
||||
// The form closes as for any created document; no conflict, no error.
|
||||
expect(container.querySelector('input[placeholder="Document key"]')).toBeNull();
|
||||
expect(container.textContent).not.toContain("Out of date");
|
||||
expect(container.textContent).not.toContain("already exists");
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
queryClient.clear();
|
||||
});
|
||||
|
||||
it("forwards externalReferences to the rendered document body so URL decoration applies", async () => {
|
||||
const issue = createIssue();
|
||||
const root = createRoot(container);
|
||||
|
||||
@@ -14,11 +14,14 @@ import { isSystemIssueDocumentKey } from "@paperclipai/shared";
|
||||
import { useLocation } from "@/lib/router";
|
||||
import { ApiError } from "../api/client";
|
||||
import { issuesApi } from "../api/issues";
|
||||
import { useAutosaveIndicator } from "../hooks/useAutosaveIndicator";
|
||||
import { useDurableAutosave } from "../hooks/useDurableAutosave";
|
||||
import { describeError } from "../api/errors";
|
||||
import { loadStructuredDraft, saveStructuredDraft } from "../lib/composer-draft";
|
||||
import { copyTextToClipboard } from "../lib/clipboard";
|
||||
import { deriveDocumentRevisionState } from "../lib/document-revisions";
|
||||
import type { CompanyUserProfile } from "../lib/company-members";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
import { useDraftOwner } from "../hooks/useDraftOwner";
|
||||
import { cn, relativeTime } from "../lib/utils";
|
||||
import { FoldCurtain } from "./FoldCurtain";
|
||||
import { DocumentAnnotationsCountChip, IssueDocumentAnnotations } from "./IssueDocumentAnnotations";
|
||||
@@ -134,6 +137,38 @@ function isLockedDocumentError(error: unknown) {
|
||||
return error instanceof ApiError && error.status === 409 && error.message === "Document is locked";
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsaved document edits live here until the server confirms them. The scope
|
||||
* names the signed-in user as well as the document, so another account in the
|
||||
* same browser never restores (or autosaves) someone else's unpublished text.
|
||||
* A null scope (the session is still loading) stores and restores nothing.
|
||||
*/
|
||||
function documentDraftStorageKey(scope: string, key: string) {
|
||||
return `paperclip:document-draft:v2:${scope}:${key}`;
|
||||
}
|
||||
|
||||
function loadStoredDocumentDraft(scope: string | null, key: string): DraftState | null {
|
||||
if (!scope) return null;
|
||||
const stored = loadStructuredDraft<Partial<DraftState> | null>(documentDraftStorageKey(scope, key), null);
|
||||
if (
|
||||
!stored ||
|
||||
stored.key !== key ||
|
||||
typeof stored.body !== "string" ||
|
||||
typeof stored.title !== "string" ||
|
||||
(stored.baseRevisionId !== null && typeof stored.baseRevisionId !== "string")
|
||||
) return null;
|
||||
return { key, title: stored.title, body: stored.body, baseRevisionId: stored.baseRevisionId ?? null, isNew: false };
|
||||
}
|
||||
|
||||
function clearStoredDocumentDraft(scope: string | null, key: string) {
|
||||
if (!scope) return;
|
||||
try {
|
||||
localStorage.removeItem(documentDraftStorageKey(scope, key));
|
||||
} catch {
|
||||
// Unavailable storage holds nothing to clear.
|
||||
}
|
||||
}
|
||||
|
||||
function downloadDocumentFile(key: string, body: string) {
|
||||
const blob = new Blob([body], { type: "text/markdown;charset=utf-8" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
@@ -242,7 +277,7 @@ function makeIssueDocumentSubject(issue: Issue): DocumentSubjectConfig {
|
||||
};
|
||||
}
|
||||
|
||||
export function IssueDocumentsSection({
|
||||
function AccountIssueDocumentsSection({
|
||||
issue,
|
||||
subject,
|
||||
canDeleteDocuments,
|
||||
@@ -308,6 +343,8 @@ export function IssueDocumentsSection({
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [draft, setDraft] = useState<DraftState | null>(null);
|
||||
const [documentConflict, setDocumentConflict] = useState<DocumentConflictState | null>(null);
|
||||
const draftOwner = useDraftOwner();
|
||||
const draftScope = draftOwner !== undefined ? `${draftOwner}:${documentSubject.id}` : null;
|
||||
const [foldedDocumentKeys, setFoldedDocumentKeys] = useState<string[]>(() => loadFoldedDocumentKeys(documentSubject.id));
|
||||
const [annotationPanelOpenKeys, setAnnotationPanelOpenKeys] = useState<string[]>(
|
||||
() => (defaultAnnotationPanelOpenKeys ?? []),
|
||||
@@ -321,12 +358,17 @@ export function IssueDocumentsSection({
|
||||
const autosaveDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const copiedDocumentTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const hasScrolledToHashRef = useRef(false);
|
||||
const {
|
||||
state: autosaveState,
|
||||
markDirty,
|
||||
reset,
|
||||
runSave,
|
||||
} = useAutosaveIndicator();
|
||||
// Each save binds its own request and 409 check (see commitDraft).
|
||||
const autosave = useDurableAutosave<DraftState>({
|
||||
sourceId: `issue-documents:${documentSubject.id}`,
|
||||
targetKey: `${draftScope}:${draft?.key ?? ""}`,
|
||||
save: async () => undefined,
|
||||
action: "save the document",
|
||||
});
|
||||
const { markDirty, reset, run: runAutosave } = autosave;
|
||||
const autosaveState = autosave.status;
|
||||
const autosaveStateRef = useRef(autosaveState);
|
||||
autosaveStateRef.current = autosaveState;
|
||||
|
||||
const { data: documents } = useQuery({
|
||||
queryKey: documentSubject.documentsQueryKey,
|
||||
@@ -486,7 +528,12 @@ export function IssueDocumentsSection({
|
||||
const beginEdit = (key: string) => {
|
||||
const doc = sortedDocuments.find((entry) => entry.key === key);
|
||||
if (!doc) return;
|
||||
const conflictedDraft = documentConflict?.key === key ? documentConflict.localDraft : null;
|
||||
const storedDraft = loadStoredDocumentDraft(draftScope, key);
|
||||
const conflictedDraft = documentConflict?.key === key
|
||||
? documentConflict.localDraft
|
||||
: storedDraft && (storedDraft.body !== doc.body || storedDraft.title !== (doc.title ?? ""))
|
||||
? storedDraft
|
||||
: null;
|
||||
setFoldedDocumentKeys((current) => current.filter((entry) => entry !== key));
|
||||
resetAutosaveState();
|
||||
setDocumentConflict((current) => current?.key === key ? current : null);
|
||||
@@ -515,6 +562,7 @@ export function IssueDocumentsSection({
|
||||
if (autosaveDebounceRef.current) {
|
||||
clearTimeout(autosaveDebounceRef.current);
|
||||
}
|
||||
if (draft && !draft.isNew) clearStoredDocumentDraft(draftScope, draft.key);
|
||||
resetAutosaveState();
|
||||
setDocumentConflict(null);
|
||||
setDraft(null);
|
||||
@@ -574,16 +622,17 @@ export function IssueDocumentsSection({
|
||||
return true;
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
const saved = await upsertDocument.mutateAsync({
|
||||
...currentDraft,
|
||||
key: normalizedKey,
|
||||
title: isPlanKey(normalizedKey) ? "" : normalizedTitle,
|
||||
body: currentDraft.body,
|
||||
baseRevisionId: options?.overrideConflict
|
||||
? activeConflict?.serverDocument.latestRevisionId ?? currentDraft.baseRevisionId
|
||||
: currentDraft.baseRevisionId,
|
||||
});
|
||||
const attempted: DraftState = {
|
||||
...currentDraft,
|
||||
key: normalizedKey,
|
||||
title: isPlanKey(normalizedKey) ? "" : normalizedTitle,
|
||||
body: currentDraft.body,
|
||||
baseRevisionId: options?.overrideConflict
|
||||
? activeConflict?.serverDocument.latestRevisionId ?? currentDraft.baseRevisionId
|
||||
: currentDraft.baseRevisionId,
|
||||
};
|
||||
const applySaved = (saved: IssueDocument) => {
|
||||
clearStoredDocumentDraft(draftScope, normalizedKey);
|
||||
setError(null);
|
||||
setDocumentConflict((current) => current?.key === normalizedKey ? null : current);
|
||||
setDraft((value) => {
|
||||
@@ -592,7 +641,8 @@ export function IssueDocumentsSection({
|
||||
return {
|
||||
key: saved.key,
|
||||
title: saved.title ?? "",
|
||||
body: saved.body,
|
||||
// Keep text typed while this save was in flight.
|
||||
body: value.body === currentDraft.body ? saved.body : value.body,
|
||||
baseRevisionId: saved.latestRevisionId,
|
||||
isNew: false,
|
||||
};
|
||||
@@ -600,16 +650,22 @@ export function IssueDocumentsSection({
|
||||
syncDocumentCaches(saved);
|
||||
invalidateIssueDocuments();
|
||||
};
|
||||
|
||||
try {
|
||||
if (options?.trackAutosave) {
|
||||
setAutosaveDocumentKey(normalizedKey);
|
||||
await runSave(save);
|
||||
} else {
|
||||
await save();
|
||||
}
|
||||
const save = async () => {
|
||||
applySaved(await upsertDocument.mutateAsync(attempted));
|
||||
};
|
||||
// A retry after a lost response finds its own earlier save: the base
|
||||
// revision is stale (or, for a new document, the key now exists), but the
|
||||
// server already holds exactly this text.
|
||||
const matchesServer = async (error: unknown) => {
|
||||
if (isLockedDocumentError(error)) return false;
|
||||
const latest = await documentSubject.getDocument(normalizedKey);
|
||||
if (latest.body !== currentDraft.body) return false;
|
||||
if (!isPlanKey(normalizedKey) && (latest.title ?? "") !== normalizedTitle) return false;
|
||||
applySaved(latest);
|
||||
return true;
|
||||
} catch (err) {
|
||||
};
|
||||
|
||||
const handleSaveFailure = async (err: unknown): Promise<false> => {
|
||||
if (isLockedDocumentError(err)) {
|
||||
setError("Document is locked. Unlock it before editing.");
|
||||
resetAutosaveState();
|
||||
@@ -640,14 +696,27 @@ export function IssueDocumentsSection({
|
||||
return false;
|
||||
}
|
||||
}
|
||||
setError(err instanceof Error ? err.message : "Failed to save document");
|
||||
setError(describeError(err, { action: "save the document" }).body);
|
||||
return false;
|
||||
}
|
||||
}, [documentConflict, documentSubject, invalidateIssueDocuments, resetAutosaveState, runSave, sortedDocuments, syncDocumentCaches, upsertDocument]);
|
||||
};
|
||||
|
||||
if (options?.trackAutosave) setAutosaveDocumentKey(normalizedKey);
|
||||
const result = await runAutosave(attempted, {
|
||||
save,
|
||||
matchesServer,
|
||||
// A retry after an outage reports a lock or a conflict the same way.
|
||||
onRetryFailed: (err) => void handleSaveFailure(err),
|
||||
});
|
||||
if (result.kind === "saved") return true;
|
||||
// Kept on this device; it saves when the connection allows.
|
||||
if (result.kind === "waiting") return false;
|
||||
return handleSaveFailure(result.error);
|
||||
}, [documentConflict, documentSubject, draftScope, invalidateIssueDocuments, resetAutosaveState, runAutosave, sortedDocuments, syncDocumentCaches, upsertDocument]);
|
||||
|
||||
const reloadDocumentFromServer = useCallback((key: string) => {
|
||||
if (documentConflict?.key !== key) return;
|
||||
const serverDocument = documentConflict.serverDocument;
|
||||
clearStoredDocumentDraft(draftScope, key);
|
||||
setDraft({
|
||||
key: serverDocument.key,
|
||||
title: serverDocument.title ?? "",
|
||||
@@ -658,7 +727,7 @@ export function IssueDocumentsSection({
|
||||
setDocumentConflict(null);
|
||||
resetAutosaveState();
|
||||
setError(null);
|
||||
}, [documentConflict, resetAutosaveState]);
|
||||
}, [documentConflict, draftScope, resetAutosaveState]);
|
||||
|
||||
const overwriteDocumentFromDraft = useCallback(async (key: string) => {
|
||||
if (documentConflict?.key !== key) return;
|
||||
@@ -831,6 +900,39 @@ export function IssueDocumentsSection({
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Persist every unsaved edit so a reload or an outage cannot lose it.
|
||||
useEffect(() => {
|
||||
if (!draft || draft.isNew) return;
|
||||
const existing = sortedDocuments.find((doc) => doc.key === draft.key);
|
||||
if (!existing) return;
|
||||
if (existing.body === draft.body && (existing.title ?? "") === draft.title) {
|
||||
clearStoredDocumentDraft(draftScope, draft.key);
|
||||
} else if (draftScope) {
|
||||
saveStructuredDraft(documentDraftStorageKey(draftScope, draft.key), draft);
|
||||
}
|
||||
}, [draftScope, draft, sortedDocuments]);
|
||||
|
||||
// After a reload, reopen the first document with an unsaved edit; the
|
||||
// autosave below then saves it.
|
||||
const restoredStoredDraftRef = useRef(false);
|
||||
useEffect(() => {
|
||||
// Wait for the session: the stored draft belongs to one user.
|
||||
if (restoredStoredDraftRef.current || !documents || !draftScope) return;
|
||||
restoredStoredDraftRef.current = true;
|
||||
if (draft) return;
|
||||
for (const doc of sortedDocuments) {
|
||||
const stored = loadStoredDocumentDraft(draftScope, doc.key);
|
||||
if (!stored) continue;
|
||||
if (stored.body === doc.body && stored.title === (doc.title ?? "")) {
|
||||
clearStoredDocumentDraft(draftScope, doc.key);
|
||||
continue;
|
||||
}
|
||||
beginEdit(doc.key);
|
||||
return;
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [documents, draftScope]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!draft || draft.isNew) return;
|
||||
if (documentConflict?.key === draft.key) return;
|
||||
@@ -840,7 +942,7 @@ export function IssueDocumentsSection({
|
||||
existing.body !== draft.body ||
|
||||
(existing.title ?? "") !== draft.title;
|
||||
if (!hasChanges) {
|
||||
if (autosaveState !== "saved") {
|
||||
if (autosaveStateRef.current !== "saved") {
|
||||
resetAutosaveState();
|
||||
}
|
||||
return;
|
||||
@@ -858,7 +960,7 @@ export function IssueDocumentsSection({
|
||||
clearTimeout(autosaveDebounceRef.current);
|
||||
}
|
||||
};
|
||||
}, [autosaveState, commitDraft, documentConflict, draft, markDocumentDirty, resetAutosaveState, sortedDocuments]);
|
||||
}, [commitDraft, documentConflict, draft, markDocumentDirty, resetAutosaveState, sortedDocuments]);
|
||||
|
||||
const documentBodyShellClassName = "mt-3";
|
||||
const documentBodyPaddingClassName = "";
|
||||
@@ -1309,7 +1411,7 @@ export function IssueDocumentsSection({
|
||||
bodyMarkdown={displayedBody}
|
||||
draftDirty={Boolean(activeDraft) && (
|
||||
(activeDraft?.body ?? doc.body) !== doc.body
|
||||
|| (autosaveDocumentKey === doc.key && autosaveState === "saving")
|
||||
|| (autosaveDocumentKey === doc.key && (autosaveState === "saving" || autosaveState === "waiting"))
|
||||
)}
|
||||
draftConflicted={Boolean(activeConflict)}
|
||||
historicalPreview={isHistoricalPreview}
|
||||
@@ -1343,16 +1445,11 @@ export function IssueDocumentsSection({
|
||||
? activeConflict
|
||||
? "Out of date"
|
||||
: autosaveDocumentKey === doc.key
|
||||
? autosaveState === "saving"
|
||||
? "Autosaving..."
|
||||
: autosaveState === "saved"
|
||||
? "Saved"
|
||||
: autosaveState === "error"
|
||||
? "Could not save"
|
||||
: ""
|
||||
? autosave.label ?? ""
|
||||
: ""
|
||||
: ""}
|
||||
</span>
|
||||
{activeDraft && autosaveDocumentKey === doc.key && autosaveState === "stalled" ? <Button type="button" size="sm" variant="ghost" onClick={autosave.resendNow}>Retry saving</Button> : null}
|
||||
</div>
|
||||
{canVoteOnDocument && doc.latestRevisionId ? (
|
||||
<OutputFeedbackButtons
|
||||
@@ -1414,3 +1511,14 @@ export function IssueDocumentsSection({
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function IssueDocumentsSection(props: Parameters<typeof AccountIssueDocumentsSection>[0]) {
|
||||
const owner = useDraftOwner();
|
||||
const previousOwner = useRef(owner);
|
||||
const generation = useRef(0);
|
||||
if (previousOwner.current !== owner) {
|
||||
if (previousOwner.current !== undefined) generation.current += 1;
|
||||
previousOwner.current = owner;
|
||||
}
|
||||
return <AccountIssueDocumentsSection key={JSON.stringify([generation.current, props.subject?.id ?? props.issue?.id])} {...props} />;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import { webcrypto } from "node:crypto";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
@@ -9,7 +10,7 @@ import { queryKeys } from "../lib/queryKeys";
|
||||
import { trackRecentAssignee, trackRecentAssigneeUser } from "../lib/recent-assignees";
|
||||
import { getLastProjectId, trackRecentProject } from "../lib/recent-projects";
|
||||
import { rememberComposerEffort } from "../lib/recent-composer-effort";
|
||||
import { NewIssueDialog } from "./NewIssueDialog";
|
||||
import { addStagedFilesToIssue, NewIssueDialog } from "./NewIssueDialog";
|
||||
|
||||
const primaryState = vi.hoisted(() => ({ primaryAgentId: null as string | null, loading: false }));
|
||||
vi.mock("./primary-agent/PrimaryAgentPresentation", () => ({ usePrimaryAgentPresentation: () => primaryState }));
|
||||
@@ -550,7 +551,7 @@ describe("NewIssueDialog", () => {
|
||||
primaryState.primaryAgentId = primary;
|
||||
if (recent) trackRecentAssignee(recent, "company-1");
|
||||
if (explicit) dialogState.newIssueDefaults = { assigneeAgentId: explicit };
|
||||
if (draft) localStorage.setItem("paperclip:issue-draft", JSON.stringify({ title: "Saved request", description: "", assigneeValue: `agent:${draft}`, projectId: "" }));
|
||||
if (draft) localStorage.setItem("paperclip:issue-draft:user-1", JSON.stringify({ title: "Saved request", description: "", assigneeValue: `agent:${draft}`, projectId: "" }));
|
||||
const { root } = renderDialog(container);
|
||||
await waitForAssertion(() => expect(container.querySelector('[data-testid="task-chat-composer-assignee-label"]')?.textContent).toBe(expected));
|
||||
act(() => root.unmount());
|
||||
@@ -747,7 +748,7 @@ describe("NewIssueDialog", () => {
|
||||
});
|
||||
|
||||
it("restores private visibility from a saved draft without a project", async () => {
|
||||
localStorage.setItem("paperclip:issue-draft", JSON.stringify({ title: "Private draft", description: "", status: "todo", priority: "", projectId: "", isPrivate: true }));
|
||||
localStorage.setItem("paperclip:issue-draft:user-1", JSON.stringify({ title: "Private draft", description: "", status: "todo", priority: "", projectId: "", isPrivate: true }));
|
||||
const { root } = renderDialog(container);
|
||||
await flush();
|
||||
const toggle = container.querySelector<HTMLButtonElement>('button[data-testid="composer-private-chip"]')!;
|
||||
@@ -807,7 +808,7 @@ describe("NewIssueDialog", () => {
|
||||
// Saving this form must retain only the explicit toggle choice. A later
|
||||
// standalone draft must not acquire a sticky private flag from its parent.
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 850)); });
|
||||
expect(JSON.parse(localStorage.getItem("paperclip:issue-draft")!).isPrivate).toBe(false);
|
||||
expect(JSON.parse(localStorage.getItem("paperclip:issue-draft:user-1")!).isPrivate).toBe(false);
|
||||
const submit = Array.from(container.querySelectorAll("button")).find(button => button.getAttribute("aria-label") === "Create sub-task")!;
|
||||
await act(async () => submit.click());
|
||||
await flush();
|
||||
@@ -1056,7 +1057,7 @@ describe("NewIssueDialog", () => {
|
||||
id: "project-1", name: "Alpha", workspaces: [{ id: "source-default", isPrimary: true }],
|
||||
executionWorkspacePolicy: { enabled: true, defaultMode: "isolated_workspace" },
|
||||
}]);
|
||||
localStorage.setItem("paperclip:issue-draft", JSON.stringify({
|
||||
localStorage.setItem("paperclip:issue-draft:user-1", JSON.stringify({
|
||||
title: "Draft task", description: "", status: "todo", priority: "medium", assigneeValue: "",
|
||||
reviewerValue: "", approverValue: "", projectId: "project-1",
|
||||
projectWorkspaceId: "stale-source", selectedExecutionWorkspaceId: "stale-workspace", executionWorkspaceMode: "reuse_existing",
|
||||
@@ -1327,7 +1328,7 @@ describe("NewIssueDialog", () => {
|
||||
|
||||
|
||||
it("restores a description-only draft", async () => {
|
||||
localStorage.setItem("paperclip:issue-draft", JSON.stringify({
|
||||
localStorage.setItem("paperclip:issue-draft:user-1", JSON.stringify({
|
||||
title: "", description: "Keep the request without a title", status: "todo", priority: "medium",
|
||||
assigneeValue: "", reviewerValue: "", approverValue: "", projectId: "",
|
||||
assigneeModelOverride: "", assigneeThinkingEffort: "", assigneeChrome: false,
|
||||
@@ -1565,6 +1566,300 @@ describe("NewIssueDialog", () => {
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("keeps a create that hit an outage and resends it with the same key", async () => {
|
||||
const { ApiError } = await import("../api/client");
|
||||
dialogState.newIssueDefaults = { title: "Created during a deploy" };
|
||||
mockIssuesApi.create
|
||||
.mockRejectedValueOnce(new ApiError("Unavailable", 503, { error: "tenant_app_unavailable" }))
|
||||
.mockResolvedValue({ id: "issue-created", identifier: "PAP-9", companyId: "company-1", projectId: null });
|
||||
const { root } = renderDialog(container);
|
||||
await flush();
|
||||
const button = (label: string) => Array.from(container.querySelectorAll("button"))
|
||||
.find((item) => item.getAttribute("aria-label") === label || item.textContent === label)!;
|
||||
|
||||
act(() => button("Create task").click());
|
||||
await waitForAssertion(() => expect(container.textContent).toContain("Sending when reconnected…"));
|
||||
expect(container.textContent).not.toContain("tenant_app_unavailable");
|
||||
expect(localStorage.getItem("paperclip:issue-draft:pending-create:user-1")).toContain(
|
||||
mockIssuesApi.create.mock.calls[0][1].idempotencyKey,
|
||||
);
|
||||
|
||||
// The waiting request is what gets created, so later edits are locked out.
|
||||
expect(container.querySelector<HTMLInputElement>('input[aria-label="Task title"]')?.disabled).toBe(true);
|
||||
|
||||
act(() => button("Resend now").click());
|
||||
await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledTimes(2));
|
||||
expect(mockIssuesApi.create.mock.calls[1][1].idempotencyKey).toBe(mockIssuesApi.create.mock.calls[0][1].idempotencyKey);
|
||||
await waitForAssertion(() => expect(dialogState.closeNewIssue).toHaveBeenCalled());
|
||||
expect(localStorage.getItem("paperclip:issue-draft:pending-create:user-1")).toBeNull();
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("shows why a resent create was rejected", async () => {
|
||||
const { ApiError } = await import("../api/client");
|
||||
dialogState.newIssueDefaults = { title: "Rejected on resend" };
|
||||
mockIssuesApi.create
|
||||
.mockRejectedValueOnce(new ApiError("Unavailable", 503, { error: "tenant_app_unavailable" }))
|
||||
.mockRejectedValueOnce(new ApiError("Project is archived", 422, { error: "Project is archived" }));
|
||||
const { root } = renderDialog(container);
|
||||
await flush();
|
||||
const button = (label: string) => Array.from(container.querySelectorAll("button"))
|
||||
.find((item) => item.getAttribute("aria-label") === label || item.textContent === label)!;
|
||||
|
||||
act(() => button("Create task").click());
|
||||
await waitForAssertion(() => expect(container.textContent).toContain("Sending when reconnected…"));
|
||||
act(() => button("Resend now").click());
|
||||
await waitForAssertion(() => expect(container.querySelector('[role="alert"]')?.textContent).toContain("Project is archived"));
|
||||
expect(container.textContent).not.toContain("Sending when reconnected…");
|
||||
expect(container.querySelector<HTMLInputElement>('input[aria-label="Task title"]')?.disabled).toBe(false);
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("never creates a restored task without the files it was submitted with", async () => {
|
||||
dialogState.newIssueDefaults = { title: "Has files" };
|
||||
localStorage.setItem("paperclip:issue-draft:pending-create:user-1", JSON.stringify({
|
||||
version: 1,
|
||||
key: "paperclip:issue-draft:pending-create:user-1",
|
||||
idempotencyKey: "create-key-123",
|
||||
createdAt: Date.now(),
|
||||
payload: {
|
||||
fingerprint: "{}",
|
||||
data: { companyId: "company-1", title: "Has files" },
|
||||
stagedFileNames: ["spec.pdf"],
|
||||
},
|
||||
}));
|
||||
const { root } = renderDialog(container);
|
||||
await flush();
|
||||
|
||||
await waitForAssertion(() => expect(container.querySelector('[role="alert"]')?.textContent).toContain("spec.pdf"));
|
||||
expect(container.querySelector('[role="alert"]')?.textContent).toContain("Attach it again");
|
||||
await act(async () => { container.querySelector<HTMLButtonElement>('[aria-label="Create task"]')!.click(); });
|
||||
await flush();
|
||||
expect(mockIssuesApi.create).not.toHaveBeenCalled();
|
||||
expect(localStorage.getItem("paperclip:issue-draft:pending-create:user-1")).toBeNull();
|
||||
// The original key outlives the rejection, so it survives another reload.
|
||||
expect(localStorage.getItem("paperclip:issue-draft:create-awaiting-files:user-1")).toContain("create-key-123");
|
||||
act(() => root.unmount());
|
||||
|
||||
const reloaded = renderDialog(container);
|
||||
await flush();
|
||||
expect(container.querySelector('[role="alert"]')?.textContent).toContain("spec.pdf");
|
||||
expect(localStorage.getItem("paperclip:issue-draft:create-awaiting-files:user-1")).toContain("create-key-123");
|
||||
expect(mockIssuesApi.create).not.toHaveBeenCalled();
|
||||
act(() => reloaded.root.unmount());
|
||||
});
|
||||
|
||||
it.each([false, true])("keeps restored create payload immutable when files are reattached (changed title: %s)", async changed => {
|
||||
mockIssuesApi.create.mockResolvedValue({ id: "issue-1", identifier: "PAP-1", companyId: "company-1" });
|
||||
mockIssuesApi.uploadAttachment.mockResolvedValue({});
|
||||
dialogState.newIssueDefaults = { title: "Has files" };
|
||||
const spec = new File(["a"], "spec.pdf", { lastModified: 1 });
|
||||
const notes = new File(["bb"], "notes.pdf", { lastModified: 2 });
|
||||
localStorage.setItem("paperclip:issue-draft:pending-create:user-1", JSON.stringify({
|
||||
version: 1,
|
||||
key: "paperclip:issue-draft:pending-create:user-1",
|
||||
idempotencyKey: "create-key-123",
|
||||
createdAt: Date.now(),
|
||||
payload: {
|
||||
fingerprint: JSON.stringify({ stagedFiles: ["attachment::spec.pdf:1:1", "attachment::notes.pdf:2:2"] }),
|
||||
data: { companyId: "company-1", title: "Has files" },
|
||||
stagedFileNames: ["spec.pdf", "notes.pdf"],
|
||||
},
|
||||
}));
|
||||
const { root } = renderDialog(container);
|
||||
await flush();
|
||||
await waitForAssertion(() => expect(container.querySelector('[role="alert"]')?.textContent).toContain("spec.pdf"));
|
||||
|
||||
const input = container.querySelector<HTMLInputElement>('input[type="file"]')!;
|
||||
Object.defineProperty(input, "files", { configurable: true, value: [notes, spec] });
|
||||
await act(async () => {
|
||||
input.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
});
|
||||
await flush();
|
||||
if (changed) await typeTextareaValue(container.querySelector<HTMLInputElement>('input[aria-label="Task title"]')!, "Changed after restore");
|
||||
const send = container.querySelector<HTMLButtonElement>('[aria-label="Create task"]')!;
|
||||
await act(async () => { send.click(); });
|
||||
await flush();
|
||||
if (changed) {
|
||||
expect(mockIssuesApi.create).not.toHaveBeenCalled();
|
||||
expect(container.textContent).toContain("original fields");
|
||||
} else {
|
||||
await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledTimes(1));
|
||||
expect(mockIssuesApi.create.mock.calls[0][1].idempotencyKey).toBe("create-key-123");
|
||||
expect(mockIssuesApi.create.mock.calls[0][1].title).toBe("Has files");
|
||||
}
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("drops an account's restored create and staged files when the account changes", async () => {
|
||||
dialogState.newIssueDefaults = { title: "Account A saved task" };
|
||||
const file = new File(["a"], "spec.pdf", { lastModified: 1 });
|
||||
const original = JSON.stringify({ version: 1, key: "paperclip:issue-draft:create-awaiting-files:user-1", idempotencyKey: "account-a-create-key", createdAt: Date.now(), payload: { fingerprint: JSON.stringify({ stagedFiles: ["attachment::spec.pdf:1:1"] }), data: { companyId: "company-1", title: "Account A saved task" }, stagedFileNames: ["spec.pdf"] } });
|
||||
localStorage.setItem("paperclip:issue-draft:create-awaiting-files:user-1", original);
|
||||
const { root, queryClient } = renderDialog(container);
|
||||
try {
|
||||
await waitForAssertion(() => expect(container.textContent).toContain("spec.pdf"));
|
||||
const input = container.querySelector<HTMLInputElement>('input[type="file"]')!;
|
||||
Object.defineProperty(input, "files", { configurable: true, value: [file] });
|
||||
await act(async () => { input.dispatchEvent(new Event("change", { bubbles: true })); }); await flush();
|
||||
mockAuthApi.getSession.mockResolvedValue({ user: { id: "user-2" } });
|
||||
queryClient.setQueryData(queryKeys.auth.session, { user: { id: "user-2" } });
|
||||
await waitForAssertion(() => expect(container.querySelector<HTMLInputElement>('input[aria-label="Task title"]')?.value ?? "").toBe(""));
|
||||
expect(container.textContent).not.toContain("spec.pdf");
|
||||
expect(localStorage.getItem("paperclip:issue-draft:create-awaiting-files:user-1")).toBe(original);
|
||||
await typeTextareaValue(container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Describe a task…"]')!, "Account B fresh task");
|
||||
mockIssuesApi.create.mockResolvedValue({ id: "task-b", identifier: "PAP-2", companyId: "company-1" });
|
||||
await act(async () => container.querySelector<HTMLButtonElement>('[aria-label="Create task"]')!.click());
|
||||
await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledTimes(1));
|
||||
expect(mockIssuesApi.create.mock.calls[0][1].description).toBe("Account B fresh task");
|
||||
expect(mockIssuesApi.create.mock.calls[0][1].idempotencyKey).not.toBe("account-a-create-key");
|
||||
expect(mockIssuesApi.uploadAttachment).not.toHaveBeenCalled();
|
||||
} finally { act(() => root.unmount()); queryClient.clear(); }
|
||||
});
|
||||
|
||||
it.each([false, true])("retains a restored task backup after the debounce (session known=%s)", async (sessionKnown) => {
|
||||
if (!sessionKnown) mockAuthApi.getSession.mockReturnValue(new Promise(() => {}));
|
||||
localStorage.setItem("paperclip:issue-draft:user-1", JSON.stringify({
|
||||
title: "", description: "Keep this restored backup", status: "todo", priority: "",
|
||||
assigneeValue: "", reviewerValue: "", approverValue: "", watchdogAgentId: "", watchdogInstructions: "",
|
||||
projectId: "", projectWorkspaceId: "", assigneeModelLane: "primary", assigneeModelOverride: "",
|
||||
assigneeThinkingEffort: "", assigneeChrome: false, executionWorkspaceMode: "shared_workspace",
|
||||
selectedExecutionWorkspaceId: "", workMode: "standard", isPrivate: false, composerSettings: null,
|
||||
}));
|
||||
const { root, queryClient } = renderDialog(container);
|
||||
try {
|
||||
await flush();
|
||||
if (!sessionKnown) queryClient.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||||
await waitForAssertion(() => expect(container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Describe a task…"]')?.value).toBe("Keep this restored backup"));
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 850)); });
|
||||
expect(JSON.parse(localStorage.getItem("paperclip:issue-draft:user-1") ?? "null")?.description).toBe("Keep this restored backup");
|
||||
dialogState.newIssueOpen = false;
|
||||
act(() => root.render(<QueryClientProvider client={queryClient}><NewIssueDialog /></QueryClientProvider>));
|
||||
await flush();
|
||||
dialogState.newIssueOpen = true;
|
||||
act(() => root.render(<QueryClientProvider client={queryClient}><NewIssueDialog /></QueryClientProvider>));
|
||||
await flush();
|
||||
expect(container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Describe a task…"]')?.value).toBe("Keep this restored backup");
|
||||
} finally { act(() => root.unmount()); queryClient.clear(); }
|
||||
});
|
||||
|
||||
it.each([false, true])("keeps erased task text erased after reopening (session known=%s)", async (sessionKnown) => {
|
||||
if (!sessionKnown) mockAuthApi.getSession.mockReturnValue(new Promise(() => {}));
|
||||
localStorage.setItem("paperclip:issue-draft:user-1", JSON.stringify({ title: "", description: "Older saved text" }));
|
||||
const { root, queryClient } = renderDialog(container);
|
||||
try {
|
||||
await flush();
|
||||
const editor = container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Describe a task…"]')!;
|
||||
await typeTextareaValue(editor, "Erase this task text");
|
||||
await typeTextareaValue(editor, "");
|
||||
if (!sessionKnown) queryClient.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 850)); });
|
||||
await waitForAssertion(() => expect(localStorage.getItem("paperclip:issue-draft:user-1")).toBeNull());
|
||||
dialogState.newIssueOpen = false;
|
||||
act(() => root.render(<QueryClientProvider client={queryClient}><NewIssueDialog /></QueryClientProvider>));
|
||||
await flush();
|
||||
dialogState.newIssueOpen = true;
|
||||
act(() => root.render(<QueryClientProvider client={queryClient}><NewIssueDialog /></QueryClientProvider>));
|
||||
await flush();
|
||||
expect(container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Describe a task…"]')?.value).toBe("");
|
||||
expect(container.textContent).not.toContain("Erase this task text");
|
||||
} finally { act(() => root.unmount()); queryClient.clear(); }
|
||||
});
|
||||
|
||||
it.each([false, true])("keeps task typing through the first session lookup (storage unavailable=%s)", async (unavailable) => {
|
||||
mockAuthApi.getSession.mockReturnValue(new Promise(() => {}));
|
||||
const { root, queryClient } = renderDialog(container);
|
||||
let storage: ReturnType<typeof vi.spyOn> | undefined;
|
||||
try {
|
||||
await flush();
|
||||
await typeTextareaValue(container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Describe a task…"]')!, "Typed before account lookup");
|
||||
if (unavailable) storage = vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { throw new Error("Storage unavailable"); });
|
||||
queryClient.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||||
await flush(); await flush();
|
||||
expect(container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Describe a task…"]')?.value).toBe("Typed before account lookup");
|
||||
if (!unavailable) expect(localStorage.getItem("paperclip:issue-draft:user-1")).toContain("Typed before account lookup");
|
||||
expect(mockIssuesApi.create).not.toHaveBeenCalled();
|
||||
} finally { storage?.mockRestore(); act(() => root.unmount()); queryClient.clear(); }
|
||||
});
|
||||
|
||||
it.each(["create", "upload"] as const)("stops old staged work after an account change during %s", async (during) => {
|
||||
dialogState.newIssueDefaults = { title: "Account A in-flight task" };
|
||||
let finish!: (value: unknown) => void;
|
||||
const waiting = new Promise(resolve => { finish = resolve; });
|
||||
const created = { id: "task-a", identifier: "PAP-1", companyId: "company-1" };
|
||||
mockIssuesApi.create.mockImplementation(() => during === "create" ? waiting : Promise.resolve(created));
|
||||
mockIssuesApi.uploadAttachment.mockImplementation(() => during === "upload" ? waiting : Promise.resolve({}));
|
||||
const { root, queryClient } = renderDialog(container);
|
||||
try {
|
||||
await flush(); await flush();
|
||||
const input = container.querySelector<HTMLInputElement>('input[type="file"]')!;
|
||||
Object.defineProperty(input, "files", { configurable: true, value: [new File(["a"], "first.pdf"), new File(["b"], "second.pdf")] });
|
||||
await act(async () => { input.dispatchEvent(new Event("change", { bubbles: true })); }); await flush();
|
||||
await act(async () => { container.querySelector<HTMLButtonElement>('[aria-label="Create task"]')!.click(); });
|
||||
await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledTimes(1));
|
||||
if (during === "upload") await waitForAssertion(() => expect(mockIssuesApi.uploadAttachment).toHaveBeenCalledTimes(1));
|
||||
const key = mockIssuesApi.create.mock.calls[0][1].idempotencyKey;
|
||||
mockAuthApi.getSession.mockResolvedValue({ user: { id: "user-2" } });
|
||||
queryClient.setQueryData(queryKeys.auth.session, { user: { id: "user-2" } });
|
||||
await flush(); await flush();
|
||||
finish(during === "create" ? created : {});
|
||||
await waitForAssertion(() => {
|
||||
const mutation = queryClient.getMutationCache().getAll().find(item => (item.state.variables as { idempotencyKey?: string } | undefined)?.idempotencyKey === key);
|
||||
expect(mutation?.state.status).toMatch(/^(success|error)$/);
|
||||
});
|
||||
expect(mockIssuesApi.uploadAttachment).toHaveBeenCalledTimes(during === "create" ? 0 : 1);
|
||||
expect(dialogState.closeNewIssue).not.toHaveBeenCalled();
|
||||
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(); }
|
||||
});
|
||||
|
||||
it("restores original document keys when colliding document names are reattached in reverse", async () => {
|
||||
dialogState.newIssueDefaults = { title: "Has documents" };
|
||||
mockIssuesApi.create.mockResolvedValue({ id: "issue-1", identifier: "PAP-1", companyId: "company-1" });
|
||||
mockIssuesApi.upsertDocument.mockResolvedValue({});
|
||||
const markdown = new File(["a"], "notes.md", { type: "text/markdown", lastModified: 1 });
|
||||
const text = new File(["bb"], "notes.txt", { type: "text/plain", lastModified: 2 });
|
||||
localStorage.setItem("paperclip:issue-draft:create-awaiting-files:user-1", JSON.stringify({ version: 1, key: "paperclip:issue-draft:create-awaiting-files:user-1", idempotencyKey: "original-doc-create-key", createdAt: Date.now(), payload: { fingerprint: JSON.stringify({ stagedFiles: ["document:notes:notes.md:1:1", "document:notes-2:notes.txt:2:2"] }), data: { companyId: "company-1", title: "Has documents" }, stagedFileNames: ["notes.md", "notes.txt"] } }));
|
||||
const { root } = renderDialog(container);
|
||||
try {
|
||||
await waitForAssertion(() => expect(container.textContent).toContain("notes.md"));
|
||||
const input = container.querySelector<HTMLInputElement>('input[type="file"]')!;
|
||||
Object.defineProperty(input, "files", { configurable: true, value: [text, markdown] });
|
||||
await act(async () => { input.dispatchEvent(new Event("change", { bubbles: true })); }); await flush();
|
||||
await act(async () => container.querySelector<HTMLButtonElement>('[aria-label="Create task"]')!.click());
|
||||
await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledTimes(1));
|
||||
expect(mockIssuesApi.create.mock.calls[0][1].idempotencyKey).toBe("original-doc-create-key");
|
||||
await waitForAssertion(() => expect(mockIssuesApi.upsertDocument).toHaveBeenCalledTimes(2));
|
||||
expect(mockIssuesApi.upsertDocument).toHaveBeenCalledWith("issue-1", "notes", expect.objectContaining({ body: "a" }));
|
||||
expect(mockIssuesApi.upsertDocument).toHaveBeenCalledWith("issue-1", "notes-2", expect.objectContaining({ body: "bb" }));
|
||||
} finally { act(() => root.unmount()); }
|
||||
});
|
||||
|
||||
it("restores a saved subtask's parent and goal when opened from the normal New Task action", async () => {
|
||||
dialogState.newIssueDefaults = {};
|
||||
mockIssuesApi.create.mockResolvedValue({ id: "issue-1", identifier: "PAP-1", companyId: "company-1" });
|
||||
mockIssuesApi.uploadAttachment.mockResolvedValue({});
|
||||
mockIssuesApi.get.mockResolvedValue({ id: "parent-1", identifier: "PAP-2", title: "Parent", isPrivate: false });
|
||||
localStorage.setItem("paperclip:issue-draft:user-1", JSON.stringify({ title: "Saved subtask", description: "", status: "todo", priority: "", projectId: "", assigneeValue: "" }));
|
||||
localStorage.setItem("paperclip:issue-draft:create-awaiting-files:user-1", JSON.stringify({
|
||||
version: 1, key: "paperclip:issue-draft:create-awaiting-files:user-1", idempotencyKey: "subtask-key-123", createdAt: Date.now(),
|
||||
payload: { fingerprint: JSON.stringify({ stagedFiles: ["attachment::spec.pdf:1:1"] }),
|
||||
data: { companyId: "company-1", title: "Saved subtask", parentId: "parent-1", goalId: "goal-1" }, stagedFileNames: ["spec.pdf"] },
|
||||
}));
|
||||
const { root } = renderDialog(container);
|
||||
await flush();
|
||||
const input = container.querySelector<HTMLInputElement>('input[type="file"]')!;
|
||||
Object.defineProperty(input, "files", { configurable: true, value: [new File(["a"], "spec.pdf", { lastModified: 1 })] });
|
||||
await act(async () => { input.dispatchEvent(new Event("change", { bubbles: true })); });
|
||||
await flush();
|
||||
await act(async () => { container.querySelector<HTMLButtonElement>('[aria-label="Create sub-task"]')!.click(); });
|
||||
await flush();
|
||||
expect(mockIssuesApi.create).toHaveBeenCalledTimes(1);
|
||||
expect(mockIssuesApi.create.mock.calls[0]?.[1]).toMatchObject({ idempotencyKey: "subtask-key-123", title: "Saved subtask", parentId: "parent-1", goalId: "goal-1" });
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("submits Chinese, Japanese, and Hindi issue text without normalization", async () => {
|
||||
const title = "验证中文任务";
|
||||
const description = [
|
||||
@@ -2035,7 +2330,7 @@ describe("NewIssueDialog", () => {
|
||||
enableIsolatedWorkspaces: false,
|
||||
});
|
||||
localStorage.setItem(
|
||||
"paperclip:issue-draft",
|
||||
"paperclip:issue-draft:user-1",
|
||||
JSON.stringify({
|
||||
title: "Watched task",
|
||||
description: "",
|
||||
@@ -2099,7 +2394,7 @@ describe("NewIssueDialog", () => {
|
||||
|
||||
it("restores shared model, effort, and fast settings into the created task", async () => {
|
||||
mockAgentsApi.list.mockResolvedValue([{ id: "agent-1", name: "Coder", status: "active", adapterType: "codex_local", adapterConfig: {}, runtimeConfig: {}, permissions: {} }]);
|
||||
localStorage.setItem("paperclip:issue-draft", JSON.stringify({
|
||||
localStorage.setItem("paperclip:issue-draft:user-1", JSON.stringify({
|
||||
title: "", description: "Use the saved run settings", status: "todo", priority: "medium",
|
||||
assigneeValue: "agent:agent-1", projectId: "", workMode: "planning",
|
||||
composerSettings: { model: "gpt-6-astra", effort: "ultra", fast: true },
|
||||
@@ -2135,3 +2430,70 @@ describe("NewIssueDialog", () => {
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe("addStagedFilesToIssue", () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("crypto", webcrypto);
|
||||
localStorage.clear();
|
||||
mockIssuesApi.uploadAttachment.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it("keeps a confirmed upload receipt when ownership changes before the next file", async () => {
|
||||
const files = ["one", "two"].map((name, index) => ({ id: name, kind: "attachment" as const, file: new File([name], `${name}.pdf`, { lastModified: index + 1 }) }));
|
||||
let owned = true;
|
||||
const assertCurrentOwner = () => { if (!owned) throw new Error("Account changed"); };
|
||||
mockIssuesApi.uploadAttachment.mockResolvedValue({}).mockImplementationOnce(async () => { owned = false; return {}; });
|
||||
const input = { companyId: "company-1", issueId: "task-1", stagedFiles: files, idempotencyKey: "original-upload-request", assertCurrentOwner };
|
||||
await expect(addStagedFilesToIssue(input)).rejects.toThrow("Account changed");
|
||||
expect(mockIssuesApi.uploadAttachment).toHaveBeenCalledTimes(1);
|
||||
owned = true;
|
||||
await expect(addStagedFilesToIssue(input)).resolves.toEqual([]);
|
||||
expect(mockIssuesApi.uploadAttachment.mock.calls.map(call => call[2].name)).toEqual(["one.pdf", "two.pdf"]);
|
||||
});
|
||||
|
||||
it("uploads distinct files with the same metadata instead of treating one as a receipt", async () => {
|
||||
const stagedFiles = ["a", "b"].map((body, index) => ({
|
||||
id: `staged-${index}`,
|
||||
kind: "attachment" as const,
|
||||
file: new File([body], "report.txt", { lastModified: 123 }),
|
||||
}));
|
||||
mockIssuesApi.uploadAttachment.mockResolvedValue({});
|
||||
expect(await addStagedFilesToIssue({ companyId: "company-1", issueId: "issue-1", idempotencyKey: "metadata-collision", stagedFiles })).toEqual([]);
|
||||
expect(mockIssuesApi.uploadAttachment).toHaveBeenCalledTimes(2);
|
||||
expect(mockIssuesApi.uploadAttachment.mock.calls[0]?.[2]).toBe(stagedFiles[0]!.file);
|
||||
expect(mockIssuesApi.uploadAttachment.mock.calls[1]?.[2]).toBe(stagedFiles[1]!.file);
|
||||
});
|
||||
|
||||
it("still uploads files when browser hashing is unavailable", async () => {
|
||||
vi.stubGlobal("crypto", {});
|
||||
const stagedFiles = ["a", "b"].map((body, index) => ({
|
||||
id: `staged-${index}`, kind: "attachment" as const,
|
||||
file: new File([body], "report.txt", { lastModified: 123 }),
|
||||
}));
|
||||
mockIssuesApi.uploadAttachment.mockResolvedValue({});
|
||||
expect(await addStagedFilesToIssue({ companyId: "company-1", issueId: "issue-1", idempotencyKey: "hashing-unavailable", stagedFiles })).toEqual([]);
|
||||
expect(mockIssuesApi.uploadAttachment).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("never adds a file twice when a create replays after a reload mid-upload", async () => {
|
||||
const spec = { id: "staged-1", kind: "attachment" as const, file: new File(["a"], "spec.pdf", { lastModified: 1 }) };
|
||||
const notes = { id: "staged-2", kind: "attachment" as const, file: new File(["bb"], "notes.txt", { lastModified: 2 }) };
|
||||
mockIssuesApi.uploadAttachment.mockResolvedValueOnce({}).mockRejectedValueOnce(new Error("Upload interrupted"));
|
||||
const target = { companyId: "company-1", issueId: "issue-1", idempotencyKey: "create-key-123" };
|
||||
expect(await addStagedFilesToIssue({ ...target, stagedFiles: [spec, notes] })).toEqual(["notes.txt"]);
|
||||
|
||||
// Reattached after a reload: new staging ids, the same files, the same key.
|
||||
mockIssuesApi.uploadAttachment.mockResolvedValue({});
|
||||
expect(await addStagedFilesToIssue({
|
||||
...target,
|
||||
stagedFiles: [{ ...spec, id: "staged-3" }, { ...notes, id: "staged-4" }],
|
||||
})).toEqual([]);
|
||||
expect(mockIssuesApi.uploadAttachment.mock.calls.map((call) => (call[2] as File).name)).toEqual([
|
||||
"spec.pdf",
|
||||
"notes.txt",
|
||||
"notes.txt",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -43,10 +43,74 @@ import { TaskChatPresentationProvider } from "./task-chat/presentation-mode";
|
||||
import { mergeComposerRunSettings, type ComposerRunSettings } from "./task-chat/composer-run-settings";
|
||||
import { useSidebar } from "../context/SidebarContext";
|
||||
import { InlineBanner } from "./InlineBanner";
|
||||
import { PendingSendNotice } from "./PendingSendNotice";
|
||||
import { useDurableSubmit } from "../hooks/useDurableSubmit";
|
||||
import { describeError, type ErrorDescription } from "../api/errors";
|
||||
import { clearPendingSend, pendingSendKeyFor, readPendingSend, writePendingSend, PendingSendAccountChangedError } from "../lib/pending-send";
|
||||
import { useDraftOwner, useDraftOwnerReader } from "../hooks/useDraftOwner";
|
||||
import { InlineEntitySelector, type InlineEntityOption } from "./InlineEntitySelector";
|
||||
import { getTrustPreset } from "../lib/trust-policy-ui";
|
||||
|
||||
const DRAFT_KEY = "paperclip:issue-draft";
|
||||
/** A create that is waiting to resend: its request body and idempotency key. */
|
||||
const PENDING_CREATE_KEY = "paperclip:issue-draft:pending-create";
|
||||
|
||||
/**
|
||||
* The create request. Staged files cannot be stored, so they ride in memory and
|
||||
* only their names are saved: a create restored after reload knows it needs them.
|
||||
*/
|
||||
type PendingCreate = { fingerprint: string; data: Record<string, unknown>; stagedFileNames?: string[] };
|
||||
|
||||
function isPendingCreate(value: unknown): value is PendingCreate {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
||||
const row = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof row.fingerprint === "string" &&
|
||||
!!row.data && typeof row.data === "object" && !Array.isArray(row.data) &&
|
||||
typeof (row.data as Record<string, unknown>).companyId === "string" &&
|
||||
(row.stagedFileNames === undefined ||
|
||||
(Array.isArray(row.stagedFileNames) && row.stagedFileNames.every((name) => typeof name === "string")))
|
||||
);
|
||||
}
|
||||
|
||||
/** Thrown before sending a restored create whose staged files are gone from memory. */
|
||||
class StagedFilesMissingError extends Error {
|
||||
constructor(names: string[]) {
|
||||
super(
|
||||
`This page no longer has ${names.length === 1 ? "the file" : `the ${names.length} files`} staged for this task (${names.join(", ")}). Attach ${names.length === 1 ? "it" : "them"} again, then create the task.`,
|
||||
);
|
||||
this.name = "StagedFilesMissingError";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A restored create that could not be sent for lack of its files. Its key is
|
||||
* kept until a create succeeds or the user cancels, so reattaching after any
|
||||
* number of reloads replays a create that already reached the server.
|
||||
*/
|
||||
const CREATE_AWAITING_FILES_KEY = "paperclip:issue-draft:create-awaiting-files";
|
||||
|
||||
function stagedFilesMissingDescription(names: string[]): ErrorDescription {
|
||||
return describeError(new StagedFilesMissingError(names), { action: "create the task" });
|
||||
}
|
||||
|
||||
/** Identifies a staged file across reselection from disk, unlike its per-staging `id`. */
|
||||
function stagedFileIdentity(file: StagedIssueFile): string {
|
||||
return [file.kind, file.documentKey ?? "", file.file.name, file.file.size, file.file.lastModified].join(":");
|
||||
}
|
||||
function restoreStagedDocumentKeys(files: StagedIssueFile[], fingerprint: string | undefined): StagedIssueFile[] {
|
||||
let required: unknown;
|
||||
try { required = JSON.parse(fingerprint ?? "{}").stagedFiles; } catch { return files; }
|
||||
if (!Array.isArray(required)) return files;
|
||||
return files.map(file => {
|
||||
if (file.kind !== "document") return file;
|
||||
const suffix = `:${file.file.name}:${file.file.size}:${file.file.lastModified}`;
|
||||
const matches = required.filter((identity): identity is string => typeof identity === "string" && identity.startsWith("document:") && identity.endsWith(suffix));
|
||||
if (matches.length !== 1) return file;
|
||||
return { ...file, documentKey: matches[0].slice("document:".length, -suffix.length) };
|
||||
});
|
||||
}
|
||||
|
||||
const DEBOUNCE_MS = 800;
|
||||
|
||||
type VisualViewportLayout = {
|
||||
@@ -146,12 +210,103 @@ type StagedIssueFile = {
|
||||
title?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Files a keyed create has already added to its task. A replayed create (same
|
||||
* key, after a reload mid-upload) gets the existing task back from the
|
||||
* server, and must not add those files a second time.
|
||||
*/
|
||||
const CREATE_UPLOAD_RECEIPTS_PREFIX = "paperclip:issue-draft:create-uploads:";
|
||||
|
||||
function loadCreateUploadReceipts(idempotencyKey: string): Set<string> {
|
||||
try {
|
||||
const stored = JSON.parse(localStorage.getItem(CREATE_UPLOAD_RECEIPTS_PREFIX + idempotencyKey) ?? "[]");
|
||||
return new Set(Array.isArray(stored) ? stored.filter((item): item is string => typeof item === "string") : []);
|
||||
} catch {
|
||||
return new Set();
|
||||
}
|
||||
}
|
||||
|
||||
function saveCreateUploadReceipts(idempotencyKey: string, receipts: Set<string>) {
|
||||
try {
|
||||
localStorage.setItem(CREATE_UPLOAD_RECEIPTS_PREFIX + idempotencyKey, JSON.stringify([...receipts]));
|
||||
} catch {
|
||||
// Without storage a replay after reload may add a file twice; nothing is lost.
|
||||
}
|
||||
}
|
||||
|
||||
export function clearCreateUploadReceipts(idempotencyKey: string) {
|
||||
try {
|
||||
localStorage.removeItem(CREATE_UPLOAD_RECEIPTS_PREFIX + idempotencyKey);
|
||||
} catch {
|
||||
// Unavailable storage holds nothing to clear.
|
||||
}
|
||||
}
|
||||
|
||||
/** Add staged files to a created task, skipping any this create already added. Returns the names that failed. */
|
||||
export async function addStagedFilesToIssue(input: {
|
||||
companyId: string;
|
||||
issueId: string;
|
||||
stagedFiles: StagedIssueFile[];
|
||||
idempotencyKey?: string;
|
||||
assertCurrentOwner?: () => void;
|
||||
}): Promise<string[]> {
|
||||
const { companyId, issueId, stagedFiles, idempotencyKey } = input;
|
||||
const receipts = idempotencyKey ? loadCreateUploadReceipts(idempotencyKey) : new Set<string>();
|
||||
const failures: string[] = [];
|
||||
for (const stagedFile of stagedFiles) {
|
||||
input.assertCurrentOwner?.();
|
||||
let identity: string | undefined;
|
||||
if (idempotencyKey && globalThis.crypto?.subtle) {
|
||||
try {
|
||||
const bytes = await new Promise<ArrayBuffer>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(reader.result as ArrayBuffer);
|
||||
reader.onerror = () => reject(reader.error);
|
||||
reader.onabort = () => reject(new Error("File read cancelled"));
|
||||
reader.readAsArrayBuffer(stagedFile.file);
|
||||
});
|
||||
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
||||
const hash = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, "0")).join("");
|
||||
identity = JSON.stringify([stagedFileIdentity(stagedFile), hash]);
|
||||
} catch {
|
||||
identity = undefined;
|
||||
}
|
||||
}
|
||||
input.assertCurrentOwner?.();
|
||||
if (identity && receipts.has(identity)) continue;
|
||||
try {
|
||||
if (stagedFile.kind === "document") {
|
||||
const body = await stagedFile.file.text();
|
||||
input.assertCurrentOwner?.();
|
||||
await issuesApi.upsertDocument(issueId, stagedFile.documentKey ?? "document", {
|
||||
title: stagedFile.documentKey === "plan" ? null : (stagedFile.title ?? null),
|
||||
format: "markdown",
|
||||
body,
|
||||
baseRevisionId: null,
|
||||
});
|
||||
} else {
|
||||
await issuesApi.uploadAttachment(companyId, issueId, stagedFile.file);
|
||||
}
|
||||
if (identity && idempotencyKey) {
|
||||
receipts.add(identity);
|
||||
saveCreateUploadReceipts(idempotencyKey, receipts);
|
||||
}
|
||||
input.assertCurrentOwner?.();
|
||||
} catch {
|
||||
input.assertCurrentOwner?.();
|
||||
failures.push(stagedFile.file.name);
|
||||
}
|
||||
}
|
||||
return failures;
|
||||
}
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { buildAssigneeAdapterOverrides, type IssueModelLane } from "../lib/issue-assignee-overrides";
|
||||
|
||||
function loadDraft(): IssueDraft | null {
|
||||
function loadDraft(owner: string | undefined): IssueDraft | null {
|
||||
if (owner === undefined) return null;
|
||||
try {
|
||||
const raw = localStorage.getItem(DRAFT_KEY);
|
||||
const raw = localStorage.getItem(pendingSendKeyFor(DRAFT_KEY, owner));
|
||||
if (!raw) return null;
|
||||
return JSON.parse(raw) as IssueDraft;
|
||||
} catch {
|
||||
@@ -159,12 +314,12 @@ function loadDraft(): IssueDraft | null {
|
||||
}
|
||||
}
|
||||
|
||||
function saveDraft(draft: IssueDraft) {
|
||||
localStorage.setItem(DRAFT_KEY, JSON.stringify(draft));
|
||||
function saveDraft(owner: string, draft: IssueDraft) {
|
||||
try { localStorage.setItem(pendingSendKeyFor(DRAFT_KEY, owner), JSON.stringify(draft)); } catch {}
|
||||
}
|
||||
|
||||
function clearDraft() {
|
||||
localStorage.removeItem(DRAFT_KEY);
|
||||
function clearDraft(owner: string | undefined) {
|
||||
try { if (owner !== undefined) localStorage.removeItem(pendingSendKeyFor(DRAFT_KEY, owner)); } catch {}
|
||||
}
|
||||
|
||||
function isTextDocumentFile(file: File) {
|
||||
@@ -277,8 +432,24 @@ function isWorkModeEscapeShortcut(e: Pick<KeyboardEvent, "key" | "metaKey">) {
|
||||
}
|
||||
|
||||
export function NewIssueDialog() {
|
||||
const owner = useDraftOwner();
|
||||
const { newIssueDefaults } = useDialog();
|
||||
const [scope, setScope] = useState({ owner, generation: 0, ignoredDefaults: null as typeof newIssueDefaults | null });
|
||||
const changed = scope.owner !== owner;
|
||||
const knownChange = changed && scope.owner !== undefined;
|
||||
const next = changed ? { owner, generation: scope.generation + (knownChange ? 1 : 0), ignoredDefaults: knownChange ? newIssueDefaults : scope.ignoredDefaults } : scope;
|
||||
if (changed) setScope(next);
|
||||
return <AccountNewIssueDialog key={next.generation} ignoreDefaults={next.ignoredDefaults === newIssueDefaults} />;
|
||||
}
|
||||
|
||||
function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) {
|
||||
const { visible: workspaceIsolationControlsVisible } = useWorkspaceIsolationControls();
|
||||
const { newIssueOpen, newIssueDefaults, closeNewIssue } = useDialog();
|
||||
const { newIssueOpen, newIssueDefaults: sharedDefaults, closeNewIssue } = useDialog();
|
||||
const newIssueDefaults = useMemo(() => ignoreDefaults ? {} as typeof sharedDefaults : sharedDefaults, [ignoreDefaults, sharedDefaults]);
|
||||
const readOwner = useDraftOwnerReader();
|
||||
const active = useRef(true);
|
||||
useEffect(() => { active.current = true; return () => { active.current = false; }; }, []);
|
||||
const unboundFormDraft = useRef<IssueDraft | null>(null);
|
||||
const visualViewportLayout = useVisualViewportLayout(newIssueOpen);
|
||||
const dialogBodyRef = useRef<HTMLDivElement>(null);
|
||||
const { companies, selectedCompanyId: effectiveCompanyId } = useCompany();
|
||||
@@ -317,12 +488,24 @@ export function NewIssueDialog() {
|
||||
const initializationKeyRef = useRef<string | null>(null);
|
||||
const defaultAssigneePendingRef = useRef(false);
|
||||
const defaultProjectPendingRef = useRef(false);
|
||||
const createRequestRef = useRef<{ fingerprint: string; idempotencyKey: string } | null>(null);
|
||||
// `recovering`: a create restored without its files keeps its key until it is
|
||||
// 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 [restoredLaunch, setRestoredLaunch] = useState<{ owner: string | undefined; parentId?: string; goalId?: string } | 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 } : {}),
|
||||
});
|
||||
const awaitingFilesKey = draftOwner !== undefined ? pendingSendKeyFor(CREATE_AWAITING_FILES_KEY, draftOwner) : null;
|
||||
|
||||
const primaryAgent = usePrimaryAgentPresentation(effectiveCompanyId);
|
||||
const isSubIssueMode = Boolean(newIssueDefaults.parentId);
|
||||
const isSubIssueMode = Boolean(parentId);
|
||||
const parentIssueLabel =
|
||||
newIssueDefaults.parentIdentifier ?? (newIssueDefaults.parentId ? newIssueDefaults.parentId.slice(0, 8) : "");
|
||||
(newIssueDefaults.parentId === parentId ? newIssueDefaults.parentIdentifier : undefined) ?? (parentId ? parentId.slice(0, 8) : "");
|
||||
const parentExecutionWorkspaceId = newIssueDefaults.executionWorkspaceId ?? "";
|
||||
const parentExecutionWorkspaceLabel = newIssueDefaults.parentExecutionWorkspaceLabel ?? parentExecutionWorkspaceId;
|
||||
|
||||
@@ -391,9 +574,9 @@ export function NewIssueDialog() {
|
||||
});
|
||||
|
||||
const { data: privacyParent, isError: parentPrivacyError, refetch: refetchParentPrivacy } = useQuery({
|
||||
queryKey: queryKeys.issues.detail(newIssueDefaults.parentId ?? ""),
|
||||
queryFn: () => issuesApi.get(newIssueDefaults.parentId!),
|
||||
enabled: newIssueOpen && Boolean(newIssueDefaults.parentId),
|
||||
queryKey: queryKeys.issues.detail(parentId ?? ""),
|
||||
queryFn: () => issuesApi.get(parentId!),
|
||||
enabled: newIssueOpen && Boolean(parentId),
|
||||
});
|
||||
const parentPrivacyUnresolved = isSubIssueMode && !privacyParent;
|
||||
const inheritsPrivateAccess = privacyParent?.visibility === "private" || privacyParent?.project?.visibility === "private";
|
||||
@@ -423,6 +606,9 @@ export function NewIssueDialog() {
|
||||
});
|
||||
}, [agents, companyMembers?.users, orderedProjects, mentionIssues]);
|
||||
|
||||
const assertCurrentOwner = () => {
|
||||
if (!active.current || draftOwner === undefined || readOwner() !== draftOwner) throw new PendingSendAccountChangedError();
|
||||
};
|
||||
const createIssue = useMutation({
|
||||
mutationFn: async ({
|
||||
companyId,
|
||||
@@ -430,30 +616,22 @@ export function NewIssueDialog() {
|
||||
navigateOnCreate,
|
||||
...data
|
||||
}: { companyId: string; stagedFiles: StagedIssueFile[]; navigateOnCreate?: boolean } & Record<string, unknown>) => {
|
||||
assertCurrentOwner();
|
||||
const issue = await issuesApi.create(companyId, data);
|
||||
const failures: string[] = [];
|
||||
|
||||
for (const stagedFile of pendingStagedFiles) {
|
||||
try {
|
||||
if (stagedFile.kind === "document") {
|
||||
const body = await stagedFile.file.text();
|
||||
await issuesApi.upsertDocument(issue.id, stagedFile.documentKey ?? "document", {
|
||||
title: stagedFile.documentKey === "plan" ? null : (stagedFile.title ?? null),
|
||||
format: "markdown",
|
||||
body,
|
||||
baseRevisionId: null,
|
||||
});
|
||||
} else {
|
||||
await issuesApi.uploadAttachment(companyId, issue.id, stagedFile.file);
|
||||
}
|
||||
} catch {
|
||||
failures.push(stagedFile.file.name);
|
||||
}
|
||||
}
|
||||
assertCurrentOwner();
|
||||
const failures = await addStagedFilesToIssue({
|
||||
companyId,
|
||||
issueId: issue.id,
|
||||
stagedFiles: pendingStagedFiles,
|
||||
assertCurrentOwner,
|
||||
idempotencyKey: typeof data.idempotencyKey === "string" ? data.idempotencyKey : undefined,
|
||||
});
|
||||
|
||||
assertCurrentOwner();
|
||||
return { issue, companyId, failures, navigateOnCreate };
|
||||
},
|
||||
onSuccess: ({ issue, companyId, failures, navigateOnCreate }) => {
|
||||
assertCurrentOwner();
|
||||
trackRecentProject(issue.projectId ?? "", companyId);
|
||||
if (issue.assigneeAgentId) trackRecentAssignee(issue.assigneeAgentId, companyId);
|
||||
if (issue.assigneeUserId) trackRecentAssigneeUser(issue.assigneeUserId, companyId);
|
||||
@@ -483,20 +661,94 @@ export function NewIssueDialog() {
|
||||
action: openIssueAction,
|
||||
});
|
||||
}
|
||||
clearDraft();
|
||||
clearDraft(draftOwner);
|
||||
reset();
|
||||
closeNewIssue();
|
||||
if (navigateOnCreate) 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<string, StagedIssueFile[]>());
|
||||
// The composer shows a rejection of the first attempt; later (automatic or
|
||||
// Resend now) rejections show here.
|
||||
const firstAttemptKey = useRef<string | null>(null);
|
||||
const [resendError, setResendError] = useState<ErrorDescription | null>(null);
|
||||
// Once the account is known, a create still waiting for its files keeps its
|
||||
// key and asks for the files again.
|
||||
useEffect(() => {
|
||||
if (!awaitingFilesKey) return;
|
||||
const awaiting = readPendingSend(awaitingFilesKey, isPendingCreate);
|
||||
if (!awaiting) return;
|
||||
createRequestRef.current ??= {
|
||||
fingerprint: awaiting.payload.fingerprint,
|
||||
idempotencyKey: awaiting.idempotencyKey,
|
||||
recovering: true,
|
||||
payload: awaiting.payload,
|
||||
};
|
||||
restoreLaunch(awaiting.payload);
|
||||
const names = awaiting.payload.stagedFileNames;
|
||||
if (names?.length) setResendError((current) => current ?? stagedFilesMissingDescription(names));
|
||||
}, [awaitingFilesKey]);
|
||||
const durableCreate = useDurableSubmit<PendingCreate, unknown>({
|
||||
sourceId: "new-issue-dialog",
|
||||
storageKey: PENDING_CREATE_KEY,
|
||||
isPayload: isPendingCreate,
|
||||
action: "create the task",
|
||||
send: async (payload, idempotencyKey) => {
|
||||
const stagedFiles = stagedFilesByKey.current.get(idempotencyKey);
|
||||
// Never create a restored task without the files it was submitted with.
|
||||
if (!stagedFiles && payload.stagedFileNames?.length) {
|
||||
throw new StagedFilesMissingError(payload.stagedFileNames);
|
||||
}
|
||||
const result = await createIssue.mutateAsync({
|
||||
...(payload.data as { companyId: string }),
|
||||
stagedFiles: stagedFiles ?? [],
|
||||
idempotencyKey,
|
||||
});
|
||||
stagedFilesByKey.current.delete(idempotencyKey);
|
||||
clearCreateUploadReceipts(idempotencyKey);
|
||||
return result;
|
||||
},
|
||||
onRejected: (error, description, pending) => {
|
||||
if (error instanceof StagedFilesMissingError) {
|
||||
// Reattaching the same files resubmits under the original key, so a
|
||||
// create that already reached the server is replayed, not duplicated.
|
||||
createRequestRef.current = {
|
||||
fingerprint: pending.payload.fingerprint,
|
||||
idempotencyKey: pending.idempotencyKey,
|
||||
recovering: true,
|
||||
payload: pending.payload,
|
||||
};
|
||||
restoreLaunch(pending.payload);
|
||||
if (awaitingFilesKey) writePendingSend(awaitingFilesKey, pending);
|
||||
}
|
||||
if (pending.idempotencyKey !== firstAttemptKey.current) 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 pendingCreate = durableCreate.pending;
|
||||
const { resendNow: resendCreateNow } = durableCreate;
|
||||
useEffect(() => {
|
||||
if (pendingCreate?.payload.stagedFileNames?.length && !stagedFilesByKey.current.has(pendingCreate.idempotencyKey)) {
|
||||
resendCreateNow();
|
||||
}
|
||||
}, [pendingCreate, resendCreateNow]);
|
||||
|
||||
// Debounced draft saving
|
||||
const scheduleSave = useCallback((draft: IssueDraft) => {
|
||||
if (draftOwner === undefined && (unboundFormDraft.current || draft.title.trim() || draft.description.trim())) unboundFormDraft.current = draft;
|
||||
if (draftTimer.current) clearTimeout(draftTimer.current);
|
||||
draftTimer.current = setTimeout(() => {
|
||||
if (draft.title.trim() || draft.description.trim()) saveDraft(draft);
|
||||
const owner = readOwner();
|
||||
if (owner !== undefined && (draftOwner === undefined || owner === draftOwner)) {
|
||||
if (draft.title.trim() || draft.description.trim()) saveDraft(owner, draft);
|
||||
else clearDraft(owner);
|
||||
}
|
||||
}, DEBOUNCE_MS);
|
||||
}, []);
|
||||
}, [draftOwner, readOwner]);
|
||||
|
||||
const setIssueText = useCallback((nextTitle: string, nextDescription: string) => {
|
||||
setHasTitle(Boolean(nextTitle));
|
||||
@@ -600,13 +852,23 @@ export function NewIssueDialog() {
|
||||
defaultProjectPendingRef.current = false;
|
||||
return;
|
||||
}
|
||||
const initializationKey = `${effectiveCompanyId ?? ""}:${JSON.stringify(newIssueDefaults)}`;
|
||||
const initializationKey = `${draftOwner ?? "unknown"}:${effectiveCompanyId ?? ""}:${JSON.stringify(newIssueDefaults)}`;
|
||||
if (initializationKeyRef.current === initializationKey) return;
|
||||
initializationKeyRef.current = initializationKey;
|
||||
if (draftTimer.current) {
|
||||
clearTimeout(draftTimer.current);
|
||||
draftTimer.current = null;
|
||||
}
|
||||
|
||||
executionWorkspaceDefaultProjectId.current = null;
|
||||
|
||||
const draft = loadDraft();
|
||||
if (draftOwner !== undefined && unboundFormDraft.current) {
|
||||
if (unboundFormDraft.current.title.trim() || unboundFormDraft.current.description.trim()) saveDraft(draftOwner, unboundFormDraft.current);
|
||||
else clearDraft(draftOwner);
|
||||
unboundFormDraft.current = null;
|
||||
return;
|
||||
}
|
||||
const draft = loadDraft(draftOwner);
|
||||
defaultProjectPendingRef.current = newIssueDefaults.projectId === undefined && !newIssueDefaults.parentId;
|
||||
defaultAssigneePendingRef.current = !newIssueDefaults.assigneeAgentId && !newIssueDefaults.assigneeUserId;
|
||||
setComposerSettings(null);
|
||||
@@ -745,7 +1007,7 @@ export function NewIssueDialog() {
|
||||
? defaultProjectId || null
|
||||
: null;
|
||||
}
|
||||
}, [newIssueOpen, newIssueDefaults, orderedProjects, effectiveCompanyId, setIssueText]);
|
||||
}, [newIssueOpen, newIssueDefaults, orderedProjects, effectiveCompanyId, setIssueText, draftOwner]);
|
||||
|
||||
// Cleanup timer on unmount
|
||||
useEffect(() => {
|
||||
@@ -755,7 +1017,9 @@ export function NewIssueDialog() {
|
||||
}, []);
|
||||
|
||||
function reset() {
|
||||
createRequestRef.current = null;
|
||||
unboundFormDraft.current = null;
|
||||
createRequestRef.current = null; setRestoredLaunch(null);
|
||||
if (awaitingFilesKey) clearPendingSend(awaitingFilesKey);
|
||||
setIssueText("", "");
|
||||
setStatus("todo");
|
||||
setPriority("");
|
||||
@@ -789,7 +1053,7 @@ export function NewIssueDialog() {
|
||||
async function handleSubmit(body: string, mode: IssueWorkMode, settings: ComposerRunSettings | null) {
|
||||
const currentTitle = titleRef.current.trim();
|
||||
const currentDescription = body.trim();
|
||||
if (!effectiveCompanyId || (!currentTitle && !currentDescription) || createIssue.isPending || worktreeSelectionIncomplete || parentPrivacyUnresolved) return;
|
||||
if (!effectiveCompanyId || (!currentTitle && !currentDescription) || createIssue.isPending || durableCreate.pending || worktreeSelectionIncomplete || parentPrivacyUnresolved) return;
|
||||
const inheritedOverrides = buildAssigneeAdapterOverrides({
|
||||
adapterType: assigneeAdapterType,
|
||||
lane: assigneeChrome ? "custom" : assigneeModelLane,
|
||||
@@ -833,7 +1097,6 @@ export function NewIssueDialog() {
|
||||
: inheritedOverrides;
|
||||
const createData = {
|
||||
companyId: effectiveCompanyId,
|
||||
stagedFiles,
|
||||
...(currentTitle ? { title: currentTitle } : {}),
|
||||
description: currentDescription || undefined,
|
||||
status,
|
||||
@@ -842,8 +1105,8 @@ export function NewIssueDialog() {
|
||||
...(effectivePrivate ? { visibility: "private" } : {}),
|
||||
...(selectedAssigneeAgentId ? { assigneeAgentId: selectedAssigneeAgentId } : {}),
|
||||
...(selectedAssigneeUserId ? { assigneeUserId: selectedAssigneeUserId } : {}),
|
||||
...(newIssueDefaults.parentId ? { parentId: newIssueDefaults.parentId } : {}),
|
||||
...(newIssueDefaults.goalId ? { goalId: newIssueDefaults.goalId } : {}),
|
||||
...(parentId ? { parentId } : {}),
|
||||
...(goalId ? { goalId } : {}),
|
||||
...(projectId ? { projectId } : {}),
|
||||
...(requestedProjectWorkspaceId ? { projectWorkspaceId: requestedProjectWorkspaceId } : {}),
|
||||
...(assigneeAdapterOverrides ? { assigneeAdapterOverrides } : {}),
|
||||
@@ -863,17 +1126,59 @@ export function NewIssueDialog() {
|
||||
: {}),
|
||||
};
|
||||
// An explicit board create is a new task even when its title already exists.
|
||||
// Reuse the request key only for retries of the same submitted draft.
|
||||
const fingerprint = JSON.stringify(createData);
|
||||
if (createRequestRef.current?.fingerprint !== fingerprint) {
|
||||
createRequestRef.current = { fingerprint, idempotencyKey: createUuid() };
|
||||
// Reuse the request key only for retries of the same submitted draft, and
|
||||
// always for a create waiting for its files: it may already have reached
|
||||
// the server, and its key then replays that task instead of a second one.
|
||||
// The file set is compared without regard to selection order.
|
||||
let request = createRequestRef.current;
|
||||
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)) {
|
||||
request = { fingerprint, idempotencyKey: createUuid() };
|
||||
createRequestRef.current = request;
|
||||
}
|
||||
await createIssue.mutateAsync({
|
||||
...createData,
|
||||
allowDuplicate: true,
|
||||
idempotencyKey: createRequestRef.current.idempotencyKey,
|
||||
navigateOnCreate: newIssueDefaults.navigateOnCreate === true,
|
||||
});
|
||||
let createPayload: PendingCreate = {
|
||||
fingerprint, data: { ...createData, allowDuplicate: true, navigateOnCreate: newIssueDefaults.navigateOnCreate === true },
|
||||
...(stagedFiles.length ? { stagedFileNames: stagedFiles.map(file => file.file.name) } : {}),
|
||||
};
|
||||
if (request.recovering) {
|
||||
const original = request.payload;
|
||||
const rejectRecovery = (message: string): never => {
|
||||
setResendError({ title: "Saved request needs attention", body: message, retryable: false });
|
||||
throw new Error(message);
|
||||
};
|
||||
if (!original) rejectRecovery("The saved request is unavailable. Cancel it before creating another task.");
|
||||
let originalFingerprint: Record<string, unknown> = {};
|
||||
try { originalFingerprint = JSON.parse(original!.fingerprint); } catch {}
|
||||
const requiredFiles = originalFingerprint.stagedFiles;
|
||||
if (original!.stagedFileNames?.length && (!Array.isArray(requiredFiles) ||
|
||||
JSON.stringify([...requiredFiles].sort()) !== JSON.stringify(createFiles.map(stagedFileIdentity).sort()))) {
|
||||
rejectRecovery(`Attach the original files again: ${original!.stagedFileNames.join(", ")}.`);
|
||||
}
|
||||
const normalize = (_key: string, value: unknown) => value && typeof value === "object" && !Array.isArray(value)
|
||||
? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b))) : value;
|
||||
const fieldsChanged = Object.entries(original!.data).some(([key, value]) =>
|
||||
!["allowDuplicate", "navigateOnCreate"].includes(key) && JSON.stringify(value, normalize) !== JSON.stringify((createData as Record<string, unknown>)[key], normalize));
|
||||
if (fieldsChanged || (typeof originalFingerprint.companyId === "string" &&
|
||||
JSON.stringify(originalFingerprint, normalize) !== JSON.stringify(JSON.parse(fingerprint), normalize))) {
|
||||
rejectRecovery("Restore the saved task's original fields before retrying, or cancel the saved request to start another task.");
|
||||
}
|
||||
createPayload = original!;
|
||||
}
|
||||
request.payload = createPayload;
|
||||
const { idempotencyKey } = request;
|
||||
stagedFilesByKey.current.set(idempotencyKey, createFiles);
|
||||
firstAttemptKey.current = idempotencyKey;
|
||||
setResendError(null);
|
||||
let result;
|
||||
try {
|
||||
result = await durableCreate.submit(createPayload, { idempotencyKey });
|
||||
} finally {
|
||||
firstAttemptKey.current = null;
|
||||
}
|
||||
// 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;
|
||||
}
|
||||
|
||||
function handleKeyDown(e: React.KeyboardEvent) {
|
||||
@@ -885,7 +1190,7 @@ export function NewIssueDialog() {
|
||||
}
|
||||
|
||||
function stageFiles(files: File[]) {
|
||||
if (files.length === 0 || createIssue.isPending) return;
|
||||
if (files.length === 0 || createIssue.isPending || durableCreate.pending) return;
|
||||
setStagedFiles((current) => {
|
||||
const next = [...current];
|
||||
for (const file of files) {
|
||||
@@ -1200,13 +1505,44 @@ export function NewIssueDialog() {
|
||||
runSettings: composerSettings,
|
||||
onRunSettingsChange: setComposerSettings,
|
||||
header:
|
||||
hasTitle || isSubIssueMode ? (
|
||||
hasTitle || isSubIssueMode || durableCreate.pending || resendError ? (
|
||||
<div className="mb-3 flex flex-col gap-2 text-xs">
|
||||
{durableCreate.pending && durableCreate.status !== "sending" ? (
|
||||
<PendingSendNotice
|
||||
noun="task"
|
||||
persisted={durableCreate.persisted}
|
||||
resending={durableCreate.resending}
|
||||
stalled={durableCreate.status === "stalled"}
|
||||
onResendNow={durableCreate.resendNow}
|
||||
onCancel={() => {
|
||||
// The draft (title and description) is still saved; only the send stops.
|
||||
const cancelledKey = durableCreate.pending?.idempotencyKey;
|
||||
const cancelled = durableCreate.cancel();
|
||||
if (cancelled) {
|
||||
createRequestRef.current = null; setRestoredLaunch(null);
|
||||
if (awaitingFilesKey) clearPendingSend(awaitingFilesKey, cancelledKey);
|
||||
if (cancelledKey) clearCreateUploadReceipts(cancelledKey);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
{resendError && !durableCreate.pending ? (
|
||||
<div>
|
||||
<p role="alert" className="text-sm text-destructive">{resendError.title}. {resendError.body}</p>
|
||||
{createRequestRef.current?.recovering ? <Button type="button" size="sm" variant="ghost" onClick={() => {
|
||||
const key = createRequestRef.current?.idempotencyKey;
|
||||
if (awaitingFilesKey && key) clearPendingSend(awaitingFilesKey, key);
|
||||
if (key) { stagedFilesByKey.current.delete(key); clearCreateUploadReceipts(key); }
|
||||
createRequestRef.current = null; setRestoredLaunch(null); setResendError(null);
|
||||
}}>Cancel saved request</Button> : null}
|
||||
</div>
|
||||
) : null}
|
||||
{hasTitle ? (
|
||||
<input
|
||||
aria-label="Task title"
|
||||
value={title}
|
||||
disabled={createIssue.isPending}
|
||||
// The waiting request is what gets created; later edits would be lost.
|
||||
disabled={createIssue.isPending || Boolean(durableCreate.pending)}
|
||||
className="w-full bg-transparent text-sm text-foreground outline-none"
|
||||
onChange={(event) => {
|
||||
titleRef.current = event.target.value;
|
||||
@@ -1378,7 +1714,8 @@ export function NewIssueDialog() {
|
||||
) : null}
|
||||
</>
|
||||
),
|
||||
submitDisabled: worktreeSelectionIncomplete || parentPrivacyUnresolved,
|
||||
submitDisabled: worktreeSelectionIncomplete || parentPrivacyUnresolved || Boolean(durableCreate.pending),
|
||||
readOnly: Boolean(durableCreate.pending),
|
||||
contextBar: (
|
||||
<>
|
||||
<InlineEntitySelector
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/**
|
||||
* Shown above a composer while a send waits for the connection. The text stays
|
||||
* on this device and resends with its original request ID, so it cannot post
|
||||
* twice; the user can resend now or take the text back with Cancel.
|
||||
*
|
||||
* Without `onResendNow` (a send saved by an older version, with no stored
|
||||
* request to replay) it only says the outcome is unknown and offers Cancel.
|
||||
*/
|
||||
export function PendingSendNotice({
|
||||
noun = "message",
|
||||
resending,
|
||||
stalled,
|
||||
persisted = false,
|
||||
onResendNow,
|
||||
onCancel,
|
||||
className,
|
||||
}: {
|
||||
/** What is being sent: "comment", "task", "update". */
|
||||
noun?: string;
|
||||
resending: boolean;
|
||||
stalled: boolean;
|
||||
persisted?: boolean;
|
||||
onResendNow?: () => void;
|
||||
onCancel: () => void;
|
||||
className?: string;
|
||||
}) {
|
||||
const replayable = Boolean(onResendNow);
|
||||
const title = !replayable
|
||||
? `We couldn’t confirm whether this ${noun} was sent.`
|
||||
: resending
|
||||
? "Sending…"
|
||||
: stalled
|
||||
? `Couldn’t send this ${noun} yet.`
|
||||
: "Sending when reconnected…";
|
||||
const detail = replayable
|
||||
? persisted ? `Your ${noun} is saved on this device.`
|
||||
: "Browser storage is unavailable. Keep this tab open or copy your text before leaving."
|
||||
: "It may already be in the conversation. Check it before sending again; Cancel keeps your text.";
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
data-testid="pending-send-notice"
|
||||
className={cn("space-y-2 rounded-md border border-border bg-muted p-3 text-sm", className)}
|
||||
>
|
||||
<p className="flex items-center gap-2 font-medium">
|
||||
{resending ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden /> : null}
|
||||
{title}
|
||||
</p>
|
||||
<p className="text-muted-foreground">{detail}</p>
|
||||
<div className="flex items-center gap-2">
|
||||
{onResendNow ? (
|
||||
<Button type="button" size="sm" variant="outline" disabled={resending} onClick={onResendNow}>
|
||||
Resend now
|
||||
</Button>
|
||||
) : null}
|
||||
<Button type="button" size="sm" variant="ghost" disabled={resending} onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -513,7 +513,6 @@ export function TaskChatThread(props: TaskChatThreadProps) {
|
||||
userProfileMap,
|
||||
currentUserId,
|
||||
onAdd,
|
||||
onReviewConversation,
|
||||
onCancelRun,
|
||||
stopPending,
|
||||
stopScope,
|
||||
@@ -3309,7 +3308,6 @@ export function TaskChatThread(props: TaskChatThreadProps) {
|
||||
comment.authorUserId === currentUserId && comment.clientRequestId &&
|
||||
!("clientStatus" in comment && comment.clientStatus)
|
||||
).map((comment) => comment.clientRequestId!))}
|
||||
onReviewConversation={onReviewConversation}
|
||||
onStop={liveRun ? onCancelRun : undefined}
|
||||
stopPending={stopPending}
|
||||
stopScope={stopScope}
|
||||
|
||||
@@ -9,6 +9,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { ExternallyConnectedTaskBanner } from "./ExternallyConnectedTaskBanner";
|
||||
import { boardSendDraftKey, readBoardSendDraft } from "./board-send-draft";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
const mockSession = vi.hoisted(() => ({ userId: "user-1" }));
|
||||
vi.mock("@/api/auth", () => ({
|
||||
authApi: { getSession: vi.fn(async () => ({ user: { id: mockSession.userId } })) },
|
||||
}));
|
||||
|
||||
const mockChatEndpointsApi = vi.hoisted(() => ({
|
||||
getIssueBinding: vi.fn(),
|
||||
@@ -20,6 +25,19 @@ const uploadAttachmentMock = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/api/issues", () => ({
|
||||
issuesApi: { uploadAttachment: uploadAttachmentMock },
|
||||
}));
|
||||
// Lets a test report that automatic resends stopped, without running eight
|
||||
// backoff rounds; otherwise the real hook runs.
|
||||
const autoResendOverride = vi.hoisted(() => ({ stalled: false }));
|
||||
vi.mock("@/hooks/useDurableSubmit", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/hooks/useDurableSubmit")>();
|
||||
return {
|
||||
...actual,
|
||||
useAutoResend: (options: Parameters<typeof actual.useAutoResend>[0]) => {
|
||||
const result = actual.useAutoResend(options);
|
||||
return autoResendOverride.stalled ? { ...result, stalled: true } : result;
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock("@/hooks/useChatConnectorsEnabled", async (importOriginal) => ({
|
||||
...await importOriginal<typeof import("@/hooks/useChatConnectorsEnabled")>(),
|
||||
useChatConnectorsEnabled: () => ({ enabled: true, githubEnabled: true, loaded: true }),
|
||||
@@ -99,6 +117,7 @@ describe("ExternallyConnectedTaskBanner publication truth", () => {
|
||||
new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
if (!existingQueryClient) queryClient.setQueryData(queryKeys.auth.session, { user: { id: mockSession.userId } });
|
||||
flushSync(() => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
@@ -131,6 +150,7 @@ describe("ExternallyConnectedTaskBanner publication truth", () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockSession.userId = "user-1";
|
||||
sessionStorage.clear();
|
||||
mockChatEndpointsApi.getPublicationBatchStatus.mockImplementation(
|
||||
() => new Promise(() => {}),
|
||||
@@ -154,6 +174,131 @@ describe("ExternallyConnectedTaskBanner publication truth", () => {
|
||||
flushSync(() => root.unmount());
|
||||
container.remove();
|
||||
vi.restoreAllMocks();
|
||||
autoResendOverride.stalled = false;
|
||||
});
|
||||
|
||||
it("cancels an automatic resend and hides its draft after an account change", async () => {
|
||||
mockChatEndpointsApi.publishBoardMessage.mockRejectedValue(new ApiError("Bad gateway", 502, {}));
|
||||
const client = await renderBanner();
|
||||
await composeAndSubmit("Private account A message");
|
||||
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(1);
|
||||
const retainedA = [...Array(sessionStorage.length)].map((_, index) => sessionStorage.getItem(sessionStorage.key(index)!));
|
||||
mockSession.userId = "user-2";
|
||||
await act(() => { client.setQueryData(queryKeys.auth.session, { user: { id: "user-2" } }); });
|
||||
await flushReact();
|
||||
await new Promise(resolve => setTimeout(resolve, 1_100));
|
||||
await flushReact();
|
||||
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(1);
|
||||
expect(container.querySelector("textarea")?.value ?? "").not.toContain("Private account A message");
|
||||
expect(container.textContent).not.toContain("Sending when reconnected");
|
||||
expect([...Array(sessionStorage.length)].map((_, index) => sessionStorage.getItem(sessionStorage.key(index)!))).toEqual(retainedA);
|
||||
client.clear();
|
||||
});
|
||||
|
||||
it("ignores an old account's late receipt after the session changes", async () => {
|
||||
let finish!: (result: unknown) => void;
|
||||
mockChatEndpointsApi.publishBoardMessage.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
|
||||
const client = await renderBanner();
|
||||
await composeAndSubmit("Private pending account A message");
|
||||
mockSession.userId = "user-2";
|
||||
await act(() => { client.setQueryData(queryKeys.auth.session, { user: { id: "user-2" } }); });
|
||||
await flushReact();
|
||||
await act(() => { finish({ id: "publication-old", state: "published", attempts: 1 }); });
|
||||
await flushReact();
|
||||
expect(pushToastMock).not.toHaveBeenCalled();
|
||||
expect(container.querySelector("textarea")?.value ?? "").not.toContain("Private pending account A message");
|
||||
expect(sessionStorage.length).toBe(1);
|
||||
client.clear();
|
||||
});
|
||||
|
||||
it("restores only the original account's retained send after returning to it", async () => {
|
||||
mockChatEndpointsApi.publishBoardMessage.mockRejectedValue(new ApiError("Bad gateway", 502, {}));
|
||||
const client = await renderBanner();
|
||||
await composeAndSubmit("Account A retained request");
|
||||
const originalKey = mockChatEndpointsApi.publishBoardMessage.mock.calls[0][3];
|
||||
mockSession.userId = "user-2";
|
||||
await act(() => { client.setQueryData(queryKeys.auth.session, { user: { id: "user-2" } }); });
|
||||
await flushReact();
|
||||
await act(() => findButton(container, "Send to channel").click());
|
||||
expect(container.querySelector("textarea")?.value).toBe("");
|
||||
mockSession.userId = "user-1";
|
||||
await act(() => { client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } }); });
|
||||
await flushReact();
|
||||
expect(container.querySelector("textarea")?.value).toBe("Account A retained request");
|
||||
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(1);
|
||||
mockChatEndpointsApi.publishBoardMessage.mockResolvedValueOnce({ id: "publication-recovered", state: "published", attempts: 1 });
|
||||
await act(() => findButton(container, "Retry safely").click());
|
||||
await flushReact();
|
||||
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenLastCalledWith("endpoint-1", "conversation-1", "Account A retained request", originalKey, []);
|
||||
});
|
||||
|
||||
it("does not reveal or replay an older retained send without a known owner", async () => {
|
||||
const key = boardSendDraftKey("company-1", "issue-1", "endpoint-1", "conversation-1");
|
||||
const saved = JSON.stringify({ body: "Unowned private message", attachmentIds: [], idempotencyKey: "legacy-request-key-1", publication: null });
|
||||
sessionStorage.setItem(key, saved);
|
||||
await renderBanner();
|
||||
expect(container.querySelector("textarea")?.value).toBe("");
|
||||
expect(container.querySelector("textarea")?.disabled).toBe(true);
|
||||
expect(container.textContent).toContain("Open Activity");
|
||||
expect(container.textContent).not.toContain("Unowned private message");
|
||||
expect(mockChatEndpointsApi.publishBoardMessage).not.toHaveBeenCalled();
|
||||
expect(sessionStorage.getItem(key)).toBe(saved);
|
||||
});
|
||||
|
||||
it.each([false, true])("can explicitly discard an unowned receipt without replaying its message (storage failure=%s)", async (storageFailure) => {
|
||||
const key = boardSendDraftKey("company-1", "issue-1", "endpoint-1", "conversation-1");
|
||||
const saved = JSON.stringify({ body: "Unowned private message", attachmentIds: [], idempotencyKey: "legacy-request-key-1", publication: null });
|
||||
sessionStorage.setItem(key, saved);
|
||||
await renderBanner();
|
||||
await act(() => findButton(container, "Discard saved delivery record").click());
|
||||
await flushReact();
|
||||
expect(document.body.textContent).toContain("does not cancel an update");
|
||||
const dialog = document.body.querySelector<HTMLElement>('[role="alertdialog"]')!;
|
||||
expect(dialog).toBeTruthy();
|
||||
await act(() => findButton(dialog, "Keep record").click());
|
||||
await flushReact();
|
||||
expect(sessionStorage.getItem(key)).toBe(saved);
|
||||
expect(container.querySelector("textarea")?.disabled).toBe(true);
|
||||
if (storageFailure) {
|
||||
const remove = vi.spyOn(Object.getPrototypeOf(sessionStorage), "removeItem").mockImplementation(() => { throw new Error("Storage unavailable"); });
|
||||
await act(() => findButton(container, "Discard saved delivery record").click());
|
||||
await flushReact();
|
||||
await act(() => findButton(document.body, "Discard record").click());
|
||||
await flushReact();
|
||||
expect(sessionStorage.getItem(key)).toBe(saved);
|
||||
expect(container.querySelector("textarea")?.disabled).toBe(true);
|
||||
expect(container.textContent).toContain("could not be discarded");
|
||||
expect(mockChatEndpointsApi.publishBoardMessage).not.toHaveBeenCalled();
|
||||
remove.mockRestore();
|
||||
}
|
||||
await act(() => findButton(container, "Discard saved delivery record").click());
|
||||
await flushReact();
|
||||
await act(() => findButton(document.body, "Discard record").click());
|
||||
await flushReact();
|
||||
expect(sessionStorage.getItem(key)).toBeNull();
|
||||
await act(() => findButton(container, "Send to channel").click());
|
||||
await flushReact();
|
||||
expect(container.querySelector("textarea")?.disabled).toBe(false);
|
||||
expect(container.querySelector("textarea")?.value).toBe("");
|
||||
expect(mockChatEndpointsApi.publishBoardMessage).not.toHaveBeenCalled();
|
||||
await act(() => setTextareaValue(container.querySelector("textarea")!, "Fresh deliberate message"));
|
||||
mockChatEndpointsApi.publishBoardMessage.mockResolvedValueOnce({ id: "fresh-publication", state: "published", attempts: 1 });
|
||||
await act(() => [...container.querySelectorAll("button")].filter(button => button.textContent?.trim() === "Send to channel").at(-1)!.click());
|
||||
await flushReact();
|
||||
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledWith("endpoint-1", "conversation-1", "Fresh deliberate message", expect.not.stringMatching("legacy-request-key-1"), []);
|
||||
});
|
||||
|
||||
it("asks for Resend now once automatic resends stop", async () => {
|
||||
autoResendOverride.stalled = true;
|
||||
mockChatEndpointsApi.publishBoardMessage.mockRejectedValue(
|
||||
new ApiError("Bad gateway", 502, { error: "Bad gateway" }),
|
||||
);
|
||||
await renderBanner();
|
||||
await composeAndSubmit();
|
||||
expect(container.textContent).toContain("Couldn’t send this update yet.");
|
||||
expect(container.textContent).toContain("Automatic resends stopped; choose Resend now");
|
||||
expect(container.textContent).not.toContain("It resends on its own");
|
||||
expect(findButton(container, "Resend now")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("only reports success and clears the draft after confirmed publication", async () => {
|
||||
@@ -322,6 +467,7 @@ describe("ExternallyConnectedTaskBanner publication truth", () => {
|
||||
"issue-1",
|
||||
"endpoint-1",
|
||||
"conversation-1",
|
||||
"user-1",
|
||||
),
|
||||
)?.attachmentNames,
|
||||
).toEqual([{ id: "uploaded-image", name: "cat.png" }]);
|
||||
@@ -879,7 +1025,12 @@ describe("ExternallyConnectedTaskBanner publication truth", () => {
|
||||
?.click(),
|
||||
);
|
||||
await flushReact();
|
||||
expect(container.textContent).toContain("Delivery result not confirmed");
|
||||
// A 5xx may have committed: it waits to resend with the same identity.
|
||||
expect(container.textContent).toContain(
|
||||
kind === "server-error"
|
||||
? "Sending when reconnected…"
|
||||
: "Delivery result not confirmed",
|
||||
);
|
||||
expect(container.textContent).not.toContain("Edit rejected send");
|
||||
expect(container.querySelector("textarea")?.disabled).toBe(true);
|
||||
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(1);
|
||||
@@ -1068,6 +1219,7 @@ describe("ExternallyConnectedTaskBanner publication truth", () => {
|
||||
"issue-1",
|
||||
"endpoint-1",
|
||||
"conversation-1",
|
||||
"user-1",
|
||||
),
|
||||
),
|
||||
).toBeNull();
|
||||
@@ -1217,6 +1369,7 @@ describe("ExternallyConnectedTaskBanner publication truth", () => {
|
||||
"issue-1",
|
||||
"endpoint-1",
|
||||
"conversation-1",
|
||||
"user-1",
|
||||
),
|
||||
),
|
||||
).toMatchObject({
|
||||
@@ -1231,6 +1384,7 @@ describe("ExternallyConnectedTaskBanner publication truth", () => {
|
||||
"issue-1",
|
||||
"endpoint-2",
|
||||
"conversation-2",
|
||||
"user-1",
|
||||
),
|
||||
),
|
||||
).toBeNull();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { TaskVoiceLauncher } from "@/components/voice/TaskVoiceLauncher";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { ExternalLink, Paperclip, Radio } from "lucide-react";
|
||||
import type {
|
||||
ChatPublicationState,
|
||||
@@ -22,6 +22,11 @@ import { cn } from "@/lib/utils";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { useChatConnectorsEnabled, chatProviderVisible } from "@/hooks/useChatConnectorsEnabled";
|
||||
import { issuesApi } from "@/api/issues";
|
||||
import { describeError } from "@/api/errors";
|
||||
import { classifySendFailure, type SendOutcome } from "@/lib/pending-send";
|
||||
import { useAutoResend } from "@/hooks/useDurableSubmit";
|
||||
import { useDraftOwner, useDraftOwnerReader } from "@/hooks/useDraftOwner";
|
||||
import { useAccountBoundMutation } from "@/hooks/useAccountBoundMutation";
|
||||
import {
|
||||
boardSendDraftKey,
|
||||
clearBoardSendDraft,
|
||||
@@ -33,6 +38,8 @@ import {
|
||||
type RetainedBoardSend,
|
||||
} from "./board-send-draft";
|
||||
|
||||
import { LegacyBoardSendNotice } from "./LegacyBoardSendNotice";
|
||||
|
||||
const providerNames: Record<ChatProvider, string> = {
|
||||
speko: "Speko",
|
||||
slack: "Slack",
|
||||
@@ -136,11 +143,13 @@ type ConnectedTaskProps = {
|
||||
|
||||
export function ExternallyConnectedTaskBanner(props: ConnectedTaskProps) {
|
||||
const { binding } = useIssueChatBinding(props.companyId, props.issueId);
|
||||
const draftOwner = useDraftOwner();
|
||||
return <>
|
||||
{binding && binding.provider !== "speko" && binding.provider !== "agentmail" && <ConnectedTaskComposer
|
||||
key={boardSendDraftKey(props.companyId, props.issueId, binding.endpointId, binding.conversationId)}
|
||||
{draftOwner !== undefined && binding && binding.provider !== "speko" && binding.provider !== "agentmail" && <ConnectedTaskComposer
|
||||
key={boardSendDraftKey(props.companyId, props.issueId, binding.endpointId, binding.conversationId, draftOwner)}
|
||||
{...props}
|
||||
binding={binding}
|
||||
draftOwner={draftOwner}
|
||||
/>}
|
||||
<TaskVoiceLauncher companyId={props.companyId} issueId={props.issueId} agentId={props.assigneeAgentId} boundEndpointId={binding?.provider === "speko" ? binding.endpointId : undefined} />
|
||||
</>;
|
||||
@@ -153,7 +162,9 @@ function ConnectedTaskComposer({
|
||||
issueId,
|
||||
issueCacheRefs,
|
||||
binding,
|
||||
}: ConnectedTaskProps & { binding: ExternalChannelBindingSummary }) {
|
||||
draftOwner,
|
||||
}: ConnectedTaskProps & { binding: ExternalChannelBindingSummary; draftOwner: string }) {
|
||||
const readOwner = useDraftOwnerReader();
|
||||
const { pushToast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
const [composing, setComposing] = useState(false);
|
||||
@@ -174,6 +185,7 @@ function ConnectedTaskComposer({
|
||||
);
|
||||
const [selectionNotice, setSelectionNotice] = useState(false);
|
||||
const [storageError, setStorageError] = useState<string | null>(null);
|
||||
const [unownedRequest, setUnownedRequest] = useState(false);
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
const uploadInFlight = useRef(false);
|
||||
const mounted = useRef(true);
|
||||
@@ -194,13 +206,21 @@ function ConnectedTaskComposer({
|
||||
issueId,
|
||||
binding.endpointId,
|
||||
binding.conversationId,
|
||||
draftOwner,
|
||||
)
|
||||
: null;
|
||||
const legacyStorageKey = boardSendDraftKey(companyId, issueId, binding.endpointId, binding.conversationId);
|
||||
const loadedStorageKey = useRef<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (!storageKey || loadedStorageKey.current === storageKey) return;
|
||||
loadedStorageKey.current = storageKey;
|
||||
try {
|
||||
if (sessionStorage.getItem(legacyStorageKey) !== null) {
|
||||
setUnownedRequest(true);
|
||||
setStorageError("An earlier update has an unknown sender. Open Activity to check its delivery before starting a new update.");
|
||||
setComposing(true);
|
||||
return;
|
||||
}
|
||||
const saved = readBoardSendDraft(storageKey);
|
||||
retainedScopeKey.current = storageKey;
|
||||
retainedSend.current = saved;
|
||||
@@ -220,7 +240,7 @@ function ConnectedTaskComposer({
|
||||
);
|
||||
setComposing(true);
|
||||
}
|
||||
}, [storageKey]);
|
||||
}, [legacyStorageKey, storageKey, unownedRequest]);
|
||||
const deliveryScopeReady = Boolean(
|
||||
storageKey &&
|
||||
loadedStorageKey.current === storageKey &&
|
||||
@@ -265,6 +285,7 @@ function ConnectedTaskComposer({
|
||||
const publicationStatus = useQuery({
|
||||
queryKey: [
|
||||
"chat-publication-batch",
|
||||
draftOwner,
|
||||
companyId,
|
||||
binding?.endpointId,
|
||||
binding?.conversationId,
|
||||
@@ -294,21 +315,23 @@ function ConnectedTaskComposer({
|
||||
finishPublication();
|
||||
}
|
||||
}, [publication, publicationStatus.data, finishPublication]);
|
||||
const publish = useMutation({
|
||||
const publish = useAccountBoundMutation({
|
||||
mutationFn: (input: {
|
||||
attachmentIds: string[];
|
||||
body: string;
|
||||
idempotencyKey: string;
|
||||
endpointId: string;
|
||||
conversationId: string;
|
||||
}) =>
|
||||
chatEndpointsApi.publishBoardMessage(
|
||||
}) => {
|
||||
if (readOwner() !== draftOwner) throw new DOMException("Your account changed. Reopen this task to send from your current account.", "AbortError");
|
||||
return chatEndpointsApi.publishBoardMessage(
|
||||
input.endpointId,
|
||||
input.conversationId,
|
||||
input.body,
|
||||
input.idempotencyKey,
|
||||
input.attachmentIds,
|
||||
),
|
||||
);
|
||||
},
|
||||
onSuccess: (result) => {
|
||||
invalidateTask();
|
||||
const feedback = publicationFeedback[result.state];
|
||||
@@ -366,16 +389,50 @@ function ConnectedTaskComposer({
|
||||
});
|
||||
return;
|
||||
}
|
||||
// Outages and lost receipts resend on their own with the same request
|
||||
// identity; the inline notice covers them.
|
||||
if (classifySendFailure(error) === "pending") return;
|
||||
pushToast({
|
||||
title: "Couldn't confirm channel delivery",
|
||||
body:
|
||||
error instanceof Error
|
||||
? `${error.message} Your draft is kept; retrying here reuses the same request identity.`
|
||||
: "Your draft is kept; retrying here reuses the same request identity.",
|
||||
body: `${describeError(error).body} Your draft is kept; retrying here reuses the same request identity.`,
|
||||
tone: "error",
|
||||
});
|
||||
},
|
||||
});
|
||||
// A send that failed with an outage or a lost receipt in this session
|
||||
// resends with its saved key; the server returns the original publication
|
||||
// instead of queueing another message. A send restored after reload has an
|
||||
// unknown outcome and waits for an explicit retry.
|
||||
const resendWaiting = Boolean(
|
||||
deliveryScopeReady &&
|
||||
unconfirmedRequest &&
|
||||
retainedSend.current &&
|
||||
!rejection &&
|
||||
!publication &&
|
||||
!storageError &&
|
||||
publish.status === "error" &&
|
||||
classifySendFailure(publish.error) === "pending",
|
||||
);
|
||||
const autoResend = useAutoResend({
|
||||
sourceId: `board-send:${storageKey ?? issueId}`,
|
||||
active: resendWaiting,
|
||||
resend: async (): Promise<SendOutcome> => {
|
||||
const input = retainedSend.current;
|
||||
if (!input || readOwner() !== draftOwner) return "rejected";
|
||||
try {
|
||||
await publish.mutateAsync({
|
||||
...input,
|
||||
endpointId: binding.endpointId,
|
||||
conversationId: binding.conversationId,
|
||||
});
|
||||
return "sent";
|
||||
} catch (error) {
|
||||
return classifySendFailure(error);
|
||||
}
|
||||
},
|
||||
});
|
||||
// Automatic resends gave up while online; only Resend now tries again.
|
||||
const resendStalled = resendWaiting && autoResend.stalled && !autoResend.resending;
|
||||
const uploadDisabled = Boolean(
|
||||
retainedSend.current ||
|
||||
publication ||
|
||||
@@ -653,9 +710,21 @@ function ConnectedTaskComposer({
|
||||
)}
|
||||
{storageError && (
|
||||
<p role="alert" className="text-xs text-destructive">
|
||||
{storageError}
|
||||
{storageError}{" "}
|
||||
<Link className="underline underline-offset-4" to={activityPath}>Open Activity</Link>
|
||||
</p>
|
||||
)}
|
||||
{unownedRequest && <LegacyBoardSendNotice onDiscard={() => {
|
||||
if (readOwner() !== draftOwner) return;
|
||||
try { clearBoardSendDraft(legacyStorageKey); }
|
||||
catch {
|
||||
setStorageError("Saved delivery record could not be discarded. Restore browser storage, then try again.");
|
||||
return;
|
||||
}
|
||||
loadedStorageKey.current = null;
|
||||
setUnownedRequest(false);
|
||||
setStorageError(null);
|
||||
}} />}
|
||||
{rejection && (
|
||||
<div
|
||||
role="alert"
|
||||
@@ -706,17 +775,26 @@ function ConnectedTaskComposer({
|
||||
)}
|
||||
{!rejection &&
|
||||
(publish.isError || unconfirmedRequest) &&
|
||||
!publish.isPending &&
|
||||
// An automatic resend keeps the waiting notice up while it runs.
|
||||
(!publish.isPending || autoResend.resending) &&
|
||||
!publication && (
|
||||
<div
|
||||
role="alert"
|
||||
className="space-y-1 rounded-md border border-border bg-background p-3 text-xs"
|
||||
>
|
||||
<p className="font-medium">Delivery result not confirmed</p>
|
||||
<p className="font-medium">
|
||||
{resendStalled
|
||||
? "Couldn’t send this update yet."
|
||||
: resendWaiting || autoResend.resending
|
||||
? "Sending when reconnected…"
|
||||
: "Delivery result not confirmed"}
|
||||
</p>
|
||||
<p className="text-muted-foreground">
|
||||
Your exact draft and request identity are kept. Retry safely
|
||||
to learn the authoritative publication state without creating
|
||||
a duplicate.
|
||||
{resendStalled
|
||||
? "Your exact draft and request identity are kept. Automatic resends stopped; choose Resend now to try again without creating a duplicate."
|
||||
: resendWaiting || autoResend.resending
|
||||
? "Your exact draft and request identity are kept. It resends on its own without creating a duplicate."
|
||||
: "Your exact draft and request identity are kept. Retry safely to learn the authoritative publication state without creating a duplicate."}
|
||||
</p>
|
||||
<Link
|
||||
className="inline-block font-medium underline underline-offset-4"
|
||||
@@ -845,11 +923,17 @@ function ConnectedTaskComposer({
|
||||
onClick={() => {
|
||||
if (
|
||||
uploadInFlight.current ||
|
||||
readOwner() !== draftOwner ||
|
||||
!storageKey ||
|
||||
loadedStorageKey.current !== storageKey ||
|
||||
retainedScopeKey.current !== storageKey
|
||||
)
|
||||
return;
|
||||
if (resendWaiting) {
|
||||
// Same saved request; also restarts the automatic resends.
|
||||
autoResend.resendNow();
|
||||
return;
|
||||
}
|
||||
idempotencyKey.current ??= crypto.randomUUID();
|
||||
const input = retainedSend.current ?? {
|
||||
attachmentIds: selectedAttachmentIds,
|
||||
@@ -883,7 +967,9 @@ function ConnectedTaskComposer({
|
||||
>
|
||||
{publish.isPending
|
||||
? "Sending…"
|
||||
: !rejection && (publish.isError || unconfirmedRequest)
|
||||
: resendWaiting
|
||||
? "Resend now"
|
||||
: !rejection && (publish.isError || unconfirmedRequest)
|
||||
? "Retry safely"
|
||||
: "Send to channel"}
|
||||
</Button>
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import {
|
||||
AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
|
||||
AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export function LegacyBoardSendNotice({ onDiscard }: { onDiscard: () => void }) {
|
||||
return <AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button size="sm" variant="outline">Discard saved delivery record</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Discard saved delivery record?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
First check Activity. Discarding this browser record does not cancel an update
|
||||
that was already accepted. It lets you start a new update.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Keep record</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={onDiscard}>Discard record</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>;
|
||||
}
|
||||
@@ -75,6 +75,18 @@ describe("session-scoped Board send identity", () => {
|
||||
clearBoardSendDraft(key);
|
||||
expect(readBoardSendDraft(key)).toBeNull();
|
||||
});
|
||||
it("keeps account-scoped sends separate from each other and unowned legacy records", () => {
|
||||
const scope = ["company", "task", "endpoint", "conversation"] as const;
|
||||
const a = boardSendDraftKey(...scope, "user-a");
|
||||
const b = boardSendDraftKey(...scope, "user-b");
|
||||
const legacy = boardSendDraftKey(...scope);
|
||||
const draft = { body: "Private A", attachmentIds: [], idempotencyKey: "stable-request-key-a", publication: null };
|
||||
writeBoardSendDraft(a, draft);
|
||||
expect(readBoardSendDraft(a)).toEqual(draft);
|
||||
expect(readBoardSendDraft(b)).toBeNull();
|
||||
expect(readBoardSendDraft(legacy)).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects corrupt retained identity instead of silently enabling a new send", () => {
|
||||
sessionStorage.setItem("corrupt", '{"body":"draft"}');
|
||||
expect(() => readBoardSendDraft("corrupt")).toThrow(
|
||||
|
||||
@@ -71,8 +71,12 @@ export function boardSendDraftKey(
|
||||
issueId: string,
|
||||
endpointId: string,
|
||||
conversationId: string,
|
||||
owner?: string,
|
||||
) {
|
||||
return `paperclip:board-send:v1:${JSON.stringify([companyId, issueId, endpointId, conversationId])}`;
|
||||
const scope = [companyId, issueId, endpointId, conversationId];
|
||||
return owner === undefined
|
||||
? `paperclip:board-send:v1:${JSON.stringify(scope)}`
|
||||
: `paperclip:board-send:v2:${JSON.stringify([owner, ...scope])}`;
|
||||
}
|
||||
|
||||
export function readBoardSendDraft(key: string): RetainedBoardSend | null {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act, type ReactElement } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { IssueChatThread } from "./IssueChatThread";
|
||||
import { TaskChatComposer } from "./task-chat/TaskChatComposer";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
import {
|
||||
loadDraftSubmission,
|
||||
saveDraft,
|
||||
saveDraftAttachments,
|
||||
saveDraftSubmission,
|
||||
} from "../lib/composer-draft";
|
||||
|
||||
vi.mock("./MarkdownEditor", async () => {
|
||||
const { forwardRef, useImperativeHandle, useRef } = await import("react");
|
||||
return {
|
||||
MarkdownEditor: forwardRef(function Editor(
|
||||
{ value, onChange, readOnly }: { value: string; onChange: (value: string) => void; readOnly?: boolean },
|
||||
ref,
|
||||
) {
|
||||
const input = useRef<HTMLTextAreaElement>(null);
|
||||
useImperativeHandle(ref, () => ({ focus: () => input.current?.focus(), clear: () => onChange("") }));
|
||||
return <textarea ref={input} aria-label="Recovery draft" value={value} readOnly={readOnly}
|
||||
onChange={event => onChange(event.target.value)} />;
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
let client: QueryClient;
|
||||
beforeEach(() => {
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
client = new QueryClient({ defaultOptions: { queries: { enabled: false, retry: false } } });
|
||||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||||
});
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
client.clear();
|
||||
});
|
||||
|
||||
describe.each(["task chat", "legacy thread"] as const)("%s composer recovery", surface => {
|
||||
it.each([false, true])("can send the retained draft after an already-reviewed unknown save (reload=%s)", async reload => {
|
||||
const key = "reviewed-unknown-save";
|
||||
const originalAttemptId = "9af8228f-0be7-45ae-a104-6fbe0af6f1d3";
|
||||
const attachmentId = "5e5f9946-c706-4785-8988-d4d6f0f499ab";
|
||||
const body = "I enabled the connection. Please try again.";
|
||||
const contentPath = `/api/attachments/${attachmentId}/content`;
|
||||
saveDraft(key, body);
|
||||
saveDraftAttachments(key, [{ attachmentId, name: "notes.txt", inline: false, contentPath }]);
|
||||
// This is the old persisted state shown after Review conversation. It has
|
||||
// no replayable request snapshot, so recovery must not blindly resend it.
|
||||
saveDraftSubmission(key, { attemptId: originalAttemptId, reviewed: true });
|
||||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||||
const composer: ReactElement = surface === "task chat"
|
||||
? <TaskChatComposer onAdd={onAdd} draftKey={key} workMode="standard" />
|
||||
: <MemoryRouter><IssueChatThread onAdd={onAdd} draftKey={key}
|
||||
comments={[]} linkedRuns={[]} timelineEvents={[]} liveRuns={[]}
|
||||
enableLiveTranscriptPolling={false} /></MemoryRouter>;
|
||||
const element = <QueryClientProvider client={client}>{composer}</QueryClientProvider>;
|
||||
await act(async () => root.render(element));
|
||||
if (reload) {
|
||||
await act(async () => root.unmount());
|
||||
root = createRoot(container);
|
||||
await act(async () => root.render(element));
|
||||
}
|
||||
const editor = () => container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Recovery draft"]')!;
|
||||
const send = () => container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-send"]')
|
||||
?? Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Send")!;
|
||||
expect(editor().value).toBe(body);
|
||||
expect(onAdd).not.toHaveBeenCalled();
|
||||
const recover = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Cancel");
|
||||
expect(recover, "An unknown save must offer a non-destructive way back to the composer").toBeDefined();
|
||||
await act(async () => recover!.click());
|
||||
expect(editor().readOnly).toBe(false);
|
||||
expect(editor().value).toBe(body);
|
||||
expect(container.textContent).toContain("notes.txt");
|
||||
expect(loadDraftSubmission(key)).toBeNull();
|
||||
expect(send().disabled).toBe(false);
|
||||
await act(async () => send().click());
|
||||
expect(onAdd).toHaveBeenCalledExactlyOnceWith(`${body}\n\n[notes.txt](${contentPath})`,
|
||||
undefined, undefined, [attachmentId], expect.any(String));
|
||||
expect(onAdd.mock.calls[0]![4]).not.toBe(originalAttemptId);
|
||||
expect(editor().value).toBe("");
|
||||
expect(container.textContent).not.toContain("notes.txt");
|
||||
// Recovery must leave ordinary sending usable, including after a reload.
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value")!.set!.call(editor(), "One more message");
|
||||
editor().dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
expect(send().disabled).toBe(false);
|
||||
await act(async () => send().click());
|
||||
expect(onAdd.mock.calls[1]![0]).toBe("One more message");
|
||||
expect(onAdd.mock.calls[1]![4]).not.toBe(onAdd.mock.calls[0]![4]);
|
||||
});
|
||||
});
|
||||
@@ -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";
|
||||
|
||||
@@ -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}
|
||||
|
||||
Reference in new issue
Block a user