diff --git a/src/apps/desktop/README.md b/src/apps/desktop/README.md index 3af4631ee1..3e6dc6ae5c 100644 --- a/src/apps/desktop/README.md +++ b/src/apps/desktop/README.md @@ -155,10 +155,15 @@ when moving or sharing the project. **Save PDF** writes an editable on the viewing device. Saved PDFs embed their review state so notes and threads can be edited again when reopened in OpenBitFun; other PDF applications see standard PDF annotations. Replacing an existing output checks its current -version and asks before overwriting an externally changed file. +version and asks before overwriting an externally changed file. If the review +file changes elsewhere while this window has unsaved notes, saving pauses until +you choose **Replace with my notes** or **Load the file's notes**; Undo restores +the notes replaced by loading. Encrypted PDFs can be reviewed, but **Save PDF** +and **Export annotated PDF** are unavailable for them. Annotations retain PDF page coordinates across compilation. Check their positions -when a revision changes the layout; the preview shows a reminder after recompiling. +when a revision changes the layout; after recompiling, the preview shows a +reminder until you select **Positions checked**. LaTeX source remains the place to change manuscript text and figures. ![LaTeX source, PDF preview, and review notes in a sample writing workspace](../../../docs/images/paper-writing-workbench.png) diff --git a/src/web-ui/src/locales/en-US/tools.json b/src/web-ui/src/locales/en-US/tools.json index 45f9b48cf7..71acb3a26e 100644 --- a/src/web-ui/src/locales/en-US/tools.json +++ b/src/web-ui/src/locales/en-US/tools.json @@ -296,6 +296,12 @@ "reopen": "Reopen thread", "remove": "Delete annotation", "recompiled": "The PDF was recompiled. Annotations are retained by page; check their positions before saving.", + "encrypted": "This PDF is encrypted. Notes are saved in the review file, but an annotated PDF copy can't be created.", + "exportUnavailable": "This PDF can't be prepared for an annotated copy. Notes are still saved in the review file.", + "conflict": "The review file changed on the workspace host. Choose which notes to keep.", + "keepMine": "Replace with my notes", + "reloadFile": "Load the file's notes", + "confirmLayout": "Positions checked", "hints": { "highlight": "Select text in the PDF to highlight it.", "note": "Click a position on the PDF to add a note.", diff --git a/src/web-ui/src/locales/zh-CN/tools.json b/src/web-ui/src/locales/zh-CN/tools.json index 37034c6d27..490d198cad 100644 --- a/src/web-ui/src/locales/zh-CN/tools.json +++ b/src/web-ui/src/locales/zh-CN/tools.json @@ -296,6 +296,12 @@ "reopen": "重新打开评论", "remove": "删除批注", "recompiled": "PDF 已重新编译,批注按页保留;保存前请核对位置。", + "encrypted": "该 PDF 已加密。批注会保存在批注文件中,但无法生成带批注的 PDF 副本。", + "exportUnavailable": "无法为该 PDF 生成带批注的副本。批注仍会保存在批注文件中。", + "conflict": "批注文件已在工作区主机上被修改。请选择要保留的批注。", + "keepMine": "用我的批注覆盖", + "reloadFile": "载入文件中的批注", + "confirmLayout": "已核对位置", "hints": { "highlight": "在 PDF 中选中文字即可添加高亮。", "note": "点击 PDF 中的位置即可添加笔记。", diff --git a/src/web-ui/src/locales/zh-TW/tools.json b/src/web-ui/src/locales/zh-TW/tools.json index 5045f0be63..8d1eeb3076 100644 --- a/src/web-ui/src/locales/zh-TW/tools.json +++ b/src/web-ui/src/locales/zh-TW/tools.json @@ -296,6 +296,12 @@ "reopen": "重新開啟評論", "remove": "刪除註解", "recompiled": "PDF 已重新編譯,註解按頁保留;儲存前請核對位置。", + "encrypted": "此 PDF 已加密。註解會儲存在註解檔中,但無法產生含註解的 PDF 副本。", + "exportUnavailable": "無法為此 PDF 產生含註解的副本。註解仍會儲存在註解檔中。", + "conflict": "註解檔已在工作區主機上被修改。請選擇要保留的註解。", + "keepMine": "以我的註解覆寫", + "reloadFile": "載入檔案中的註解", + "confirmLayout": "已核對位置", "hints": { "highlight": "在 PDF 中選取文字即可加入醒目提示。", "note": "點擊 PDF 中的位置即可新增筆記。", diff --git a/src/web-ui/src/tools/editor/components/LatexEditor.test.tsx b/src/web-ui/src/tools/editor/components/LatexEditor.test.tsx index 5ef3cda554..850595c9cd 100644 --- a/src/web-ui/src/tools/editor/components/LatexEditor.test.tsx +++ b/src/web-ui/src/tools/editor/components/LatexEditor.test.tsx @@ -38,7 +38,7 @@ vi.mock('./CodeEditor', () => ({ }, })); vi.mock('../pdf-review/PdfReviewEditor', () => ({ - default: ({ pdfBase64 }: import('./PdfViewer').PdfViewerProps) =>
, + default: ({ pdfBase64, filePath }: import('./PdfViewer').PdfViewerProps) =>
, })); let container: HTMLDivElement; @@ -201,3 +201,57 @@ it.each([false, true])('inserts body snippets after the document start without r expect(source).toContain('\\begin{document}\n\\section{Title}\n'); expect(source).toContain('Existing text\n\\end{document}'); }); + +function mainFileInput() { + const input = container.querySelector('input[aria-label="editor.latexEditor.mainFile"]'); + if (!input) throw new Error('Main file input is missing'); + return input; +} +async function typeMainFile(value: string) { + const input = mainFileInput(); + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value); + input.dispatchEvent(new Event('input', { bubbles: true })); + await vi.advanceTimersByTimeAsync(1000); + }); +} +async function enableAutoCompile() { + await act(async () => { container.querySelector('[role="switch"]')!.click(); }); + await act(async () => { await vi.advanceTimersByTimeAsync(400); }); +} + +it('keeps the build target and review owner until the main-file entry is committed', async () => { + vi.useFakeTimers(); + mocks.invoke.mockResolvedValue({ pdfBase64: 'build' }); + await act(async () => { renderEditor(); }); + await enableAutoCompile(); + expect(mocks.invoke).toHaveBeenCalledTimes(1); + await act(async () => mainFileInput().focus()); + for (const partial of ['c', 'chapters/', 'chapters/paper.tex']) await typeMainFile(partial); + expect(mocks.invoke).toHaveBeenCalledTimes(1); + expect(container.querySelector('[data-pdf]')?.getAttribute('data-file')).toBe(path); + + await act(async () => { mainFileInput().dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); }); + await act(async () => { await vi.advanceTimersByTimeAsync(400); }); + expect(mocks.invoke).toHaveBeenCalledTimes(2); + expect(mocks.invoke).toHaveBeenLastCalledWith(origin, '/project/chapters/paper.tex', 'pdflatex'); + expect(container.querySelector('[data-pdf]')?.getAttribute('data-file')).toBe('/project/chapters/paper.tex'); +}); + +it('restores the committed main file on Escape and commits an edited entry on blur', async () => { + vi.useFakeTimers(); + mocks.invoke.mockResolvedValue({ pdfBase64: 'build' }); + await act(async () => { renderEditor(); }); + await enableAutoCompile(); + await act(async () => mainFileInput().focus()); + await typeMainFile('draft.tex'); + await act(async () => { mainFileInput().dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); }); + expect(mainFileInput().value).toBe(''); + await act(async () => { await vi.advanceTimersByTimeAsync(1000); }); + expect(mocks.invoke).toHaveBeenCalledTimes(1); + + await typeMainFile('appendix.tex'); + await act(async () => mainFileInput().blur()); + await act(async () => { await vi.advanceTimersByTimeAsync(400); }); + expect(mocks.invoke).toHaveBeenLastCalledWith(origin, '/project/appendix.tex', 'pdflatex'); +}); diff --git a/src/web-ui/src/tools/editor/components/LatexEditor.tsx b/src/web-ui/src/tools/editor/components/LatexEditor.tsx index 93c18b9f6c..449bd663c1 100644 --- a/src/web-ui/src/tools/editor/components/LatexEditor.tsx +++ b/src/web-ui/src/tools/editor/components/LatexEditor.tsx @@ -1,4 +1,4 @@ -import { Suspense, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import { Suspense, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react'; import { Button, IconButton, Input, Select, SplitView, Switch, Tooltip } from '@openbitfun/ui'; import { Code2, FileText, ListTree, Logs, PanelLeft, PanelRight, Play, Redo2, Save, Search, Undo2, X } from 'lucide-react'; import type * as Monaco from 'monaco-editor'; @@ -33,6 +33,8 @@ export default function LatexEditor(props: CodeEditorProps) { const [pdfOpen, setPdfOpen] = useState(retained?.pdf ?? true); const [previewWidth, setPreviewWidth] = useState(retained?.width ?? INITIAL_PREVIEW_WIDTH); const [mainFile, setMainFile] = useState(retained?.mainFile ?? ''); + // The build target and review owner change only on commit, never per keystroke. + const [mainFileDraft, setMainFileDraft] = useState(mainFile); const [source, setSource] = useState(document?.snapshot?.content ?? ''); const [outlineOpen, setOutlineOpen] = useState(false); const [logsOpen, setLogsOpen] = useState(false); @@ -173,6 +175,21 @@ export default function LatexEditor(props: CodeEditorProps) { try { await document?.saveAll(); } catch (failure) { setError(String(failure)); setLog(String(failure)); setLogsOpen(true); } }; + const commitMainFile = () => { + const value = mainFileDraft.trim(); + setMainFileDraft(value); + setMainFile(value); + }; + const handleMainFileKey = (event: KeyboardEvent) => { + if (event.key === 'Enter') { + event.preventDefault(); + commitMainFile(); + } else if (event.key === 'Escape' && mainFileDraft !== mainFile) { + event.preventDefault(); + event.stopPropagation(); + setMainFileDraft(mainFile); + } + }; return
@@ -214,8 +231,8 @@ export default function LatexEditor(props: CodeEditorProps) {
} aria-label={t('editor.latexEditor.outline')} aria-pressed={outlineOpen} onClick={() => setOutlineOpen(value => !value)} /> - + } onClick={() => setSourceOpen(false)} />
diff --git a/src/web-ui/src/tools/editor/pdf-review/PdfReviewEditor.test.tsx b/src/web-ui/src/tools/editor/pdf-review/PdfReviewEditor.test.tsx index 7210c98a22..7e2a6c7b0f 100644 --- a/src/web-ui/src/tools/editor/pdf-review/PdfReviewEditor.test.tsx +++ b/src/web-ui/src/tools/editor/pdf-review/PdfReviewEditor.test.tsx @@ -3,17 +3,27 @@ import { webcrypto } from 'node:crypto'; import { act } from 'react'; import { createRoot, type Root } from 'react-dom/client'; +import { PDFDocument } from 'pdf-lib'; import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import { activateSurface } from '@/infrastructure/peer-device/deviceSurface'; import { EditorDocument, EditorDocumentContext } from '../services/EditorDocument'; import PdfReviewEditor from './PdfReviewEditor'; import { getPdfReviewSession } from './PdfReviewSession'; import { parsePdfReview, type PdfReviewAnnotation } from './pdfReview'; +import { encryptedPdf } from './pdfReview.test-support'; + +const viewer = vi.hoisted(() => ({ pdf: undefined as unknown })); vi.mock('@/infrastructure/i18n', () => ({ useI18n: () => ({ t: (key: string) => key, formatNumber: String }), })); -vi.mock('../components/PdfViewer', () => ({ default: () =>
})); +vi.mock('../components/PdfViewer', async () => { + const { useEffect } = await import('react'); + return { default: ({ onDocumentLoaded }: { onDocumentLoaded?: (pdf: unknown) => void }) => { + useEffect(() => { if (viewer.pdf) onDocumentLoaded?.(viewer.pdf); }, []); + return
; + } }; +}); let container: HTMLDivElement; let root: Root; @@ -48,6 +58,7 @@ beforeEach(async () => { afterEach(async () => { await act(async () => root.unmount()); container.remove(); + viewer.pdf = undefined; vi.restoreAllMocks(); vi.unstubAllGlobals(); }); @@ -57,6 +68,25 @@ async function click(selector: string) { if (!button) throw new Error(`Missing review control: ${selector}`); await act(async () => button.click()); } +function buttonWithText(text: string) { + const button = [...container.querySelectorAll('button')].find(candidate => candidate.textContent === text); + if (!button) throw new Error(`Missing review control: ${text}`); + return button; +} +/** Asynchronous PDF inspection and host writes settle outside the triggering event. */ +async function waitUntil(condition: () => boolean) { + for (let attempt = 0; attempt < 100 && !condition(); attempt++) { + await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); }); + } + expect(condition()).toBe(true); +} +async function openLoadedPdf(bytes: Uint8Array, fingerprint = 'compiled-b') { + viewer.pdf = { fingerprints: [fingerprint], getData: async () => bytes.slice() }; + await act(async () => root.render(null)); + await act(async () => root.render( + + )); +} const thread = (index: number) => `.pdf-review-editor__thread:nth-child(${index})`; async function writeDraft(value: string) { const field = container.querySelector('textarea')!; @@ -139,3 +169,54 @@ it('keeps a collapsed comment draft and includes it in document Save All', async const content = writes[writes.length - 1]![1].request.content as string; expect(parsePdfReview(content).annotations[0]!.comments.at(-1)?.body).toBe('Pending reply while the comments are closed'); }); + +it('keeps an encrypted PDF reviewable without offering a broken annotated copy', async () => { + await openLoadedPdf(await encryptedPdf()); + await waitUntil(() => container.textContent?.includes('editor.pdfReview.encrypted') ?? false); + expect(container.querySelector('[role="alert"]')).toBeNull(); + expect(buttonWithText('editor.pdfReview.savePdf').disabled).toBe(true); + expect(container.querySelector('[aria-label="editor.pdfReview.export"]')?.disabled).toBe(true); +}); + +it('keeps the recompiled-layout notice until the user confirms the positions', async () => { + const session = getPdfReviewSession(document, path); + session.setFingerprint('compiled-a'); + session.replace([...session.getSnapshot().data.annotations, note('third')]); + await session.save(); + const pdf = await PDFDocument.create(); pdf.addPage(); + await openLoadedPdf(await pdf.save(), 'compiled-b'); + await waitUntil(() => container.textContent?.includes('editor.pdfReview.recompiled') ?? false); + await act(async () => buttonWithText('editor.pdfReview.confirmLayout').click()); + await waitUntil(() => !container.textContent?.includes('editor.pdfReview.recompiled')); + expect(session.getSnapshot().data.fingerprint).toBe('compiled-b'); +}); + +it('asks which notes to keep after the review file changes on the host', async () => { + const session = getPdfReviewSession(document, path); + const theirs = JSON.stringify({ version: 1, fingerprint: '', annotations: [note('theirs')] }, null, 2) + '\n'; + vi.spyOn(document.files, 'readFileContent').mockResolvedValue(theirs); + vi.mocked(document.invoke).mockRejectedValueOnce(new Error('FILE_CONFLICT: File changed after it was read; refresh before saving')); + await act(async () => { + session.replace([note('mine')]); + await session.save().catch(() => undefined); + }); + expect(container.textContent).toContain('editor.pdfReview.conflict'); + expect(container.textContent).not.toContain('editor.common.retry'); + await act(async () => buttonWithText('editor.pdfReview.keepMine').click()); + await waitUntil(() => !container.textContent?.includes('editor.pdfReview.conflict')); + const writes = vi.mocked(document.invoke).mock.calls; + expect(parsePdfReview(writes.at(-1)![1].request.content as string).annotations.map(item => item.id)).toEqual(['mine']); +}); + +it('does not fail document Save All for an unreadable review file without edits', async () => { + const blocked = new EditorDocument('review-blocked', { surfaceId: 'local', workspaceId: 'workspace-a' }, path); + vi.spyOn(blocked.files, 'getFileMetadata').mockRejectedValue(new Error('Permission denied')); + const write = vi.spyOn(blocked, 'invoke').mockResolvedValue(undefined); + await act(async () => root.render( + + )); + await act(async () => { await getPdfReviewSession(blocked, path).load(); }); + expect(getPdfReviewSession(blocked, path).getSnapshot().readOnly).toBe(true); + await expect(blocked.saveAll()).resolves.toBeUndefined(); + expect(write).not.toHaveBeenCalled(); +}); diff --git a/src/web-ui/src/tools/editor/pdf-review/PdfReviewEditor.tsx b/src/web-ui/src/tools/editor/pdf-review/PdfReviewEditor.tsx index 65789a65a6..ab96ce7433 100644 --- a/src/web-ui/src/tools/editor/pdf-review/PdfReviewEditor.tsx +++ b/src/web-ui/src/tools/editor/pdf-review/PdfReviewEditor.tsx @@ -7,11 +7,16 @@ import { savePdfFile } from '@/infrastructure/file-export/savePdfFile'; import { globalEventBus } from '@/infrastructure/event-bus'; import { useEditorDocument, type EditorDocument } from '../services/EditorDocument'; import PdfViewer, { type PdfViewerProps } from '../components/PdfViewer'; -import { getPdfReviewSession, PdfReviewExportConflict } from './PdfReviewSession'; +import { getPdfReviewSession, PdfReviewConflictError, PdfReviewExportConflict } from './PdfReviewSession'; import { confirmDialog } from '@/infrastructure/confirm-dialog'; -import { extractReviewedPdf, encodePdfBytes, type PdfReviewAnnotation, type PdfReviewColor, type PdfReviewTool } from './pdfReview'; +import { createLogger } from '@/shared/utils/logger'; +import { encodePdfBytes, PdfReviewEncryptedError, readPdfReviewSource, type PdfReviewAnnotation, type PdfReviewColor, type PdfReviewTool } from './pdfReview'; import './PdfReviewEditor.scss'; +const log = createLogger('PdfReviewEditor'); +/** Overlay notes and the sidecar keep working; only annotated PDF copies are blocked. */ +type AnnotatedCopyBlock = 'encrypted' | 'unreadable'; + export interface PdfReviewEditorProps extends PdfViewerProps { onDirtyStateChange?: (dirty: boolean) => void } export default function PdfReviewEditor(props: PdfReviewEditorProps) { const document = useEditorDocument(); @@ -33,8 +38,10 @@ function DocumentPdfReviewEditor({ document, onDirtyStateChange, ...props }: Pdf const [pdf, setPdf] = useState(); const [fingerprint, setFingerprint] = useState(''); const [preparedPdf, setPreparedPdf] = useState<{ input: string; base64: string }>(); + const [copyBlock, setCopyBlock] = useState(); const activePdfRef = useRef(); const [operation, setOperation] = useState<'save' | 'export'>(); + const [resolving, setResolving] = useState(false); const [message, setMessage] = useState(''); const [error, setError] = useState(''); const onDirtyRef = useRef(onDirtyStateChange); @@ -52,22 +59,29 @@ function DocumentPdfReviewEditor({ document, onDirtyStateChange, ...props }: Pdf const commitDraftRef = useRef(commitDraft); commitDraftRef.current = commitDraft; useEffect(() => document.registerSaveParticipant(`pdf-review-draft:${props.filePath}`, async () => { - commitDraftRef.current(); await session.save(); + commitDraftRef.current(); + // An unreadable review with nothing to write must not fail the source's Save All. + const { dirty, saving } = session.getSnapshot(); + if (dirty || saving) await session.save(); onDirtyRef.current?.(session.getSnapshot().dirty || !!draftRef.current.trim()); }), [document, props.filePath, session]); const onLoaded = useCallback((pdf: PDFDocumentProxy) => { - setPdf(pdf); activePdfRef.current = pdf; + setPdf(pdf); activePdfRef.current = pdf; setCopyBlock(undefined); void (async () => { try { await session.load(); const sourceBytes = await pdf.getData(); await session.observePdfBytes(sourceBytes); - const embedded = await extractReviewedPdf(sourceBytes); - if (activePdfRef.current !== pdf || !embedded) return; - session.importEmbedded(embedded.data); - setPreparedPdf({ input: props.pdfBase64 ?? props.filePath, base64: encodePdfBytes(embedded.bytes) }); + const source = await readPdfReviewSource(sourceBytes); + if (activePdfRef.current !== pdf) return; + if (source.encrypted) { setCopyBlock('encrypted'); return; } + if (!source.embedded) return; + session.importEmbedded(source.embedded.data); + setPreparedPdf({ input: props.pdfBase64 ?? props.filePath, base64: encodePdfBytes(source.embedded.bytes) }); } catch (failure) { - if (activePdfRef.current === pdf) setError(String(failure)); + // The viewer already rendered this file; only annotated copies need pdf-lib to parse it. + log.warn('PDF could not be prepared for annotated copies', { error: failure }); + if (activePdfRef.current === pdf) setCopyBlock('unreadable'); } })(); const value = pdf.fingerprints[0] ?? ''; @@ -117,10 +131,21 @@ function DocumentPdfReviewEditor({ document, onDirtyStateChange, ...props }: Pdf } } } catch (failure) { - setError(failure instanceof Error ? failure.message : String(failure)); + if (failure instanceof PdfReviewEncryptedError) setCopyBlock('encrypted'); + // The conflict notice already explains the paused write and offers both choices. + else if (!(failure instanceof PdfReviewConflictError)) setError(failure instanceof Error ? failure.message : String(failure)); } finally { setOperation(undefined); } }; + const resolveConflict = async (choice: 'local' | 'host') => { + setResolving(true); + setError(''); + try { await (choice === 'local' ? session.keepLocalChanges() : session.reloadFromHost()); } + catch (failure) { + if (!(failure instanceof PdfReviewConflictError)) setError(failure instanceof Error ? failure.message : String(failure)); + } finally { setResolving(false); } + }; const enabled = snapshot.loaded && !snapshot.readOnly && document.isCurrent() && props.isActiveTab !== false; + const copyEnabled = !!pdf && !operation && enabled && !copyBlock; const tools: Array<[PdfReviewTool, typeof MousePointer2]> = [ ['select', MousePointer2], ['highlight', Highlighter], ['note', MessageSquareText], ['ink', Pencil], ]; @@ -147,16 +172,26 @@ function DocumentPdfReviewEditor({ document, onDirtyStateChange, ...props }: Pdf } aria-label={t('editor.pdfReview.comments')} aria-pressed={commentsOpen} onClick={() => setCommentsOpen(value => !value)} /> - } aria-label={t('editor.pdfReview.export')} - disabled={!pdf || !!operation || !enabled} onClick={() => void run('export')} /> + disabled={!copyEnabled} onClick={() => void run('export')} />
- {stale &&
{t('editor.pdfReview.recompiled')}
} - {(snapshot.error || error) &&
+ {copyBlock &&
+ {t(copyBlock === 'encrypted' ? 'editor.pdfReview.encrypted' : 'editor.pdfReview.exportUnavailable')} +
} + {stale &&
+ {t('editor.pdfReview.recompiled')} + +
} + {snapshot.conflict ?
+ {t('editor.pdfReview.conflict')} {error && {error}} + + +
: (snapshot.error || error) &&
{t('editor.pdfReview.saveFailed')} {snapshot.error || error}
} diff --git a/src/web-ui/src/tools/editor/pdf-review/PdfReviewSession.test.ts b/src/web-ui/src/tools/editor/pdf-review/PdfReviewSession.test.ts index 8d58426000..4f32a392b5 100644 --- a/src/web-ui/src/tools/editor/pdf-review/PdfReviewSession.test.ts +++ b/src/web-ui/src/tools/editor/pdf-review/PdfReviewSession.test.ts @@ -3,7 +3,7 @@ import { webcrypto } from 'node:crypto'; import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import { EditorDocument } from '../services/EditorDocument'; import { activateSurface } from '@/infrastructure/peer-device/deviceSurface'; -import { PdfReviewSession, PdfReviewExportConflict } from './PdfReviewSession'; +import { getPdfReviewSession, PdfReviewSession, PdfReviewExportConflict } from './PdfReviewSession'; import { PDFDocument } from 'pdf-lib'; export function note(id = 'note-1'): PdfReviewAnnotation { return { id, kind: 'note', page: 1, rect: [20, 30, 40, 50], color: 'yellow', @@ -109,3 +109,77 @@ it('requires an exact approved version before replacing a pre-existing annotated await session.savePdf(bytes, expectedHash); expect(upload).toHaveBeenCalledWith(expect.objectContaining({ path: '/paper/main.annotated.pdf', workspaceId: 'workspace-a', expectedHash })); }); + +const theirs = JSON.stringify({ version: 1, fingerprint: '', annotations: [note('theirs')] }, null, 2) + '\n'; +const lastWrite = (write: ReturnType['write']) => write.mock.calls.at(-1)![1].request; +const savedIds = (write: ReturnType['write']) => + parsePdfReview(lastWrite(write).content as string).annotations.map(item => item.id); + +it.each([ + ['refused by the host', 'FILE_CONFLICT: File already exists; refresh before replacing it'], + ['after a lost response', 'Connection lost after write'], +])('holds unsaved notes in a conflict when another writer changed the file (%s)', async (_case, failure) => { + const { document, session, write } = createSession(); await session.load(); + vi.spyOn(document.files, 'readFileContent').mockResolvedValue(theirs); + write.mockRejectedValueOnce(new Error(failure)); + session.replace([note('mine')]); + await expect(session.save()).rejects.toThrow(); + await expect(session.save()).rejects.toThrow(); + expect(session.getSnapshot()).toMatchObject({ conflict: true, dirty: true }); + expect(session.getSnapshot().data.annotations.map(item => item.id)).toEqual(['mine']); + expect(write).toHaveBeenCalledTimes(1); +}); + +async function conflictedSession() { + const setup = createSession(); await setup.session.load(); + vi.spyOn(setup.document.files, 'readFileContent').mockResolvedValue(theirs); + setup.write.mockRejectedValueOnce(new Error('FILE_CONFLICT: File changed after it was read; refresh before saving')); + setup.session.replace([note('mine')]); + await expect(setup.session.save()).rejects.toThrow(); + return setup; +} + +it('replaces the changed review file with local notes only when the user keeps them', async () => { + const { session, write } = await conflictedSession(); + await session.keepLocalChanges(); + expect(session.getSnapshot()).toMatchObject({ conflict: false, dirty: false }); + expect(lastWrite(write).expectedHash).toBe(await pdfBytesHash(new TextEncoder().encode(theirs))); + expect(savedIds(write)).toEqual(['mine']); +}); + +it('loads the changed review file on request and can undo back to the local notes', async () => { + const { session, write } = await conflictedSession(); + await session.reloadFromHost(); + expect(session.getSnapshot()).toMatchObject({ conflict: false, dirty: false }); + expect(session.getSnapshot().data.annotations.map(item => item.id)).toEqual(['theirs']); + session.undo(); await session.save(); + expect(lastWrite(write).expectedHash).toBe(await pdfBytesHash(new TextEncoder().encode(theirs))); + expect(savedIds(write)).toEqual(['mine']); +}); + +it('keeps the earlier PDF fingerprint until the user confirms the recompiled layout', async () => { + const { session, write } = createSession(); await session.load(); + const savedFingerprint = () => parsePdfReview(lastWrite(write).content as string).fingerprint; + session.setFingerprint('compiled-a'); + session.replace([note('first')]); await session.save(); + expect(savedFingerprint()).toBe('compiled-a'); + session.setFingerprint('compiled-b'); + session.replace([note('first'), note('second')]); await session.save(); + expect(session.getSnapshot().data.fingerprint).toBe('compiled-a'); + expect(savedFingerprint()).toBe('compiled-a'); + const pdf = await PDFDocument.create(); pdf.addPage(); + await session.savePdf(await pdf.save()); + expect(session.getSnapshot().data.fingerprint).toBe('compiled-a'); + session.confirmCurrentLayout(); await session.save(); + expect(session.getSnapshot().data.fingerprint).toBe('compiled-b'); + expect(savedFingerprint()).toBe('compiled-b'); +}); + +it('does not let an unedited review path block document Save All', async () => { + const document = new EditorDocument('review-paths', { surfaceId: 'local', workspaceId: 'workspace-a' }, '/paper/main.tex'); + vi.spyOn(document.files, 'getFileMetadata').mockRejectedValue(new Error('Permission denied')); + const write = vi.spyOn(document, 'invoke').mockResolvedValue(undefined); + getPdfReviewSession(document, '/paper/ch'); + await expect(document.saveAll()).resolves.toBeUndefined(); + expect(write).not.toHaveBeenCalled(); +}); diff --git a/src/web-ui/src/tools/editor/pdf-review/PdfReviewSession.ts b/src/web-ui/src/tools/editor/pdf-review/PdfReviewSession.ts index b68dc9c28d..c1eae2f00f 100644 --- a/src/web-ui/src/tools/editor/pdf-review/PdfReviewSession.ts +++ b/src/web-ui/src/tools/editor/pdf-review/PdfReviewSession.ts @@ -8,12 +8,23 @@ import { annotatedPdfPath, decodePdfBytes, emptyPdfReview, exportReviewedPdf, pa export class PdfReviewExportConflict extends Error { constructor(readonly path: string, readonly expectedHash: string) { super('The PDF destination already exists or has changed.'); } } +/** Another writer changed the review file; unsaved notes wait for an explicit choice. */ +export class PdfReviewConflictError extends Error { + constructor() { + super('The review file changed on the workspace host. Existing notes have been preserved.'); + this.name = 'PdfReviewConflictError'; + } +} +// Both execution hosts report a failed compare-and-swap with this prefix; nothing was written. +const isWriteConflict = (error: unknown) => String(error).includes('FILE_CONFLICT'); export interface PdfReviewSnapshot { data: PdfReviewData; loaded: boolean; readOnly: boolean; dirty: boolean; saving: boolean; + /** Writes pause until the user keeps local notes or reloads the host file. */ + conflict: boolean; error?: string; canUndo: boolean; canRedo: boolean; @@ -21,7 +32,7 @@ export interface PdfReviewSnapshot { /** One owner per EditorDocument; hiding a pane never loses history or pending writes. */ export class PdfReviewSession { private snapshot: PdfReviewSnapshot = { - data: emptyPdfReview(), loaded: false, readOnly: false, dirty: false, saving: false, canUndo: false, canRedo: false, + data: emptyPdfReview(), loaded: false, readOnly: false, dirty: false, saving: false, conflict: false, canUndo: false, canRedo: false, }; private listeners = new Set<() => void>(); private past: PdfReviewAnnotation[][] = []; @@ -35,7 +46,10 @@ export class PdfReviewSession { private currentFingerprint = ''; private exportedHash?: string; constructor(readonly document: EditorDocument, readonly sourcePath: string) { - document.registerSaveParticipant(`pdf-review:${sourcePath}`, () => this.save()); + // Sessions outlive their pane, including ones for an abandoned main-file path. Save All + // owes a write only for notes changed here, so an unused path cannot block it. + document.registerSaveParticipant(`pdf-review:${sourcePath}`, + () => (this.snapshot.dirty || this.writing ? this.save() : Promise.resolve())); } readonly subscribe = (listener: () => void) => { this.listeners.add(listener); @@ -79,6 +93,17 @@ export class PdfReviewSession { this.publish({ data }); } setFingerprint(fingerprint: string) { this.currentFingerprint = fingerprint; } + /** + * The review keeps the fingerprint of the build its notes were placed on. Edits and + * PDF saves never move it; only this confirmation clears the recompiled-layout warning. + */ + confirmCurrentLayout() { + if (!this.snapshot.loaded || this.blocked || !this.document.isCurrent() || !this.currentFingerprint + || this.snapshot.data.fingerprint === this.currentFingerprint) return; + this.revision++; + this.publish({ data: { ...this.snapshot.data, fingerprint: this.currentFingerprint }, dirty: true, error: undefined }); + void this.save().catch(() => undefined); + } replace(annotations: PdfReviewAnnotation[]) { if (!this.snapshot.loaded || this.blocked || !this.document.isCurrent()) return; this.past.push(this.snapshot.data.annotations); @@ -107,36 +132,41 @@ export class PdfReviewSession { async save(): Promise { await this.load(); if (this.blocked) throw new Error(this.snapshot.error); + if (this.snapshot.conflict) throw new PdfReviewConflictError(); if (this.writing) return this.writing; if (!this.snapshot.dirty) return; this.writing = (async () => { try { this.publish({ saving: true, error: undefined }); // A lost response can follow a successful write. Reconcile only that - // known attempt before retrying; unrelated changes remain conflicts. + // known attempt before retrying; unrelated changes become a conflict. if (this.lastAttemptedContent !== undefined) { - let existing = ''; - try { existing = await this.document.files.readFileContent(reviewSidecarPath(this.sourcePath)); } - catch (failure) { if (!isLikelyFileNotFoundError(failure)) throw failure; } - const hash = existing ? await pdfBytesHash(new TextEncoder().encode(existing)) : ''; - if (existing === this.lastAttemptedContent) this.expectedHash = hash; - else if (hash !== this.expectedHash) throw new Error('The review file changed on the workspace host. Existing notes have been preserved.'); + const disk = await this.readSidecar(); + if (disk.content === this.lastAttemptedContent) this.expectedHash = disk.hash; + else if (disk.hash !== this.expectedHash) throw this.enterConflict(); this.lastAttemptedContent = undefined; } while (this.snapshot.dirty) { const revision = this.revision; - const data = { ...this.snapshot.data, fingerprint: this.currentFingerprint || this.snapshot.data.fingerprint }; + // The first notes are placed on the current build; later builds need confirmCurrentLayout. + const data = { ...this.snapshot.data, fingerprint: this.snapshot.data.fingerprint || this.currentFingerprint }; const content = JSON.stringify(data, null, 2) + '\n'; this.lastAttemptedContent = content; - await this.document.invoke('write_file_content', { request: { - filePath: reviewSidecarPath(this.sourcePath), content, expectedHash: this.expectedHash, - } }); + try { + await this.document.invoke('write_file_content', { request: { + filePath: reviewSidecarPath(this.sourcePath), content, expectedHash: this.expectedHash, + } }); + } catch (error) { + if (!isWriteConflict(error)) throw error; + this.lastAttemptedContent = undefined; + throw this.enterConflict(); + } this.expectedHash = await pdfBytesHash(new TextEncoder().encode(content)); this.lastAttemptedContent = undefined; this.publish({ dirty: this.revision !== revision, data: { ...this.snapshot.data, fingerprint: data.fingerprint } }); } } catch (error) { - this.publish({ error: String(error) }); + if (!(error instanceof PdfReviewConflictError)) this.publish({ error: String(error) }); throw error; } finally { this.writing = undefined; @@ -145,6 +175,41 @@ export class PdfReviewSession { })(); return this.writing; } + /** Explicitly replace the changed review file with the notes held in this window. */ + async keepLocalChanges(): Promise { + if (!this.snapshot.conflict || !this.document.isCurrent()) return; + const disk = await this.readSidecar(); + this.expectedHash = disk.hash; + this.lastAttemptedContent = undefined; + this.revision++; + this.publish({ conflict: false, dirty: true, error: undefined }); + await this.save(); + } + /** Explicitly load the changed review file; Undo restores the notes it replaced. */ + async reloadFromHost(): Promise { + if (!this.snapshot.conflict || !this.document.isCurrent()) return; + const disk = await this.readSidecar(); + const data = disk.content === undefined ? emptyPdfReview() : parsePdfReview(disk.content); + this.past.push(this.snapshot.data.annotations); + this.future = []; + this.expectedHash = disk.hash; + this.lastAttemptedContent = undefined; + this.revision++; + this.publish({ data, dirty: false, conflict: false, error: undefined }); + } + private enterConflict(): PdfReviewConflictError { + this.publish({ conflict: true }); + return new PdfReviewConflictError(); + } + private async readSidecar(): Promise<{ content?: string; hash: string }> { + try { + const content = await this.document.files.readFileContent(reviewSidecarPath(this.sourcePath)); + return { content, hash: await pdfBytesHash(new TextEncoder().encode(content)) }; + } catch (error) { + if (isLikelyFileNotFoundError(error)) return { hash: '' }; + throw error; + } + } async exportPdf(base: Uint8Array): Promise<{ bytes: Uint8Array; path: string }> { await this.load(); if (this.blocked) throw new Error(this.snapshot.error); @@ -156,11 +221,6 @@ export class PdfReviewSession { } async savePdf(base: Uint8Array, overwriteHash?: string): Promise { const scope = getActiveSurfaceScope(); - if (this.currentFingerprint && this.snapshot.data.annotations.length - && this.snapshot.data.fingerprint !== this.currentFingerprint && !this.blocked) { - this.revision++; - this.publish({ dirty: true, data: { ...this.snapshot.data, fingerprint: this.currentFingerprint } }); - } await this.save(); if (!this.document.isCurrent() || !this.document.scope.workspaceId) throw new Error('The PDF workspace is unavailable.'); const { bytes, path } = await this.exportPdf(base); diff --git a/src/web-ui/src/tools/editor/pdf-review/README.md b/src/web-ui/src/tools/editor/pdf-review/README.md index 3f645ce628..defd0f8cc9 100644 --- a/src/web-ui/src/tools/editor/pdf-review/README.md +++ b/src/web-ui/src/tools/editor/pdf-review/README.md @@ -1,21 +1,29 @@ # PDF review `PdfReviewSession` owns review history and serializes writes for one -`EditorDocument` and source path. Save All includes pending comment drafts. -Review JSON is versioned, preserves additive fields, and is written through the -document's workspace-scoped adapter with an expected content hash. Invalid or -unsupported records stay intact. A lost write response is reconciled against the -last attempted content before retrying. +`EditorDocument` and source path. Save All includes pending comment drafts and +writes only sessions with unsaved changes, so a session left behind by an +abandoned main-file path never blocks it. Review JSON is versioned, preserves +additive fields, and is written through the document's workspace-scoped adapter +with an expected content hash. Invalid or unsupported records stay intact. A lost +write response is reconciled against the last attempted content before retrying. +Any other host change enters a conflict: writes pause until the user explicitly +replaces that exact host version with local notes or loads the host file (Undo +restores the replaced local notes). Coordinates are PDF user-space points. `PdfReviewLayer` converts them through the current page viewport, so zoom and rotation do not change stored coordinates. -A source recompile preserves the review and warns when its PDF fingerprint changes; -page coordinates are not a text-reanchoring or SyncTeX implementation. +The review keeps the fingerprint of the build its notes were placed on. Edits and +PDF saves never update it; a recompile warning stays until the user confirms the +current layout. Page coordinates are not a text-reanchoring or SyncTeX implementation. `pdf-lib` (MIT) writes standard Highlight, Text/reply, and Ink annotations. It also embeds the review for reopening. Only our tagged annotations are replaced during export; other annotations and form fields remain. Saved appearances are removed before overlay editing, so deleting a reopened annotation also removes it visually. +`pdf-lib` can neither decrypt existing strings nor encrypt the objects it adds, so +encrypted PDFs are reviewed through the sidecar only and annotated copies are +disabled. PDFs that `pdf-lib` cannot parse are treated the same way. Workspace PDF saves use the existing bounded upload port and compare-and-swap hashes. Download/export belongs to the viewing controller. Neither path falls back to a controller-side workspace file. diff --git a/src/web-ui/src/tools/editor/pdf-review/pdfReview.test-support.ts b/src/web-ui/src/tools/editor/pdf-review/pdfReview.test-support.ts new file mode 100644 index 0000000000..1ee5c3b679 --- /dev/null +++ b/src/web-ui/src/tools/editor/pdf-review/pdfReview.test-support.ts @@ -0,0 +1,9 @@ +import { PDFDocument } from 'pdf-lib'; + +/** pdf-lib cannot encrypt; a Standard security handler makes readers decrypt every string and stream. */ +export async function encryptedPdf(): Promise { + const pdf = await PDFDocument.create(); + pdf.addPage(); + pdf.context.trailerInfo.Encrypt = pdf.context.register(pdf.context.obj({ Filter: 'Standard', V: 2, R: 3, Length: 128, P: -4 })); + return pdf.save(); +} diff --git a/src/web-ui/src/tools/editor/pdf-review/pdfReview.test.ts b/src/web-ui/src/tools/editor/pdf-review/pdfReview.test.ts index d2cf73f214..2e0f0e4121 100644 --- a/src/web-ui/src/tools/editor/pdf-review/pdfReview.test.ts +++ b/src/web-ui/src/tools/editor/pdf-review/pdfReview.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it } from 'vitest'; import { PDFDocument, PDFName, PDFDict, PDFHexString, PDFArray } from 'pdf-lib'; -import { exportReviewedPdf, extractReviewedPdf, readEmbeddedPdfReview, parsePdfReview, type PdfReviewAnnotation } from './pdfReview'; +import { exportReviewedPdf, PdfReviewEncryptedError, readEmbeddedPdfReview, readPdfReviewSource, + parsePdfReview, type PdfReviewAnnotation } from './pdfReview'; +import { encryptedPdf } from './pdfReview.test-support'; export function note(id = 'note-1'): PdfReviewAnnotation { return { id, kind: 'note', page: 1, rect: [20, 30, 40, 50], color: 'yellow', @@ -61,13 +63,23 @@ describe('portable PDF review data', () => { const review = { version: 1 as const, fingerprint: 'original', annotations: [note()] }; const saved = await exportReviewedPdf(await original.save(), review); expect(await readEmbeddedPdfReview(saved)).toEqual(review); - const opened = await extractReviewedPdf(saved); + const opened = (await readPdfReviewSource(saved)).embedded; expect(opened?.data).toEqual(review); expect((await PDFDocument.load(opened!.bytes)).getPage(0).node.Annots()?.size()).toBe(0); const revised = await exportReviewedPdf(saved, { ...review, annotations: [] }); expect((await PDFDocument.load(revised)).getPage(0).node.Annots()?.size()).toBe(0); const savedAgain = await exportReviewedPdf(saved, review); expect((await PDFDocument.load(savedAgain)).getPage(0).node.Annots()?.size()).toBe(1); + expect(await readPdfReviewSource(await original.save())).toEqual({ encrypted: false }); + }); + it('opens an encrypted PDF as having no embedded review instead of failing', async () => { + const bytes = await encryptedPdf(); + await expect(readEmbeddedPdfReview(bytes)).resolves.toBeUndefined(); + await expect(readPdfReviewSource(bytes)).resolves.toEqual({ encrypted: true }); + }); + it('refuses to write unencrypted annotation strings into an encrypted PDF', async () => { + await expect(exportReviewedPdf(await encryptedPdf(), { version: 1, fingerprint: '', annotations: [note()] })) + .rejects.toBeInstanceOf(PdfReviewEncryptedError); }); }); diff --git a/src/web-ui/src/tools/editor/pdf-review/pdfReview.ts b/src/web-ui/src/tools/editor/pdf-review/pdfReview.ts index ef75773474..4e2767b5d2 100644 --- a/src/web-ui/src/tools/editor/pdf-review/pdfReview.ts +++ b/src/web-ui/src/tools/editor/pdf-review/pdfReview.ts @@ -66,10 +66,29 @@ export async function pdfBytesHash(bytes: Uint8Array): Promise { return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join(''); } +/** pdf-lib can neither decrypt existing strings nor encrypt the objects it adds. */ +export class PdfReviewEncryptedError extends Error { + constructor() { + super('An annotated copy cannot be written into an encrypted PDF.'); + this.name = 'PdfReviewEncryptedError'; + } +} +export interface PdfReviewSource { + /** Viewing and sidecar notes still work; only annotated copies are unavailable. */ + encrypted: boolean; + embedded?: { data: PdfReviewData; bytes: Uint8Array }; +} +// Our exports are never encrypted. pdf-lib keeps the original /Encrypt entry when it +// saves, so readers would "decrypt" every string it adds into garbage. +async function loadPdf(bytes: Uint8Array) { + const lib = await import('pdf-lib'); + return { lib, pdf: await lib.PDFDocument.load(bytes, { ignoreEncryption: true }) }; +} + /** Write standard editable PDF annotations, including Unicode popup comments and replies. */ export async function exportReviewedPdf(base: Uint8Array, review: PdfReviewData): Promise { - const { PDFDocument, PDFName, PDFHexString } = await import('pdf-lib'); - const pdf = await PDFDocument.load(base); + const { lib: { PDFName, PDFHexString }, pdf } = await loadPdf(base); + if (pdf.isEncrypted) throw new PdfReviewEncryptedError(); const pages = pdf.getPages(); if (review.annotations.some(annotation => annotation.page > pages.length)) { throw new Error('Some review pages no longer exist. Reposition or remove those annotations before exporting.'); @@ -111,8 +130,8 @@ export async function exportReviewedPdf(base: Uint8Array, review: PdfReviewData) /** Embedded review state allows a saved PDF to reopen with editable threads. */ export async function readEmbeddedPdfReview(bytes: Uint8Array): Promise { - const { PDFDocument, PDFName, PDFHexString } = await import('pdf-lib'); - const pdf = await PDFDocument.load(bytes); + const { lib: { PDFName, PDFHexString }, pdf } = await loadPdf(bytes); + if (pdf.isEncrypted) return undefined; const value = pdf.catalog.get(PDFName.of('OpenBitFunReview')); if (value === undefined) return undefined; const text = pdf.context.lookup(value, PDFHexString).decodeText(); @@ -129,16 +148,19 @@ function removeOwnedAnnotations(pdf: import('pdf-lib').PDFDocument, PDFName: typ } } } -/** Remove our saved appearance before overlay editing, so deletes and recoloring are visible immediately. */ -export async function extractReviewedPdf(bytes: Uint8Array): Promise<{ data: PdfReviewData; bytes: Uint8Array } | undefined> { - const { PDFDocument, PDFName, PDFHexString } = await import('pdf-lib'); - const pdf = await PDFDocument.load(bytes); +/** + * Inspect an opened PDF once. An embedded review comes back with our saved appearances + * removed, so deletes and recoloring are visible immediately during overlay editing. + */ +export async function readPdfReviewSource(bytes: Uint8Array): Promise { + const { lib: { PDFName, PDFHexString }, pdf } = await loadPdf(bytes); + if (pdf.isEncrypted) return { encrypted: true }; const value = pdf.catalog.get(PDFName.of('OpenBitFunReview')); - if (value === undefined) return undefined; + if (value === undefined) return { encrypted: false }; const data = parsePdfReview(pdf.context.lookup(value, PDFHexString).decodeText()); removeOwnedAnnotations(pdf, PDFName); pdf.catalog.delete(PDFName.of('OpenBitFunReview')); - return { data, bytes: await pdf.save() }; + return { encrypted: false, embedded: { data, bytes: await pdf.save() } }; } export function encodePdfBytes(bytes: Uint8Array): string { let binary = '';