mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-09 16:02:36 +01:00
## Thinking Path > - Paperclip lets people manage agent work through the board. > - The board already retains loaded reads during a temporary server failure. > - Reloading the page removes that in-memory data. > - A deploy can then leave a returning user without the shell or recent tasks. > - This pull request saves an explicit, limited set of reads in the browser. > - Cached identity supports display while fresh session checks protect writes. ## Linked Issues or Issue Description **What happened?** A reload during an API outage loses the board's loaded reads. An automatic worker update can also reload a hidden tab while a write is pending. **Expected behavior** Show the cached shell and recent tasks during a temporary outage. Limit saved content by user, company, age and build. Clear it on sign-out. Wait for a fresh session before sending account-bound writes. Defer automatic reloads while work is pending. **Steps to reproduce** Open a task and settings while online. Return 503 from the API and reload. Restore the API. Sign out and confirm that saved query records are gone. Discover a worker update while offline or during an autosave and confirm that it waits. Stacked on Refs #18822. Related durable-write foundation: Refs #17960. The outage browser suite follows in a separate test PR. ## What Changed - Persist an exact read allowlist through TanStack Query dehydration and hydration. Save shell preferences, company/sidebar data, agent/project lists, plugin UI metadata, the first inbox page, and 20 recent tasks. Task UUID and identifier reads share one recent-task slot. - Namespace records by user and company. Retain eligible reads across normal memory garbage collection, expire each read after 24 hours, and discard them after a build change. Unstamped builds disable hydration and persistence while retaining sign-out cleanup. Use the existing instance-wide plugin contribution query in the user's root record. - Exclude session credentials and bootstrap data, embedded plan documents, comments, preview work products, provider credentials and environment values, browser capabilities, pairing data, other queries, and mutations. Restore only display identity from session data. Preserve safe agent provider/model display fields and configuration object shapes. Apply the projection on save and restore. - Clear saved reads on sign-out, cross-tab account changes, and definitive session denial. Keep revocation working on plain HTTP without crypto.randomUUID. Use per-user revocation revisions to reject delayed writes and stale records. Preserve a newer account. Remove every UUID/identifier projection and nested inbox copy of a denied task. - Detach shared GETs when the account changes or signs out. Load complete, freshly authorized agents before opening bulk settings from a display-only roster. Retire a pending bulk-editor result or error when row, select-all or clear changes the selection, including a clear/reselect of the same agent. - Require a fresh server lookup before account-bound writes, pending task creation, or mounted autosaves resume. This includes automatic task read receipts, inbox archives, workspace preferences and primary-agent choices, with optimistic archive changes gated too. Cancel the old write scope when the verified user changes. Release completed archives through account-independent cleanup without restoring old cached rows; an old operation cannot clear a newer hide flag. Retry unconfirmed read receipts after a fresh session succeeds for the original account, and remember confirmed receipts across refreshes. Track pending reads per task so opening another task sends its receipt immediately; revisiting reuses an outstanding receipt and its original account scope. - Defer a hidden-tab worker reload until connectivity, mutations, durable sends, and autosaves are safe. Synchronously count each unresolved operation across online rate-limit retries. Release a cancelled target’s unused dirty token when an editor changes tasks; keep stored drafts, admitted saves and queued retries. Cover autosave debounce, newer edits, navigation and undo. ## Verification - Current head `fe4f682c879` is merge-ready: all 54 check runs completed (52 successful, one skipped, one neutral), the legacy Snyk status is successful, and both `ci / verify` and `ci / e2e` pass in run `41752927822`. Greptile Apex reviewed this exact head at 5/5 with zero unresolved threads; the branch has no merge conflicts. All three PRs now meet the merge-ready bar; the stack remains unmerged pending operator approval. - Greptile Apex reviewed exact current head `fe4f682c879` at 5/5 with no actionable findings and zero unresolved threads (summary updated 2026-11-04 at 01:24:40 UTC). Both settings-account and pending-selection findings are fixed, replied to and resolved. The branch has no merge conflicts. Current-head CI now passes in run `41752927822`. - Seventeen new cases cover settings restored from actual saved query records, matching/changed/signed-out identities, denied verification, late crown responses without overwriting newer reads, and bulk-selection changes during successful/failed reads. Sixteen fail the preceding source and one preserves denial compatibility. Both settings paths reuse the existing account-bound mutation guard; its optional explicit QueryClient supports the workspace hook’s existing detached-host mode. Primary-agent optimistic updates begin only after verification and cleanup checks ownership and the cache revision. - Earlier CI run `41749456480` on prior head `2cf7516f18c` has one real server test failure: the owned-runtime case in `idle-completed-history.test.ts` could not reach its HTTP child on port 34757 within 10 seconds (99 refused probes). Its other 1,829 cases pass and three skip; the only other unsuccessful job is the downstream `verify` gate. The exact selected case passes locally, and the entire 75-case file passes in 72.19 seconds on the exact `2cf7516f18c` source tree with isolated PostgreSQL and a real child process on macOS arm64/Node 25.6.1. The Linux CI startup cause remains unknown; these local results are not a fix or CI acceptance. One failed-jobs retry with debug logging was accepted on that unchanged head, then superseded by the later settings fixes. Current-head CI remains required; no source change was made for this failure. - Current cache head `fe4f682c879`, based on read head `09d1db29dea` and master `683fa4725e9`, passes all 1,198 focused tests across twenty-eight files, UI typecheck, token gates and the enforcing query-error guard. Dependent browser head `228c1b68d30` contains this exact application source and passes standalone strict checking of all three browser specs. Current-head CI now passes in run `41752927822`. - Three new navigation regressions fail the preceding application source and pass with the fix. They open three cached tasks before any receipt resolves, leave the page before success or failure, revisit an outstanding read without duplicating it, and recover an older failed receipt after a fresh session succeeds while a later task remains pending. - The fixture repair passes all seven deadline integration cases and the complete server typecheck, including the server test layer. The old assertion deterministically fails at 23:59:06.888 UTC; its one-second-old run also fails the first-second-of-day probe. The corrected fixture passes noon and both midnight probes. The permanent three-case coverage uses seeded 2099 clocks. - Nine new cases cover archive success/failure after sign-out and another account takes over, both mounted and unmounted; cleanup ownership when a newer archive uses the same task; session-check 429 exhaustion followed by matching, changed or signed-out identity; and a failed read receipt followed by a new session read. They verify no old-cache restoration, toast or navigation, retained newer hide flags, no failed-check loop and no duplicate confirmed receipt. Seven fail the previous implementation; two compatibility cases retain account-change suppression. Initial test error-constructor and query-notification timing assumptions were corrected before the passing checks. - The inherited skills/app error-priority fix passes all 60 affected tests and UI typecheck on both application branches. Its twelve new regression cases fail the preceding read implementation. The persisted-cache suite includes 48 cases. - Six new regressions fail against the preceding application source and pass with the fix. Actual worker-update and mutation-cache listeners cannot reload a hidden tab between online 429 retries; the original create key survives, and the update reloads once after a receipt. Real self-hosted and Cloud sign-out work without crypto.randomUUID, with stamped and unstamped builds. Saved reads are removed and account write scopes are invalidated. An initial test-fixture type annotation error was corrected before the passing typecheck. - The 48 cache tests cover actual five-minute memory GC, the 20-task bound across saved and live reads, original 24-hour expiry, denial before session verification, unstamped cleanup, cross-tab revocation and delayed flushes. Private GETs cannot cross account transitions. Bulk edits require complete current agent data. Undo releases the update blocker while preserving the Saved indicator. - All 23 built-UI outage/write/loading cases pass in 4.5 minutes on exact integrated head `228c1b68d30`, containing current cache revision `fe4f682c879`: ten outage, six durable-write and seven loading cases. The run uses bundled Chromium, the built UI, a fresh local-trusted server and isolated embedded PostgreSQL on macOS arm64/Node 25.6.1. All three specs pass standalone strict TypeScript checking. Owned temporary server and database stopped. - Earlier browser runs exposed and fixed cached-header, native Storage cleanup and replay/session defects. A prior run passed 21/22 because real WebSockets contradicted the simulated HTTP outage; the fixture now closes existing socket pairs and holds new sockets through the same outage deadline. An older CI run exposed a disposed response in the Inbox route callback; pre-navigation snapshots remove that lifetime, and the current full run includes that repair. Earlier failures and their diagnosis remain in the discussion. The current full run passes. Broader historical workspace failures remain documented in Refs #18822; this does not claim a clean full workspace suite. - Current-head CI passes on `fe4f682c879`. Controlled local outages do not complete hosted authentication or a real Cloud restart/deploy acceptance. Commands for the current cache change and inherited read fix (the current focused run also includes src/lib/inboxArchiveCache.test.ts and src/pages/Inbox.test.ts): ```sh pnpm --filter @paperclipai/ui exec vitest run src/pages/CompanySkills.test.tsx src/pages/apps/AppNotConnected.test.tsx pnpm --filter @paperclipai/ui exec vitest run src/hooks/useDurableSubmit.test.tsx src/hooks/useDurableAutosave.test.tsx src/hooks/useSignOut.test.tsx src/lib/persisted-query-cache.test.ts src/lib/service-worker-updates.test.ts src/lib/service-worker-cache-policy.test.ts src/lib/pending-send.test.ts src/lib/issue-execution-policy.test.ts src/components/InlineEditor.test.tsx src/components/MarkdownEditor.test.tsx src/components/NewIssueDialog.test.tsx pnpm --filter @paperclipai/ui exec vitest run src/components/agents/AgentBulkRoster.test.tsx src/components/agents/AgentBulkSettingsSheet.test.tsx src/hooks/useAccountBoundMutation.test.tsx src/pages/IssueDetail.test.tsx src/components/TaskChatThread.test.tsx src/components/TaskChatThread.task-creation-order.test.tsx src/api/client.test.ts src/api/agents.test.ts pnpm --filter @paperclipai/ui exec vitest run src/hooks/useCoordinatorWorkspaceEnabled.test.tsx src/context/PrimaryAgentProvider.test.tsx src/components/CoordinatorWorkspaceSetting.test.tsx src/components/primary-agent/PrimaryAgentPresentation.test.tsx src/components/MobileBottomNav.coordinator.test.tsx src/components/CoordinatorSidebar.test.tsx src/pages/Issues.coordinator-routing.test.tsx pnpm --filter @paperclipai/ui typecheck pnpm check:token-gates node scripts/check-query-error-rendering.mjs --enforce --summary ``` ## Risks This deliberately saves task content on the local browser for up to 24 hours. The allowlist excludes credentials and ephemeral capabilities. Local storage can be disabled or full; persistence then fails without blocking the app. Restored data can be stale and never grants server access. A user or access change clears cached account reads and invalidates pending writes. The browser outage suite and real hosted deploy acceptance remain release requirements. There are no migrations or new dependencies. ## Model Used OpenAI `gpt-6.1-sol` through Codex, with xhigh reasoning effort, tool use, and code execution. The context window size is not exposed. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used - [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 described the issue in-PR following the bug report template - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal ticket id - [x] The focused local tests for this change pass - [x] I have added tests and updated relevant documentation - [x] I have considered and documented 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: Paperclip <noreply@paperclip.ing> Co-authored-by: Bender (Fable) <bender@agents.paperclip.ing> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
741 lines
32 KiB
TypeScript
741 lines
32 KiB
TypeScript
// @vitest-environment jsdom
|
|
|
|
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 { hasPendingWrites } from "../lib/reload-safety";
|
|
import { markCachedSession } from "../lib/cached-session";
|
|
import { startPersistedQueryCache } from "../lib/persisted-query-cache";
|
|
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<
|
|
{ focus: () => void },
|
|
{ value: string; onChange: (value: string) => void }
|
|
>(function MarkdownEditorMock(props, ref) {
|
|
const taRef = useRef<HTMLTextAreaElement>(null);
|
|
useImperativeHandle(ref, () => ({
|
|
focus: () => taRef.current?.focus(),
|
|
}));
|
|
return (
|
|
<textarea
|
|
ref={taRef}
|
|
data-testid="multiline-md-mock"
|
|
value={props.value}
|
|
onChange={(e) => props.onChange(e.target.value)}
|
|
/>
|
|
);
|
|
}),
|
|
}));
|
|
|
|
vi.mock("./MarkdownBody", () => ({
|
|
MarkdownBody: ({ children }: { children: ReactNode }) => (
|
|
<div data-testid="multiline-md-preview">{children}</div>
|
|
),
|
|
}));
|
|
|
|
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"]');
|
|
if (preview) {
|
|
preview.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
|
}
|
|
}
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
|
|
|
/** Lets React detect a DOM value change on controlled textareas (see React #10140). */
|
|
function setNativeTextareaValue(textarea: HTMLTextAreaElement, value: string) {
|
|
const valueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value")?.set;
|
|
const previous = textarea.value;
|
|
valueSetter?.call(textarea, value);
|
|
const tracker = (textarea as HTMLTextAreaElement & { _valueTracker?: { setValue: (v: string) => void } })
|
|
._valueTracker;
|
|
tracker?.setValue(previous);
|
|
textarea.dispatchEvent(new Event("input", { bubbles: true }));
|
|
}
|
|
|
|
/** Matches `queueContainedBlurCommit` (double rAF before commit). Microtasks alone do not run these. */
|
|
function flushDoubleRequestAnimationFrame(): Promise<void> {
|
|
return new Promise((resolve) => {
|
|
requestAnimationFrame(() => {
|
|
requestAnimationFrame(() => {
|
|
resolve();
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
describe("InlineEditor", () => {
|
|
let container: HTMLDivElement;
|
|
|
|
beforeEach(() => {
|
|
container = document.createElement("div");
|
|
document.body.appendChild(container);
|
|
});
|
|
|
|
afterEach(() => {
|
|
container.remove();
|
|
});
|
|
|
|
it.each(["unchanged", "escape", "save", "failure"])("reports single-line editing through %s without an initial closed notification", async (exit) => {
|
|
const onEditingChange = vi.fn();
|
|
let resolve!: () => void;
|
|
let reject!: (error: Error) => void;
|
|
const onSave = vi.fn(() => new Promise<void>((done, fail) => { resolve = done; reject = fail; }));
|
|
const root = createRoot(container);
|
|
try {
|
|
await act(async () => root.render(signedIn("user-1", <InlineEditor value="Original" onSave={onSave} onEditingChange={onEditingChange} />)));
|
|
expect(onEditingChange).not.toHaveBeenCalled();
|
|
await act(async () => container.querySelector("span")!.click());
|
|
expect(onEditingChange.mock.calls).toEqual([[true]]);
|
|
const input = container.querySelector("textarea")!;
|
|
if (exit === "save" || exit === "failure") act(() => setNativeTextareaValue(input, "Edited title"));
|
|
await act(async () => input.dispatchEvent(new KeyboardEvent("keydown", { key: exit === "escape" ? "Escape" : "Enter", bubbles: true })));
|
|
if (exit === "save" || exit === "failure") {
|
|
expect(onSave).toHaveBeenCalledWith("Edited title");
|
|
expect(onEditingChange.mock.calls).toEqual([[true]]);
|
|
if (exit === "failure") {
|
|
await act(async () => reject(new Error("Save unavailable")));
|
|
expect(onEditingChange.mock.calls).toEqual([[true]]);
|
|
expect(container.querySelector("textarea")?.value).toBe("Edited title");
|
|
return;
|
|
}
|
|
await act(async () => resolve());
|
|
}
|
|
expect(onEditingChange.mock.calls).toEqual([[true], [false]]);
|
|
expect(container.querySelector("textarea")).toBeNull();
|
|
} finally { act(() => root.unmount()); }
|
|
});
|
|
|
|
it("reports a restored single-line edit and retires it before a late save completes", async () => {
|
|
const onEditingChange = vi.fn();
|
|
let resolve!: () => void;
|
|
const onSave = vi.fn(() => new Promise<void>((done) => { resolve = done; }));
|
|
localStorage.setItem("paperclip:inline-draft:v2:user-1:restored-callback", JSON.stringify({ version: 1, draft: "Restored title", base: "Original" }));
|
|
const root = createRoot(container);
|
|
try {
|
|
await act(async () => root.render(signedIn("user-1", <InlineEditor value="Original" draftKey="restored-callback" onSave={onSave} onEditingChange={onEditingChange} />)));
|
|
expect(onEditingChange.mock.calls).toEqual([[true]]);
|
|
expect(container.querySelector("textarea")?.value).toBe("Restored title");
|
|
act(() => root.unmount());
|
|
expect(onEditingChange.mock.calls).toEqual([[true], [false]]);
|
|
await act(async () => resolve());
|
|
expect(onEditingChange.mock.calls).toEqual([[true], [false]]);
|
|
} finally { localStorage.removeItem("paperclip:inline-draft:v2:user-1:restored-callback"); }
|
|
});
|
|
|
|
it("keeps one edit notification bound to the callback that opened it", async () => {
|
|
const opened = vi.fn();
|
|
const next = vi.fn();
|
|
const onSave = vi.fn();
|
|
const root = createRoot(container);
|
|
try {
|
|
await act(async () => root.render(<InlineEditor value="Original" onSave={onSave} onEditingChange={opened} />));
|
|
await act(async () => container.querySelector("span")!.click());
|
|
await act(async () => root.render(<InlineEditor value="Original" onSave={onSave} onEditingChange={next} />));
|
|
expect(opened.mock.calls).toEqual([[true]]);
|
|
expect(next).not.toHaveBeenCalled();
|
|
await act(async () => container.querySelector("textarea")!.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })));
|
|
expect(opened.mock.calls).toEqual([[true], [false]]);
|
|
expect(next).not.toHaveBeenCalled();
|
|
} finally { act(() => root.unmount()); }
|
|
});
|
|
|
|
it("calls onSave with empty string when nullable and the field is cleared (single-line)", () => {
|
|
const onSave = vi.fn().mockResolvedValue(undefined);
|
|
const root = createRoot(container);
|
|
|
|
act(() => {
|
|
root.render(<InlineEditor value="hello" nullable onSave={onSave} />);
|
|
});
|
|
|
|
const display = container.querySelector("span");
|
|
expect(display).not.toBeNull();
|
|
expect(display?.textContent).toBe("hello");
|
|
|
|
act(() => {
|
|
display!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
|
});
|
|
|
|
const textarea = container.querySelector("textarea");
|
|
expect(textarea).not.toBeNull();
|
|
|
|
act(() => {
|
|
setNativeTextareaValue(textarea!, "");
|
|
});
|
|
act(() => {
|
|
textarea!.blur();
|
|
});
|
|
|
|
expect(onSave).toHaveBeenCalledTimes(1);
|
|
expect(onSave).toHaveBeenCalledWith("");
|
|
|
|
act(() => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
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.each([false, true])("checks a restored draft against a fresh field after session verification (multiline=%s)", async (multiline) => {
|
|
const key = "paperclip:inline-draft:v2:user-1:cached-field";
|
|
localStorage.setItem(key, JSON.stringify({ version: 1, draft: "My draft B", base: "Cached A" }));
|
|
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
|
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
|
const cache = startPersistedQueryCache(client, { storage: null, buildId: "test", eventTarget: null });
|
|
markCachedSession(client);
|
|
let releaseSession!: () => void;
|
|
mockSession.pending = new Promise(resolve => { releaseSession = () => resolve({ user: { id: "user-1" } }); });
|
|
let releaseRead!: (value: string) => void;
|
|
const readCurrentValue = vi.fn<() => Promise<string>>().mockImplementationOnce(() => new Promise(resolve => { releaseRead = resolve; })).mockResolvedValue("New server C");
|
|
const onSave = vi.fn().mockResolvedValue(undefined);
|
|
const root = createRoot(container);
|
|
const render = (value: string) => root.render(<QueryClientProvider client={client}>
|
|
<InlineEditor value={value} multiline={multiline} draftKey="cached-field" onSave={onSave} readCurrentValue={readCurrentValue} />
|
|
</QueryClientProvider>);
|
|
try {
|
|
await act(async () => render("Cached A"));
|
|
expect(onSave).not.toHaveBeenCalled();
|
|
expect(readCurrentValue).not.toHaveBeenCalled();
|
|
await act(async () => releaseSession());
|
|
expect(readCurrentValue).toHaveBeenCalledOnce();
|
|
expect(onSave).not.toHaveBeenCalled();
|
|
await act(async () => releaseRead("New server C"));
|
|
await act(async () => render("New server C"));
|
|
expect(container.querySelector("textarea")?.value).toBe("My draft B");
|
|
expect(localStorage.getItem(key)).toContain("My draft B");
|
|
expect(onSave).not.toHaveBeenCalled();
|
|
if (!multiline) {
|
|
expect(container.querySelector("textarea")?.getAttribute("aria-invalid")).toBe("true");
|
|
expect(container.querySelector("textarea")?.getAttribute("aria-description")).toContain("This changed since you loaded it");
|
|
await act(async () => container.querySelector("textarea")!.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })));
|
|
expect(readCurrentValue).toHaveBeenCalledTimes(2);
|
|
expect(onSave).not.toHaveBeenCalled();
|
|
}
|
|
} finally { act(() => root.unmount()); cache.dispose(); client.clear(); mockSession.pending = null; }
|
|
});
|
|
|
|
it("replays a restored draft after a fresh field confirms its base", async () => {
|
|
localStorage.setItem("paperclip:inline-draft:v2:user-1:confirmed-field", JSON.stringify({ version: 1, draft: "Confirmed draft", base: "Original" }));
|
|
const readCurrentValue = vi.fn().mockResolvedValue("Original");
|
|
const onSave = vi.fn().mockResolvedValue(undefined);
|
|
const root = createRoot(container);
|
|
try {
|
|
await act(async () => root.render(signedIn("user-1", <InlineEditor value="Original" draftKey="confirmed-field" onSave={onSave} readCurrentValue={readCurrentValue} />)));
|
|
expect(readCurrentValue).toHaveBeenCalledOnce();
|
|
expect(onSave).toHaveBeenCalledWith("Confirmed draft");
|
|
} finally { 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("releases a cancelled description debounce when switching cached tasks and keeps its stored draft", async () => {
|
|
vi.useFakeTimers();
|
|
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={`task-${id}:description`} onSave={onSave} />
|
|
</QueryClientProvider>,
|
|
);
|
|
try {
|
|
await act(async () => renderTask("a", saveA));
|
|
act(() => enterMultilineEdit(container));
|
|
act(() => {
|
|
const textarea = container.querySelector<HTMLTextAreaElement>('[data-testid="multiline-md-mock"]')!;
|
|
textarea.focus();
|
|
setNativeTextareaValue(textarea, "A draft before navigation");
|
|
});
|
|
expect(hasPendingWrites()).toBe(true);
|
|
await act(async () => renderTask("b", saveB));
|
|
expect(hasPendingWrites()).toBe(false);
|
|
await act(async () => { await vi.advanceTimersByTimeAsync(1_000); });
|
|
expect(saveA).not.toHaveBeenCalled();
|
|
expect(saveB).not.toHaveBeenCalled();
|
|
expect(localStorage.getItem("paperclip:inline-draft:v2:user-1:task-a:description")).toContain("A draft before navigation");
|
|
} finally { act(() => root.unmount()); client.clear(); localStorage.clear(); vi.useRealTimers(); }
|
|
});
|
|
|
|
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);
|
|
|
|
act(() => {
|
|
root.render(<InlineEditor value="hello" onSave={onSave} />);
|
|
});
|
|
|
|
const display = container.querySelector("span");
|
|
expect(display).not.toBeNull();
|
|
|
|
act(() => {
|
|
display!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
|
});
|
|
|
|
const textarea = container.querySelector("textarea");
|
|
expect(textarea).not.toBeNull();
|
|
|
|
act(() => {
|
|
setNativeTextareaValue(textarea!, "");
|
|
});
|
|
act(() => {
|
|
textarea!.blur();
|
|
});
|
|
|
|
expect(onSave).not.toHaveBeenCalled();
|
|
|
|
act(() => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("releases update blocking when a newer multiline edit is undone after an older save completes", async () => {
|
|
vi.useFakeTimers();
|
|
const root = createRoot(container);
|
|
let complete!: () => void;
|
|
const onSave = vi.fn().mockImplementationOnce(() => new Promise<void>(resolve => { complete = resolve; }));
|
|
try {
|
|
await act(async () => root.render(<InlineEditor value="Original" multiline defaultEditing onSave={onSave} />));
|
|
const textarea = container.querySelector<HTMLTextAreaElement>("textarea")!;
|
|
act(() => { textarea.focus(); setNativeTextareaValue(textarea, "First edit"); });
|
|
await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
|
|
expect(onSave).toHaveBeenCalledWith("First edit");
|
|
act(() => setNativeTextareaValue(textarea, "Newer edit"));
|
|
await act(async () => { complete(); await Promise.resolve(); });
|
|
expect(container.textContent).toContain("Saved");
|
|
expect(hasPendingWrites()).toBe(true);
|
|
act(() => setNativeTextareaValue(textarea, "Original"));
|
|
expect(container.textContent).toContain("Saved");
|
|
expect(hasPendingWrites()).toBe(false);
|
|
await act(async () => { await vi.advanceTimersByTimeAsync(2000); });
|
|
expect(onSave).toHaveBeenCalledTimes(1);
|
|
expect(container.textContent).not.toContain("Saved");
|
|
} finally { act(() => root.unmount()); vi.useRealTimers(); }
|
|
});
|
|
|
|
it("multiline nullable clear uses autosave path (shows Saved after blur)", async () => {
|
|
const onSave = vi.fn().mockResolvedValue(undefined);
|
|
const root = createRoot(container);
|
|
const outside = document.createElement("button");
|
|
document.body.appendChild(outside);
|
|
|
|
act(() => {
|
|
root.render(<InlineEditor value="hello" multiline nullable onSave={onSave} />);
|
|
});
|
|
|
|
// Non-empty value renders MarkdownBody preview; click to enter edit mode.
|
|
act(() => {
|
|
enterMultilineEdit(container);
|
|
});
|
|
|
|
const textarea = container.querySelector<HTMLTextAreaElement>('[data-testid="multiline-md-mock"]');
|
|
expect(textarea).not.toBeNull();
|
|
|
|
act(() => {
|
|
textarea!.focus();
|
|
});
|
|
act(() => {
|
|
setNativeTextareaValue(textarea!, "");
|
|
});
|
|
act(() => {
|
|
outside.focus();
|
|
});
|
|
await act(async () => {
|
|
await flushDoubleRequestAnimationFrame();
|
|
});
|
|
|
|
expect(onSave).toHaveBeenCalledTimes(1);
|
|
expect(onSave).toHaveBeenCalledWith("");
|
|
expect(container.textContent).toContain("Saved");
|
|
|
|
act(() => {
|
|
root.unmount();
|
|
});
|
|
outside.remove();
|
|
});
|
|
|
|
it("multiline defaults to MarkdownBody preview when value is non-empty, swaps to editor on click", () => {
|
|
const onSave = vi.fn().mockResolvedValue(undefined);
|
|
const root = createRoot(container);
|
|
|
|
act(() => {
|
|
root.render(<InlineEditor value="Hello world" multiline onSave={onSave} />);
|
|
});
|
|
|
|
expect(container.querySelector('[data-testid="multiline-md-preview"]')).not.toBeNull();
|
|
expect(container.querySelector('[data-testid="multiline-md-mock"]')).toBeNull();
|
|
|
|
act(() => {
|
|
enterMultilineEdit(container);
|
|
});
|
|
|
|
expect(container.querySelector('[data-testid="multiline-md-mock"]')).not.toBeNull();
|
|
expect(container.querySelector('[data-testid="multiline-md-preview"]')).toBeNull();
|
|
|
|
act(() => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("enters multiline edit mode from the keyboard preview surface", () => {
|
|
const onSave = vi.fn().mockResolvedValue(undefined);
|
|
const root = createRoot(container);
|
|
|
|
act(() => {
|
|
root.render(<InlineEditor value="Hello world" multiline onSave={onSave} />);
|
|
});
|
|
|
|
const preview = container.querySelector<HTMLElement>('[role="textbox"]');
|
|
expect(preview).not.toBeNull();
|
|
|
|
expect(preview?.getAttribute("aria-multiline")).toBe("true");
|
|
expect(preview?.tabIndex).toBe(0);
|
|
|
|
act(() => {
|
|
preview!.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "Enter" }));
|
|
});
|
|
|
|
expect(container.querySelector('[data-testid="multiline-md-mock"]')).not.toBeNull();
|
|
expect(container.querySelector('[data-testid="multiline-md-preview"]')).toBeNull();
|
|
|
|
act(() => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("syncs a new multiline value while focused when the user has not edited locally", () => {
|
|
const onSave = vi.fn().mockResolvedValue(undefined);
|
|
const root = createRoot(container);
|
|
|
|
act(() => {
|
|
root.render(<InlineEditor value="" multiline onSave={onSave} />);
|
|
});
|
|
|
|
const textarea = container.querySelector<HTMLTextAreaElement>('[data-testid="multiline-md-mock"]');
|
|
expect(textarea).not.toBeNull();
|
|
expect(textarea?.value).toBe("");
|
|
|
|
act(() => {
|
|
textarea!.focus();
|
|
});
|
|
|
|
act(() => {
|
|
root.render(<InlineEditor value="Loaded description" multiline onSave={onSave} />);
|
|
});
|
|
|
|
expect(textarea?.value).toBe("Loaded description");
|
|
|
|
act(() => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("preserves focused multiline local edits when the prop value changes underneath them", () => {
|
|
const onSave = vi.fn().mockResolvedValue(undefined);
|
|
const root = createRoot(container);
|
|
|
|
act(() => {
|
|
root.render(<InlineEditor value="Original" multiline onSave={onSave} />);
|
|
});
|
|
|
|
// Non-empty value renders MarkdownBody preview; click to enter edit mode.
|
|
act(() => {
|
|
enterMultilineEdit(container);
|
|
});
|
|
|
|
const textarea = container.querySelector<HTMLTextAreaElement>('[data-testid="multiline-md-mock"]');
|
|
expect(textarea).not.toBeNull();
|
|
|
|
act(() => {
|
|
textarea!.focus();
|
|
});
|
|
act(() => {
|
|
setNativeTextareaValue(textarea!, "Local draft");
|
|
});
|
|
|
|
act(() => {
|
|
root.render(<InlineEditor value="Remote update" multiline onSave={onSave} />);
|
|
});
|
|
|
|
expect(textarea?.value).toBe("Local draft");
|
|
|
|
act(() => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("queueContainedBlurCommit", () => {
|
|
let container: HTMLDivElement;
|
|
let inside: HTMLTextAreaElement;
|
|
let outside: HTMLButtonElement;
|
|
let originalRequestAnimationFrame: typeof window.requestAnimationFrame;
|
|
let originalCancelAnimationFrame: typeof window.cancelAnimationFrame;
|
|
|
|
beforeEach(() => {
|
|
vi.useFakeTimers();
|
|
originalRequestAnimationFrame = window.requestAnimationFrame;
|
|
originalCancelAnimationFrame = window.cancelAnimationFrame;
|
|
window.requestAnimationFrame = ((callback: FrameRequestCallback) =>
|
|
window.setTimeout(() => callback(performance.now()), 0)) as typeof window.requestAnimationFrame;
|
|
window.cancelAnimationFrame = ((id: number) => window.clearTimeout(id)) as typeof window.cancelAnimationFrame;
|
|
|
|
container = document.createElement("div");
|
|
inside = document.createElement("textarea");
|
|
outside = document.createElement("button");
|
|
container.appendChild(inside);
|
|
document.body.append(container, outside);
|
|
});
|
|
|
|
afterEach(() => {
|
|
window.requestAnimationFrame = originalRequestAnimationFrame;
|
|
window.cancelAnimationFrame = originalCancelAnimationFrame;
|
|
container.remove();
|
|
outside.remove();
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
async function flushFrames() {
|
|
await act(async () => {
|
|
vi.runAllTimers();
|
|
await Promise.resolve();
|
|
});
|
|
}
|
|
|
|
it("commits when focus stays outside the editor container", async () => {
|
|
const onCommit = vi.fn();
|
|
const cancel = queueContainedBlurCommit(container, onCommit);
|
|
|
|
outside.focus();
|
|
await flushFrames();
|
|
|
|
expect(onCommit).toHaveBeenCalledTimes(1);
|
|
cancel();
|
|
});
|
|
|
|
it("skips the commit when focus returns inside before the delayed check completes", async () => {
|
|
const onCommit = vi.fn();
|
|
const cancel = queueContainedBlurCommit(container, onCommit);
|
|
|
|
outside.focus();
|
|
inside.focus();
|
|
await flushFrames();
|
|
|
|
expect(onCommit).not.toHaveBeenCalled();
|
|
cancel();
|
|
});
|
|
});
|