diff --git a/src/client/TextEditor.tsx b/src/client/TextEditor.tsx index f7633ead..c392efe8 100644 --- a/src/client/TextEditor.tsx +++ b/src/client/TextEditor.tsx @@ -36,7 +36,7 @@ import { rewriteLocalMarkdownLinks } from './markdown-navigation.ts' import { languageForPath } from './lang.ts' import { cmSurfaceTheme, CmThemeCompartment } from './cm-themes.ts' import { cmSearchExtensions, CmSearchPhrases } from './cm-search.ts' -import { clearDraftBackup, flushDraftBackups, readDraftBackup, registerDraftSource, scheduleDraftBackup } from './editor-draft-backup.ts' +import { clearDraftBackup, draftBackupBaseMtime, flushDraftBackups, readDraftBackup, registerDraftSource, scheduleDraftBackup } from './editor-draft-backup.ts' import { flashQuoteLines, quoteFlashField, quoteFlashHighlight } from './quote-flash.ts' import { isDarkScheme, subscribeColorScheme } from './theme.ts' import { SandboxStatusBar } from './SandboxStatusBar.tsx' @@ -176,13 +176,15 @@ export function TextEditor(props: FileViewerProps) { /** The mtime the draft is based on (`null` = the file did not exist yet). * Seeded from the load, re-based whenever a fresh load reports a new mtime * (a reload may return the SAME text — see the effect below), refreshed by - * every successful save, and reset by the file-switch effect. */ + * every successful save, reset by the file-switch effect, and moved back to + * a restored draft's own base (see restoreDraftBackup). */ const mtimeRef = useRef(props.mtimeMs ?? null) /** The bytes the save baseline belongs to: the last loaded document, * advanced by every successful save (an edit-mode save never reloads, so * `props.content` alone can lag behind disk). The conflict banner's reload * compares the disk read against THIS — never the live draft, which is - * expected to differ because it holds the unsaved edit. */ + * expected to differ because it holds the unsaved edit. `null` = not known: + * a restored draft based on an older revision, whose bytes are not kept. */ const savedTextRef = useRef(content ?? null) /** The theme compartment of the current view (reconfigured on scheme flip). */ const themeCompRef = useRef(null) @@ -364,6 +366,14 @@ export function TextEditor(props: FileViewerProps) { * quit can drop the tab without a prompt, so the draft is kept in storage. * Declining drops it; accepting makes it the live draft, which the normal * dirty path then owns. + * + * The draft was typed against the file as it was when the backup was written, + * not against the bytes just loaded. Accepting therefore also restores that + * base mtime, so a file that moved while the tab was gone is refused + * (fs-conflict) instead of overwritten. The baseline text goes with it: the + * banner's reload would otherwise find the disk equal to this load and resolve + * the conflict in place, as if only the mtime had moved. An entry without a + * base keeps the mtime of this load. */ const restoreDraftBackup = (): string | null => { if (content === undefined) return null @@ -374,6 +384,11 @@ export function TextEditor(props: FileViewerProps) { clearDraftBackup(scope.sessionId, path) return null } + const base = draftBackupBaseMtime(scope.sessionId, path) + if (base !== undefined && base !== mtimeRef.current) { + mtimeRef.current = base + savedTextRef.current = null + } return backup } @@ -487,7 +502,12 @@ export function TextEditor(props: FileViewerProps) { }) const view = new CodeMirrorView({ state, parent: host }) viewRef.current = view - const releaseDraft = registerDraftSource(scope.sessionId, path, () => viewRef.current?.state.doc.toString() ?? null) + const releaseDraft = registerDraftSource( + scope.sessionId, + path, + () => viewRef.current?.state.doc.toString() ?? null, + () => mtimeRef.current, + ) if (restored !== null) { setDirty(true) setDraft(restored) diff --git a/src/client/editor-draft-backup.ts b/src/client/editor-draft-backup.ts index 902ea67d..212b0582 100644 --- a/src/client/editor-draft-backup.ts +++ b/src/client/editor-draft-backup.ts @@ -53,6 +53,15 @@ interface StoredDraft { text: string /** Write time; the FIFO order for eviction. */ savedAt: number + /** The file's mtime the draft was typed against (the editor's save baseline). + * Absent when the editor had none, and on entries from before this field. */ + baseMtimeMs?: number +} + +/** One mounted editor's live readers (see {@link registerDraftSource}). */ +interface DraftSource { + read: () => string | null + readBase: (() => number | null) | undefined } /** @@ -60,7 +69,7 @@ interface StoredDraft { * Reading at flush time (rather than per keystroke) keeps the backup free of * the O(document) stringification the editor deliberately avoids on every key. */ -const sources = new Map string | null>() +const sources = new Map() /** Keys whose draft changed since the last write. */ const pending = new Set() let timer: ReturnType | null = null @@ -87,9 +96,9 @@ function readStored(key: string): StoredDraft | undefined { try { const parsed: unknown = JSON.parse(raw) if (typeof parsed !== 'object' || parsed === null) return undefined - const { text, savedAt } = parsed as { text?: unknown; savedAt?: unknown } + const { text, savedAt, baseMtimeMs } = parsed as { text?: unknown; savedAt?: unknown; baseMtimeMs?: unknown } if (typeof text !== 'string' || typeof savedAt !== 'number') return undefined - return { text, savedAt } + return typeof baseMtimeMs === 'number' ? { text, savedAt, baseMtimeMs } : { text, savedAt } } catch { return undefined } @@ -121,7 +130,7 @@ function evict(store: Storage): void { } /** Persist one draft, dropping older ones when storage is full. */ -function writeDraft(key: string, text: string): void { +function writeDraft(key: string, text: string, baseMtimeMs: number | undefined): void { const store = storage() if (store === undefined) return if (text.length === 0 || text.length > DRAFT_BACKUP_CHARS) return @@ -129,7 +138,7 @@ function writeDraft(key: string, text: string): void { // An unchanged draft keeps its original timestamp (and therefore its place // in the FIFO order), so a restore that is re-persisted does not look new. if (previous?.text === text) return - const payload = JSON.stringify({ text, savedAt: Date.now() } satisfies StoredDraft) + const payload = JSON.stringify({ text, savedAt: Date.now(), baseMtimeMs } satisfies StoredDraft) try { store.setItem(STORAGE_PREFIX + key, payload) } catch { @@ -154,8 +163,9 @@ export function flushDraftBackups(): void { const keys = [...pending] pending.clear() for (const key of keys) { - const text = sources.get(key)?.() - if (text !== null && text !== undefined) writeDraft(key, text) + const source = sources.get(key) + const text = source?.read() + if (text !== null && text !== undefined) writeDraft(key, text, source?.readBase?.() ?? undefined) } } @@ -167,17 +177,24 @@ export function flushDraftBackups(): void { * @param sessionId - the session owning the tab. * @param path - the file the draft belongs to. * @param read - the live document's text, or null. + * @param readBase - the mtime the live document is based on, stored with the draft. * @returns the disposer (idempotent; a newer source for the same file wins). */ -export function registerDraftSource(sessionId: string, path: string, read: () => string | null): () => void { +export function registerDraftSource( + sessionId: string, + path: string, + read: () => string | null, + readBase?: () => number | null, +): () => void { const key = keyOf(sessionId, path) - sources.set(key, read) + const source: DraftSource = { read, readBase } + sources.set(key, source) if (sources.size > SOURCE_LIMIT) { const oldest = sources.keys().next().value if (oldest !== undefined && oldest !== key) sources.delete(oldest) } return () => { - if (sources.get(key) === read) sources.delete(key) + if (sources.get(key) === source) sources.delete(key) } } @@ -216,6 +233,16 @@ export function readDraftBackup(sessionId: string, path: string, content: string return entry.text } +/** + * The mtime one file's stored draft was typed against. + * @param sessionId - the session owning the tab. + * @param path - the file the draft belongs to. + * @returns the baseline, or undefined when the entry carries none. + */ +export function draftBackupBaseMtime(sessionId: string, path: string): number | undefined { + return readStored(keyOf(sessionId, path))?.baseMtimeMs +} + /** Drop one file's backup (saved, discarded, or restored). Idempotent. */ export function clearDraftBackup(sessionId: string, path: string): void { const key = keyOf(sessionId, path) diff --git a/tests/editor-draft-backup.spec.tsx b/tests/editor-draft-backup.spec.tsx index 04b3bf92..9ed29473 100644 --- a/tests/editor-draft-backup.spec.tsx +++ b/tests/editor-draft-backup.spec.tsx @@ -16,7 +16,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createElement } from 'react' import { act } from 'react-dom/test-utils' +import { EditorView } from '@codemirror/view' import { renderRoot, setupReactAct } from './test-utils.ts' +import { SidebarApiError } from '../src/client/api.ts' import { TextEditor } from '../src/client/TextEditor.tsx' import { createSidebarStore } from '../src/client/state.ts' import type { FileViewerProps } from '../src/client/service.ts' @@ -27,6 +29,7 @@ import { DRAFT_BACKUP_CHARS, DRAFT_BACKUP_LIMIT, DRAFT_BACKUP_THROTTLE_MS, + draftBackupBaseMtime, flushDraftBackups, readDraftBackup, registerDraftSource, @@ -36,11 +39,16 @@ import { setupReactAct() const fsWrite = vi.fn() +const fsRead = vi.fn() vi.mock('../src/client/api.ts', async (importOriginal) => { const actual = await importOriginal() return { ...actual, - api: { ...actual.api, fsWrite: (...args: unknown[]) => fsWrite(...args) }, + api: { + ...actual.api, + fsWrite: (...args: unknown[]) => fsWrite(...args), + fsRead: (...args: unknown[]) => fsRead(...args), + }, } }) @@ -77,10 +85,43 @@ function click(element: HTMLElement): void { act(() => { element.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) } +/** The editor's live CodeMirror view (the real document, draft included). */ +function viewOf(container: HTMLElement): EditorView { + const host = container.querySelector('.cm-editor') + const view = host === null ? null : EditorView.findFromDOM(host as HTMLElement) + if (view === null) throw new Error('the mounted editor has no CodeMirror view') + return view +} + +/** Type through CodeMirror's own doc-change path (a keystroke). */ +function typeText(container: HTMLElement, text: string): void { + act(() => { viewOf(container).dispatch({ changes: { from: 0, insert: text } }) }) +} + +function reloadButton(container: HTMLElement): HTMLButtonElement { + const button = Array.from(container.querySelectorAll('button')) + .find(candidate => candidate.textContent === 'Reload from disk') + if (button === undefined) throw new Error('the conflict banner has no reload button') + return button as HTMLButtonElement +} + +async function settle(): Promise { + await act(async () => { await Promise.resolve() }) + await act(async () => { await Promise.resolve() }) +} + +/** A body at revision 1000 that gets an edit, then goes away without a save. */ +function leaveDraftAt1000(): void { + const mounted = renderRoot(createElement(TextEditor, viewerProps({ content: 'base\n', mtimeMs: 1000 }))) + typeText(mounted.container, 'draft ') + mounted.unmount() +} + beforeEach(() => { localStorage.clear() fsWrite.mockReset() fsWrite.mockResolvedValue({ ok: true, mtimeMs: 456 }) + fsRead.mockReset() }) afterEach(() => { @@ -143,6 +184,17 @@ describe('editor-draft-backup store', () => { expect(readDraftBackup('s1', '/p/a.ts', 'same as disk')).toBeNull() expect(storedKeys()).toHaveLength(0) }) + + it('stores the base mtime with the draft, and reads a malformed one as absent', () => { + const release = registerDraftSource('s1', '/p/a.ts', () => 'typed', () => 1000) + scheduleDraftBackup('s1', '/p/a.ts') + flushDraftBackups() + release() + expect(draftBackupBaseMtime('s1', '/p/a.ts')).toBe(1000) + localStorage.setItem('dsh-better-sidebar:draft:s1::/p/a.ts', JSON.stringify({ text: 'typed', savedAt: 1, baseMtimeMs: 'x' })) + expect(draftBackupBaseMtime('s1', '/p/a.ts')).toBeUndefined() + expect(readDraftBackup('s1', '/p/a.ts', 'disk'), 'the draft itself is still offered').toBe('typed') + }) }) describe('TextEditor draft restore', () => { @@ -193,6 +245,109 @@ describe('TextEditor draft restore', () => { }) }) +describe('TextEditor draft restore: the mtime the draft was typed against', () => { + /** The newer revision a reopen loads: another writer moved the file on. */ + const newer = { content: 'rewritten elsewhere\n', mtimeMs: 2000 } + const refusedByHost = new SidebarApiError('fs-conflict', 'changed on disk') + + beforeEach(() => { + vi.stubGlobal('confirm', vi.fn().mockReturnValue(true)) + }) + + it('saves a restored draft against its own base, not the mtime just loaded', async () => { + leaveDraftAt1000() + const mounted = renderRoot(createElement(TextEditor, viewerProps(newer))) + try { + click(saveButton(mounted.container)) + await settle() + expect(fsWrite).toHaveBeenCalledTimes(1) + expect(fsWrite.mock.calls[0]![2]).toBe('draft base\n') + expect(fsWrite.mock.calls[0]![3]).toBe(1000) + } finally { + mounted.unmount() + } + }) + + it('takes the conflict path when the host refuses it: the draft stays, and the banner does not resolve in place', async () => { + // The host's own rule: only the file's current mtime passes. + fsWrite.mockImplementation((_scope: unknown, _path: unknown, _text: unknown, expected: unknown) => ( + expected === newer.mtimeMs ? Promise.resolve({ ok: true, mtimeMs: 3000 }) : Promise.reject(refusedByHost) + )) + // The disk equals what this mount loaded, which is exactly what must not + // read as "only the mtime moved": the draft was typed on other bytes. + fsRead.mockResolvedValue({ kind: 'text', content: newer.content, size: newer.content.length, mtimeMs: newer.mtimeMs }) + leaveDraftAt1000() + const onReload = vi.fn() + const mounted = renderRoot(createElement(TextEditor, viewerProps({ ...newer, onReload }))) + try { + click(saveButton(mounted.container)) + await settle() + expect(mounted.container.textContent ?? '').toContain('changed on disk since it was loaded') + expect(viewOf(mounted.container).state.doc.toString()).toBe('draft base\n') + expect(readDraftBackup('s1', '/p/a.ts', newer.content), 'a refused save keeps the backup').toBe('draft base\n') + click(reloadButton(mounted.container)) + await settle() + expect(onReload, 'the reload defers to the host and its unsaved-edits guard').toHaveBeenCalledTimes(1) + click(saveButton(mounted.container)) + await settle() + expect(fsWrite.mock.calls[1]![3], 'the probe did not move the baseline').toBe(1000) + } finally { + mounted.unmount() + } + }) + + it('keeps the original base across further edits of a restored draft', async () => { + leaveDraftAt1000() + const edited = renderRoot(createElement(TextEditor, viewerProps(newer))) + typeText(edited.container, 'more ') + edited.unmount() + const mounted = renderRoot(createElement(TextEditor, viewerProps(newer))) + try { + click(saveButton(mounted.container)) + await settle() + expect(fsWrite.mock.calls[0]![2]).toBe('more draft base\n') + expect(fsWrite.mock.calls[0]![3]).toBe(1000) + } finally { + mounted.unmount() + } + }) + + it('treats an entry without a base as before: the save carries the mtime just loaded', async () => { + localStorage.setItem('dsh-better-sidebar:draft:s1::/p/a.ts', JSON.stringify({ text: 'older entry\n', savedAt: 1 })) + const mounted = renderRoot(createElement(TextEditor, viewerProps(newer))) + try { + click(saveButton(mounted.container)) + await settle() + expect(fsWrite.mock.calls[0]![2]).toBe('older entry\n') + expect(fsWrite.mock.calls[0]![3]).toBe(newer.mtimeMs) + } finally { + mounted.unmount() + } + }) + + it('leaves a draft whose file did not move on the normal path: a touch still resolves in place (#1059)', async () => { + leaveDraftAt1000() + const onReload = vi.fn() + const mounted = renderRoot(createElement(TextEditor, viewerProps({ content: 'base\n', mtimeMs: 1000, onReload }))) + try { + fsWrite.mockRejectedValueOnce(refusedByHost) + click(saveButton(mounted.container)) + await settle() + expect(fsWrite.mock.calls[0]![3]).toBe(1000) + fsRead.mockResolvedValue({ kind: 'text', content: 'base\n', size: 5, mtimeMs: 3000 }) + click(reloadButton(mounted.container)) + await settle() + expect(onReload).not.toHaveBeenCalled() + expect(mounted.container.textContent ?? '').not.toContain('changed on disk since it was loaded') + click(saveButton(mounted.container)) + await settle() + expect(fsWrite.mock.calls[1]![3]).toBe(3000) + } finally { + mounted.unmount() + } + }) +}) + describe('native tab close', () => { it('flushes a pending draft through the host close hook before the body unmounts', () => { vi.useFakeTimers()