mirror of
https://github.com/paperclipai/paperclip
synced 2026-04-25 17:25:15 +02:00
fix(ui): keep latest issue document revision current (#3342)
## Thinking Path > - Paperclip orchestrates AI agents for zero-human companies. > - Board users and agents collaborate on issue-scoped documents such as plans and revisions need to be trustworthy because they are the audit trail for those artifacts. > - The issue document UI now supports revision history and restore, so the UI has to distinguish the current revision from historical revisions correctly even while multiple queries are refreshing. > - In `PAPA-72`, the newest content could appear under an older revision label because the current document snapshot and the revision-history query could temporarily disagree after an edit. > - That made the UI treat the newest revision like a historical restore target, which is the opposite of the intended behavior. > - This pull request derives one authoritative revision view from both sources, sorts revisions newest-first, and keeps the freshest revision marked current. > - The benefit is that revision history stays stable and trustworthy immediately after edits instead of briefly presenting the newest content as an older revision. ## What Changed - Added a `document-revisions` helper that merges the current document snapshot with fetched revision history into one normalized revision state. - Updated `IssueDocumentsSection` to render from that normalized state instead of trusting either query in isolation. - Added focused tests covering the current-revision selection and ordering behavior. ## Verification - `pnpm -r typecheck` - `pnpm build` - Targeted revision tests passed locally. - Manual reviewer check: - Open an issue document with revision history. - Edit and save the document. - Immediately open the revision selector. - Confirm the newest revision remains marked current and older revisions remain the restore targets. ## Risks - Low risk. The change is isolated to issue document revision presentation in the UI. - Main risk is merging the current snapshot with fetched history incorrectly for edge cases, which is why the helper has focused unit coverage. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [ ] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] If this change affects the UI, I have included before/after screenshots - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] I will address all Greptile and reviewer comments before requesting merge
This commit is contained in:
@@ -119,6 +119,35 @@ vi.mock("@/components/ui/dropdown-menu", async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const localStorageEntries = new Map<string, string>();
|
||||
|
||||
function ensureLocalStorageMock() {
|
||||
if (
|
||||
typeof window.localStorage?.getItem === "function"
|
||||
&& typeof window.localStorage?.setItem === "function"
|
||||
&& typeof window.localStorage?.removeItem === "function"
|
||||
&& typeof window.localStorage?.clear === "function"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object.defineProperty(window, "localStorage", {
|
||||
configurable: true,
|
||||
value: {
|
||||
getItem: (key: string) => localStorageEntries.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => {
|
||||
localStorageEntries.set(key, value);
|
||||
},
|
||||
removeItem: (key: string) => {
|
||||
localStorageEntries.delete(key);
|
||||
},
|
||||
clear: () => {
|
||||
localStorageEntries.clear();
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((res) => {
|
||||
@@ -221,6 +250,7 @@ describe("IssueDocumentsSection", () => {
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
ensureLocalStorageMock();
|
||||
window.localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
markdownEditorMockState.emitMountEmptyChange = false;
|
||||
@@ -311,6 +341,158 @@ describe("IssueDocumentsSection", () => {
|
||||
queryClient.clear();
|
||||
});
|
||||
|
||||
it("returns from a historical preview when the current revision only exists in derived state", async () => {
|
||||
const currentDocument = createIssueDocument({
|
||||
body: "Current plan body",
|
||||
latestRevisionId: "revision-4",
|
||||
latestRevisionNumber: 4,
|
||||
updatedAt: new Date("2026-03-31T12:05:00.000Z"),
|
||||
});
|
||||
const issue = createIssue();
|
||||
const root = createRoot(container);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
},
|
||||
mutations: {
|
||||
retry: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
mockIssuesApi.listDocuments.mockResolvedValue([currentDocument]);
|
||||
queryClient.setQueryData(
|
||||
queryKeys.issues.documentRevisions(issue.id, "plan"),
|
||||
[
|
||||
createRevision({
|
||||
id: "revision-3",
|
||||
revisionNumber: 3,
|
||||
body: "Historical plan body",
|
||||
createdAt: new Date("2026-03-31T11:00:00.000Z"),
|
||||
}),
|
||||
],
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<IssueDocumentsSection issue={issue} canDeleteDocuments={false} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
expect(container.textContent).toContain("Current plan body");
|
||||
|
||||
const revisionButtons = Array.from(container.querySelectorAll("button"));
|
||||
const historicalRevisionButton = revisionButtons.find((button) => button.textContent?.includes("rev 3"));
|
||||
expect(historicalRevisionButton).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
historicalRevisionButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain("Viewing revision 3");
|
||||
expect(container.textContent).toContain("Historical plan body");
|
||||
|
||||
const currentRevisionButton = Array.from(container.querySelectorAll("button"))
|
||||
.find((button) => button.textContent?.includes("rev 4"));
|
||||
expect(currentRevisionButton).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
currentRevisionButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(container.textContent).not.toContain("Viewing revision 3");
|
||||
expect(container.textContent).toContain("Current plan body");
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
queryClient.clear();
|
||||
});
|
||||
|
||||
it("returns from a historical preview when fetched history is newer than the document summary", async () => {
|
||||
const staleDocument = createIssueDocument({
|
||||
body: "Original plan body",
|
||||
latestRevisionId: "revision-2",
|
||||
latestRevisionNumber: 2,
|
||||
updatedAt: new Date("2026-03-31T12:00:00.000Z"),
|
||||
});
|
||||
const issue = createIssue();
|
||||
const root = createRoot(container);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
},
|
||||
mutations: {
|
||||
retry: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
mockIssuesApi.listDocuments.mockResolvedValue([staleDocument]);
|
||||
queryClient.setQueryData(
|
||||
queryKeys.issues.documentRevisions(issue.id, "plan"),
|
||||
[
|
||||
createRevision({
|
||||
id: "revision-3",
|
||||
revisionNumber: 3,
|
||||
body: "Current plan body",
|
||||
createdAt: new Date("2026-03-31T12:05:00.000Z"),
|
||||
}),
|
||||
createRevision({
|
||||
id: "revision-2",
|
||||
revisionNumber: 2,
|
||||
body: "Original plan body",
|
||||
createdAt: new Date("2026-03-31T12:00:00.000Z"),
|
||||
}),
|
||||
],
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<IssueDocumentsSection issue={issue} canDeleteDocuments={false} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
expect(container.textContent).toContain("Current plan body");
|
||||
|
||||
const revisionButtons = Array.from(container.querySelectorAll("button"));
|
||||
const historicalRevisionButton = revisionButtons.find((button) => button.textContent?.includes("rev 2"));
|
||||
expect(historicalRevisionButton).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
historicalRevisionButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain("Viewing revision 2");
|
||||
expect(container.textContent).toContain("Original plan body");
|
||||
|
||||
const currentRevisionButton = Array.from(container.querySelectorAll("button"))
|
||||
.find((button) => button.textContent?.includes("rev 3"));
|
||||
expect(currentRevisionButton).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
currentRevisionButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(container.textContent).not.toContain("Viewing revision 2");
|
||||
expect(container.textContent).toContain("Current plan body");
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
queryClient.clear();
|
||||
});
|
||||
|
||||
it("ignores mount-time editor change noise before a document is actively being edited", async () => {
|
||||
markdownEditorMockState.emitMountEmptyChange = true;
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import { useLocation } from "@/lib/router";
|
||||
import { ApiError } from "../api/client";
|
||||
import { issuesApi } from "../api/issues";
|
||||
import { useAutosaveIndicator } from "../hooks/useAutosaveIndicator";
|
||||
import { deriveDocumentRevisionState } from "../lib/document-revisions";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
import { cn, relativeTime } from "../lib/utils";
|
||||
import { MarkdownBody } from "./MarkdownBody";
|
||||
@@ -536,10 +537,10 @@ export function IssueDocumentsSection({
|
||||
}, []);
|
||||
|
||||
const previewRevision = useCallback((doc: IssueDocument, revisionId: string) => {
|
||||
const revisions = getDocumentRevisions(doc.key);
|
||||
const selectedRevision = revisions.find((revision) => revision.id === revisionId);
|
||||
const revisionState = deriveDocumentRevisionState(doc, getDocumentRevisions(doc.key));
|
||||
const selectedRevision = revisionState.revisions.find((revision) => revision.id === revisionId);
|
||||
if (!selectedRevision) return;
|
||||
if (selectedRevision.id === doc.latestRevisionId) {
|
||||
if (selectedRevision.id === revisionState.currentRevision.id) {
|
||||
returnToLatestRevision(doc.key);
|
||||
return;
|
||||
}
|
||||
@@ -787,7 +788,10 @@ export function IssueDocumentsSection({
|
||||
const activeDraft = draft?.key === doc.key && !draft.isNew ? draft : null;
|
||||
const activeConflict = documentConflict?.key === doc.key ? documentConflict : null;
|
||||
const isFolded = foldedDocumentKeys.includes(doc.key);
|
||||
const revisionHistory = getDocumentRevisions(doc.key);
|
||||
const rawRevisionHistory = getDocumentRevisions(doc.key);
|
||||
const revisionState = deriveDocumentRevisionState(doc, rawRevisionHistory);
|
||||
const revisionHistory = revisionState.revisions;
|
||||
const currentRevision = revisionState.currentRevision;
|
||||
const selectedRevisionId = selectedRevisionIds[doc.key] ?? null;
|
||||
const selectedHistoricalRevision = selectedRevisionId
|
||||
? revisionHistory.find((revision) => revision.id === selectedRevisionId) ?? null
|
||||
@@ -795,10 +799,10 @@ export function IssueDocumentsSection({
|
||||
const isHistoricalPreview = Boolean(selectedHistoricalRevision);
|
||||
const displayedTitle = selectedHistoricalRevision
|
||||
? selectedHistoricalRevision.title ?? ""
|
||||
: activeDraft?.title ?? doc.title ?? "";
|
||||
const displayedBody = selectedHistoricalRevision?.body ?? activeDraft?.body ?? doc.body;
|
||||
const displayedRevisionNumber = selectedHistoricalRevision?.revisionNumber ?? doc.latestRevisionNumber;
|
||||
const displayedUpdatedAt = selectedHistoricalRevision?.createdAt ?? doc.updatedAt;
|
||||
: activeDraft?.title ?? currentRevision.title ?? "";
|
||||
const displayedBody = selectedHistoricalRevision?.body ?? activeDraft?.body ?? currentRevision.body;
|
||||
const displayedRevisionNumber = selectedHistoricalRevision?.revisionNumber ?? currentRevision.revisionNumber;
|
||||
const displayedUpdatedAt = selectedHistoricalRevision?.createdAt ?? currentRevision.createdAt;
|
||||
const showTitle = !isPlanKey(doc.key) && !!displayedTitle.trim() && !titlesMatchKey(displayedTitle, doc.key);
|
||||
const canVoteOnDocument = Boolean(doc.latestRevisionId && doc.updatedByAgentId && !doc.updatedByUserId && onVote);
|
||||
|
||||
@@ -845,12 +849,12 @@ export function IssueDocumentsSection({
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-72">
|
||||
<DropdownMenuLabel>Revision history</DropdownMenuLabel>
|
||||
{revisionMenuOpenKey === doc.key && isFetchingDocumentRevisions && revisionHistory.length === 0 ? (
|
||||
{revisionMenuOpenKey === doc.key && isFetchingDocumentRevisions && rawRevisionHistory.length === 0 ? (
|
||||
<DropdownMenuItem disabled>Loading revisions...</DropdownMenuItem>
|
||||
) : revisionHistory.length > 0 ? (
|
||||
<DropdownMenuRadioGroup value={selectedRevisionId ?? doc.latestRevisionId ?? ""}>
|
||||
<DropdownMenuRadioGroup value={selectedRevisionId ?? currentRevision.id ?? ""}>
|
||||
{revisionHistory.map((revision) => {
|
||||
const isCurrentRevision = revision.id === doc.latestRevisionId;
|
||||
const isCurrentRevision = revision.id === currentRevision.id;
|
||||
return (
|
||||
<DropdownMenuRadioItem
|
||||
key={revision.id}
|
||||
|
||||
95
ui/src/lib/document-revisions.test.ts
Normal file
95
ui/src/lib/document-revisions.test.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import type { DocumentRevision, IssueDocument } from "@paperclipai/shared";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { deriveDocumentRevisionState } from "./document-revisions";
|
||||
|
||||
function createDocument(overrides: Partial<IssueDocument> = {}): IssueDocument {
|
||||
return {
|
||||
id: "document-1",
|
||||
companyId: "company-1",
|
||||
issueId: "issue-1",
|
||||
key: "plan",
|
||||
title: "Plan",
|
||||
format: "markdown",
|
||||
body: "# Current plan",
|
||||
latestRevisionId: "revision-2",
|
||||
latestRevisionNumber: 2,
|
||||
createdByAgentId: "agent-1",
|
||||
createdByUserId: null,
|
||||
updatedByAgentId: "agent-1",
|
||||
updatedByUserId: null,
|
||||
createdAt: new Date("2026-04-10T15:00:00.000Z"),
|
||||
updatedAt: new Date("2026-04-10T16:00:00.000Z"),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createRevision(overrides: Partial<DocumentRevision> = {}): DocumentRevision {
|
||||
return {
|
||||
id: "revision-1",
|
||||
companyId: "company-1",
|
||||
documentId: "document-1",
|
||||
issueId: "issue-1",
|
||||
key: "plan",
|
||||
revisionNumber: 1,
|
||||
title: "Plan",
|
||||
format: "markdown",
|
||||
body: "# Revision body",
|
||||
changeSummary: null,
|
||||
createdByAgentId: "agent-1",
|
||||
createdByUserId: null,
|
||||
createdAt: new Date("2026-04-10T15:00:00.000Z"),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("deriveDocumentRevisionState", () => {
|
||||
it("falls back to a synthetic current revision when no revision history has been fetched yet", () => {
|
||||
const state = deriveDocumentRevisionState(createDocument({
|
||||
latestRevisionId: null,
|
||||
latestRevisionNumber: 0,
|
||||
body: "# Draft plan",
|
||||
}), []);
|
||||
|
||||
expect(state.currentRevision.id).toBe("document-1-latest");
|
||||
expect(state.currentRevision.body).toBe("# Draft plan");
|
||||
expect(state.revisions.map((revision) => revision.id)).toEqual(["document-1-latest"]);
|
||||
});
|
||||
|
||||
it("sorts fetched revisions newest-first even when the API payload is out of order", () => {
|
||||
const state = deriveDocumentRevisionState(createDocument(), [
|
||||
createRevision({ id: "revision-1", revisionNumber: 1, createdAt: new Date("2026-04-10T15:00:00.000Z") }),
|
||||
createRevision({ id: "revision-2", revisionNumber: 2, body: "# Current plan", createdAt: new Date("2026-04-10T16:00:00.000Z") }),
|
||||
]);
|
||||
|
||||
expect(state.currentRevision.id).toBe("revision-2");
|
||||
expect(state.revisions.map((revision) => revision.id)).toEqual(["revision-2", "revision-1"]);
|
||||
});
|
||||
|
||||
it("keeps the latest document revision current when the revision history cache is stale", () => {
|
||||
const state = deriveDocumentRevisionState(createDocument(), [
|
||||
createRevision({ id: "revision-1", revisionNumber: 1, body: "# Original plan" }),
|
||||
]);
|
||||
|
||||
expect(state.currentRevision.id).toBe("revision-2");
|
||||
expect(state.currentRevision.body).toBe("# Current plan");
|
||||
expect(state.revisions.map((revision) => revision.id)).toEqual(["revision-2", "revision-1"]);
|
||||
});
|
||||
|
||||
it("trusts the fetched revision history when it is newer than the document summary cache", () => {
|
||||
const staleDocument = createDocument({
|
||||
body: "# Original plan",
|
||||
latestRevisionId: "revision-1",
|
||||
latestRevisionNumber: 1,
|
||||
updatedAt: new Date("2026-04-10T15:00:00.000Z"),
|
||||
});
|
||||
|
||||
const state = deriveDocumentRevisionState(staleDocument, [
|
||||
createRevision({ id: "revision-2", revisionNumber: 2, body: "# Current plan", createdAt: new Date("2026-04-10T16:00:00.000Z") }),
|
||||
createRevision({ id: "revision-1", revisionNumber: 1, body: "# Original plan", createdAt: new Date("2026-04-10T15:00:00.000Z") }),
|
||||
]);
|
||||
|
||||
expect(state.currentRevision.id).toBe("revision-2");
|
||||
expect(state.currentRevision.body).toBe("# Current plan");
|
||||
expect(state.revisions.map((revision) => revision.id)).toEqual(["revision-2", "revision-1"]);
|
||||
});
|
||||
});
|
||||
72
ui/src/lib/document-revisions.ts
Normal file
72
ui/src/lib/document-revisions.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import type { DocumentRevision, IssueDocument } from "@paperclipai/shared";
|
||||
|
||||
type DocumentRevisionState = {
|
||||
currentRevision: DocumentRevision;
|
||||
revisions: DocumentRevision[];
|
||||
};
|
||||
|
||||
function toTimestamp(value: Date | string | null | undefined) {
|
||||
if (!value) return 0;
|
||||
const timestamp = new Date(value).getTime();
|
||||
return Number.isNaN(timestamp) ? 0 : timestamp;
|
||||
}
|
||||
|
||||
function sortRevisionsDescending(revisions: DocumentRevision[]) {
|
||||
return [...revisions].sort((a, b) => {
|
||||
if (a.revisionNumber !== b.revisionNumber) {
|
||||
return b.revisionNumber - a.revisionNumber;
|
||||
}
|
||||
const createdAtDelta = toTimestamp(b.createdAt) - toTimestamp(a.createdAt);
|
||||
if (createdAtDelta !== 0) return createdAtDelta;
|
||||
return b.id.localeCompare(a.id);
|
||||
});
|
||||
}
|
||||
|
||||
function createCurrentRevisionSnapshot(document: IssueDocument): DocumentRevision {
|
||||
return {
|
||||
id: document.latestRevisionId ?? `${document.id}-latest`,
|
||||
companyId: document.companyId,
|
||||
documentId: document.id,
|
||||
issueId: document.issueId,
|
||||
key: document.key,
|
||||
revisionNumber: document.latestRevisionNumber,
|
||||
title: document.title,
|
||||
format: document.format,
|
||||
body: document.body,
|
||||
changeSummary: null,
|
||||
createdByAgentId: document.updatedByAgentId ?? document.createdByAgentId,
|
||||
createdByUserId: document.updatedByUserId ?? document.createdByUserId,
|
||||
createdAt: document.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
export function deriveDocumentRevisionState(
|
||||
document: IssueDocument,
|
||||
revisions: DocumentRevision[],
|
||||
): DocumentRevisionState {
|
||||
const sortedRevisions = sortRevisionsDescending(revisions);
|
||||
const currentSnapshot = createCurrentRevisionSnapshot(document);
|
||||
const highestFetchedRevision = sortedRevisions[0] ?? null;
|
||||
const documentAppearsStale = Boolean(
|
||||
highestFetchedRevision && highestFetchedRevision.revisionNumber > document.latestRevisionNumber,
|
||||
);
|
||||
|
||||
const currentRevision = documentAppearsStale
|
||||
? highestFetchedRevision!
|
||||
: sortedRevisions.find((revision) => revision.id === document.latestRevisionId) ?? currentSnapshot;
|
||||
|
||||
const revisionsWithCurrent = sortRevisionsDescending([currentRevision, ...sortedRevisions]);
|
||||
const dedupedRevisions: DocumentRevision[] = [];
|
||||
const seenRevisionIds = new Set<string>();
|
||||
|
||||
for (const revision of revisionsWithCurrent) {
|
||||
if (seenRevisionIds.has(revision.id)) continue;
|
||||
seenRevisionIds.add(revision.id);
|
||||
dedupedRevisions.push(revision);
|
||||
}
|
||||
|
||||
return {
|
||||
currentRevision,
|
||||
revisions: dedupedRevisions,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user