From 0dfee1dd8413649c797e89a752a7a58527f71e19 Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Mon, 26 Oct 2026 15:17:32 +0800 Subject: [PATCH 1/2] =?UTF-8?q?test(editor):=20=E8=A6=86=E7=9B=96=E4=BB=85?= =?UTF-8?q?=20mtime=20=E5=8F=98=E5=8C=96=E7=9A=84=E9=87=8D=E6=96=B0?= =?UTF-8?q?=E8=BD=BD=E5=85=A5=E4=BF=9D=E5=AD=98=E5=9F=BA=E7=BA=BF=EF=BC=88?= =?UTF-8?q?#1059=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 两个判别性用例: - TextEditor 同实例收到新 mtimeMs、content 不变时,保存必须发送新基线; - 冲突横幅重载:dirty + 仅 mtime 变化 + confirm=false 时就地更新基线并保留草稿; 磁盘文本确实变化时脏保护仍然生效。 修复前第一个文件的首例失败(100 vs 200),第二个文件的首例失败 (confirm 被调用、横幅不清除)。 --- tests/editor-conflict-reload.spec.tsx | 201 +++++++++++++++++++++++ tests/text-editor-save-baseline.spec.tsx | 163 ++++++++++++++++++ 2 files changed, 364 insertions(+) create mode 100644 tests/editor-conflict-reload.spec.tsx create mode 100644 tests/text-editor-save-baseline.spec.tsx diff --git a/tests/editor-conflict-reload.spec.tsx b/tests/editor-conflict-reload.spec.tsx new file mode 100644 index 00000000..d992f6dc --- /dev/null +++ b/tests/editor-conflict-reload.spec.tsx @@ -0,0 +1,201 @@ +/** + * "Reload from disk" after a save conflict, with the host's dirty guard in + * play (#1059). Opening a file, editing it, and then touching the file (same + * bytes, new mtime) makes the next save fail with `fs-conflict`; the banner + * promises a way out. The host's reload route stops first at `window.confirm` + * whenever the draft is dirty, and some desktop shells answer that dialog with + * no UI at all (`false`) — so a reload that would only carry a new mtime must + * NOT need the confirm: it is resolved in place, baseline updated, draft kept. + * + * Real disk edits keep the old dirty protection: when the reload returns a + * different document the host's confirm still decides, and a declined confirm + * replaces nothing. + * + * The comparison is against the bytes the editor was LOADED from, not the live + * draft: after the user's edit the draft legitimately differs from disk, and + * comparing against it would classify every touch-only reload as "changed". + */ +// @vitest-environment jsdom +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 type { Context } from '../src/context-types.ts' +import { EditorHost } from '../src/client/EditorHost.tsx' +import { TextEditor } from '../src/client/TextEditor.tsx' +import { allLeaves, createSidebarStore, type SidebarTab } from '../src/client/state.ts' +import { createBetterSidebarService, type FileViewerProps } from '../src/client/service.ts' + +setupReactAct() + +vi.mock('../src/client/api.ts', async (importOriginal) => { + // Keep the real module: TextEditor narrows the save failure with + // instanceof SidebarApiError. + const actual = await importOriginal() + return { + ...actual, + api: { ...actual.api, fsRead: vi.fn(), fsWrite: vi.fn() }, + } +}) +import { SidebarApiError, api } from '../src/client/api.ts' + +const fsRead = vi.mocked(api.fsRead) +const fsWrite = vi.mocked(api.fsWrite) + +const CONTENT = 'const a = 1\n' +/** The user's unsaved edit (what the reload must NOT throw away). */ +const DRAFT_PREFIX = '// draft\n' +const CHANGED_CONTENT = 'const a = 2\n' + +const readText = (content: string, mtimeMs: number): { kind: 'text'; content: string; size: number; mtimeMs: number } => + ({ kind: 'text', content, size: content.length, mtimeMs }) + +interface Harness { + container: HTMLDivElement + unmount: () => void +} + +function setup(): { ctx: Context; store: ReturnType; tab: () => SidebarTab } { + const store = createSidebarStore() + const service = createBetterSidebarService(store) + service.registerTab({ id: 'editor', title: 'Editor', dedupeKey: (tab) => tab.path, component: () => null }) + service.registerFileViewer({ + id: 'code', + exts: ['ts'], + priority: 0, + fetchStrategy: 'fsRead', + component: (props: FileViewerProps) => createElement(TextEditor, props), + }) + store.setSession('s1') + const ctx = { + betterSidebar: service, + sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({ byId: { s1: { cwd: '/p' } }, current: 's1' }) } }, + get: (name: string) => name === 'betterSidebar' ? service : undefined, + } as unknown as Context + ctx.betterSidebar.openTab({ type: 'editor', title: 'a.ts', path: '/p/a.ts', id: 'editor:/p/a.ts' }) + const tab = (): SidebarTab => allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs) + .find(candidate => candidate.path === '/p/a.ts')! + return { ctx, store, tab } +} + +function mount(): Harness { + const { ctx, store, tab } = setup() + const root = renderRoot(createElement(EditorHost, { + ctx, + store: store as never, + scope: { sessionId: 's1' }, + tab: tab(), + expanded: [], + revealed: [], + onToggleDir: () => {}, + onReferenceFile: () => {}, + })) + return { container: root.container, unmount: root.unmount } +} + +/** The editor's live CodeMirror view (the real document, draft included). */ +function viewOf(container: HTMLElement): EditorView { + const host = container.querySelector('.cm-editor') + if (host === null) throw new Error('the mounted editor has no .cm-editor') + const view = EditorView.findFromDOM(host as HTMLElement) + if (view === null) throw new Error('the mounted editor has no CodeMirror view') + return view +} + +/** Type the user's edit through CodeMirror's own doc-change path. */ +function typeDraft(container: HTMLElement): void { + act(() => { + viewOf(container).dispatch({ changes: { from: 0, insert: DRAFT_PREFIX } }) + }) +} + +function click(element: Element): void { + act(() => { element.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) +} + +/** Save once and assert the host refused it as a conflict. */ +async function saveIntoConflict(container: HTMLElement): Promise { + fsWrite.mockRejectedValueOnce(new SidebarApiError('fs-conflict', 'changed on disk')) + click(container.querySelector('button[aria-label="Save"]')!) + await settle() + expect(container.textContent ?? '').toContain('changed on disk since it was loaded') +} + +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() }) +} + +beforeEach(() => { + fsRead.mockReset() + fsWrite.mockReset() + fsWrite.mockResolvedValue({ ok: true, mtimeMs: 300 }) + fsRead.mockImplementation(() => Promise.resolve(readText(CONTENT, 100))) +}) + +afterEach(() => { + vi.restoreAllMocks() + document.body.innerHTML = '' +}) + +describe('save-conflict banner: reload with a dirty draft (#1059)', () => { + it('adopts a touch-only reload in place: no confirm, draft kept, next save uses the new mtime', async () => { + const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false) + const { container, unmount } = mount() + try { + await settle() + typeDraft(container) + await saveIntoConflict(container) + const before = viewOf(container) + expect(before.state.doc.toString()).toBe(`${DRAFT_PREFIX}${CONTENT}`) + // Disk still holds the loaded bytes; only the mtime moved. + fsRead.mockImplementation(() => Promise.resolve(readText(CONTENT, 200))) + click(reloadButton(container)) + await settle() + // No dirty-confirm was asked, the banner cleared, and the draft is intact. + expect(confirm).not.toHaveBeenCalled() + expect(container.textContent ?? '').not.toContain('changed on disk since it was loaded') + expect(viewOf(container), 'the same editor instance stays mounted').toBe(before) + expect(viewOf(container).state.doc.toString()).toBe(`${DRAFT_PREFIX}${CONTENT}`) + // The next save carries the fresh baseline (200) and is accepted. + click(container.querySelector('button[aria-label="Save"]')!) + await settle() + expect(fsWrite).toHaveBeenCalledTimes(2) + expect(fsWrite.mock.calls[1]![2]).toBe(`${DRAFT_PREFIX}${CONTENT}`) + expect(fsWrite.mock.calls[1]![3]).toBe(200) + } finally { + unmount() + } + }) + + it('still protects a dirty draft when the reloaded bytes really changed', async () => { + const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false) + const { container, unmount } = mount() + try { + await settle() + typeDraft(container) + await saveIntoConflict(container) + const before = viewOf(container) + // The file was really rewritten, not merely touched. + fsRead.mockImplementation(() => Promise.resolve(readText(CHANGED_CONTENT, 200))) + click(reloadButton(container)) + await settle() + // The host's dirty guard still applies: a declined confirm replaces + // nothing, and the conflict banner stays up. + expect(confirm).toHaveBeenCalledTimes(1) + expect(viewOf(container), 'no remount on a declined reload').toBe(before) + expect(viewOf(container).state.doc.toString()).toBe(`${DRAFT_PREFIX}${CONTENT}`) + expect(container.textContent ?? '').toContain('changed on disk since it was loaded') + } finally { + unmount() + } + }) +}) diff --git a/tests/text-editor-save-baseline.spec.tsx b/tests/text-editor-save-baseline.spec.tsx new file mode 100644 index 00000000..53d4e88b --- /dev/null +++ b/tests/text-editor-save-baseline.spec.tsx @@ -0,0 +1,163 @@ +/** + * The text editor's save baseline (#1059). `mtimeRef` is the optimistic- + * concurrency baseline the editor sends as `expectedMtimeMs`; the host refuses + * the save (`fs-conflict`) when the file on disk no longer matches it. + * + * A fresh load can return the SAME bytes with a NEW mtime — `touch`, a + * `git checkout`, a formatter rewriting identical text — and then `content` + * never changes, so the file-switch effect keyed on it never runs. The + * baseline must therefore ALSO follow the `mtimeMs` prop, or every later save + * keeps sending the stale value and the conflict never clears. + * + * The second case pins the other side of the contract: a genuinely different + * document must still run the original file-switch reset (preview mode, no + * draft, clean editor, conflict cleared, new baseline) unchanged. + */ +// @vitest-environment jsdom +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 { TextEditor } from '../src/client/TextEditor.tsx' +import { createSidebarStore } from '../src/client/state.ts' +import type { EditorToolbarControls, EditorToolbarState, FileViewerProps } from '../src/client/service.ts' + +setupReactAct() + +const fsWrite = vi.fn() +vi.mock('../src/client/api.ts', async (importOriginal) => { + // Keep the real module (the api surface and the error class); only the save + // call is observed. + const actual = await importOriginal() + return { + ...actual, + api: { ...actual.api, fsWrite: (...args: unknown[]) => fsWrite(...args) }, + } +}) + +const CONTENT = 'const a = 1\n' +const NEXT_CONTENT = 'const a = 2\n' + +function viewerProps(overrides: Partial = {}): FileViewerProps { + return { + ctx: {} as FileViewerProps['ctx'], + store: createSidebarStore(), + scope: { sessionId: 's1', cwd: '/p' }, + path: '/p/a.ts', + title: 'a.ts', + viewerId: 'code', + content: CONTENT, + mtimeMs: 100, + // The real editor's deployment: the host header owns the toolbar, so the + // save/mode commands arrive through the registered controls. + toolbar: 'host', + ...overrides, + } +} + +interface Harness { + container: HTMLDivElement + /** Re-render the SAME instance with the next load (a reload / file swap). */ + rerender: (next: Partial) => void + /** The last toolbar state the editor reported. */ + state: () => EditorToolbarState + /** The toolbar commands the editor registered on mount. */ + controls: () => EditorToolbarControls + /** The live CodeMirror view. */ + view: () => EditorView + unmount: () => void +} + +function mountEditor(overrides: Partial = {}): Harness { + const props = viewerProps(overrides) + let toolbar: EditorToolbarState | undefined + let controls: EditorToolbarControls | null = null + const element = (next: Partial = {}): ReturnType => + createElement(TextEditor, { + ...props, + ...next, + onToolbarState: (state: EditorToolbarState) => { toolbar = state }, + onToolbarControls: (nextControls: EditorToolbarControls | null) => { controls = nextControls }, + }) + const root = renderRoot(element()) + const view = (): EditorView => { + const host = root.container.querySelector('.cm-editor') + if (host === null) throw new Error('the mounted editor has no .cm-editor') + const live = EditorView.findFromDOM(host as HTMLElement) + if (live === null) throw new Error('the mounted editor has no CodeMirror view') + return live + } + return { + container: root.container, + rerender: (next: Partial) => { root.rerender(element(next)) }, + state: () => { + if (toolbar === undefined) throw new Error('the editor reported no toolbar state') + return toolbar + }, + controls: () => { + if (controls === null) throw new Error('the editor registered no toolbar controls') + return controls + }, + view, + unmount: root.unmount, + } +} + +/** Apply the CodeMirror transaction a keystroke would (same doc-change path). */ +function type(view: EditorView, insert: string): void { + act(() => { view.dispatch({ changes: { from: 0, insert } }) }) +} + +beforeEach(() => { + fsWrite.mockReset() + fsWrite.mockResolvedValue({ ok: true, mtimeMs: 999 }) +}) + +afterEach(() => { + document.body.innerHTML = '' +}) + +describe('TextEditor save baseline (#1059)', () => { + it('follows a fresh load of unchanged text, not just a content change', async () => { + const editor = mountEditor() + try { + const mounted = editor.view() + // The reported reload: same bytes on disk, new mtime. `content` is + // unchanged, so the file-switch effect must not be what re-bases the ref. + editor.rerender({ content: CONTENT, mtimeMs: 200 }) + expect(editor.view(), 'the same viewer instance stays mounted').toBe(mounted) + type(editor.view(), '// touched\n') + expect(editor.state().dirty).toBe(true) + await act(async () => { editor.controls().save() }) + await act(async () => { await Promise.resolve() }) + expect(fsWrite).toHaveBeenCalledTimes(1) + // (scope, path, content, expectedMtimeMs) — the fresh load's mtime. + expect(fsWrite.mock.calls[0]![3]).toBe(200) + } finally { + editor.unmount() + } + }) + + it('still performs the file-switch reset when the content really changes', async () => { + const editor = mountEditor({ viewerId: 'markdown', path: '/p/a.md', title: 'a.md' }) + try { + expect(editor.state()).toMatchObject({ mode: 'preview', dirty: false, saveState: 'idle' }) + act(() => { editor.controls().setMode('edit') }) + expect(editor.state().mode).toBe('edit') + type(editor.view(), '# draft\n') + expect(editor.state().dirty).toBe(true) + // A genuinely different document: the original [content] reset runs. + editor.rerender({ content: NEXT_CONTENT, mtimeMs: 400 }) + expect(editor.view().state.doc.toString()).toBe(NEXT_CONTENT) + expect(editor.state()).toMatchObject({ mode: 'preview', dirty: false, saveState: 'idle' }) + await act(async () => { editor.controls().save() }) + await act(async () => { await Promise.resolve() }) + expect(fsWrite).toHaveBeenCalledTimes(1) + expect(fsWrite.mock.calls[0]![2]).toBe(NEXT_CONTENT) + expect(fsWrite.mock.calls[0]![3]).toBe(400) + } finally { + editor.unmount() + } + }) +}) From 44007061bb209638a2812e0e93dd4fe83cfd29a3 Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Mon, 26 Oct 2026 15:17:35 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix(editor):=20=E9=87=8D=E6=96=B0=E8=BD=BD?= =?UTF-8?q?=E5=85=A5=E5=90=8E=E4=B8=8D=E5=86=8D=E6=AD=BB=E9=94=81=E5=9C=A8?= =?UTF-8?q?=20fs-conflict=EF=BC=88#1059=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根因:保存基线 mtimeRef 只在 [content] effect 里刷新;重新载入返回同样 文本时 content 不变,effect 不跑,下一次保存继续发送旧 expectedMtimeMs。 修复: - props.mtimeMs 变化时也更新 mtimeRef(只动基线,模式/草稿/脏标记的 文件切换重置语义保持不动); - 冲突横幅「Reload from disk」先探测磁盘文本:与上次载入/保存的字节 一致时说明只有 mtime 变了,就地采用新基线、保留草稿、不经过脏确认; 文本确实变化时才交回宿主的带确认重载(脏保护不变); - 记录最近一次成功保存的文本作为比较点:编辑态保存不会重新载入,单靠 props.content 会滞后于磁盘。 tests/text-editor-conflict.spec.tsx 的横幅回调断言跟随异步探测调整: 探测失败时仍在下一微任务回落宿主重载。 --- CHANGELOG.md | 1 + src/client/TextEditor.tsx | 60 ++++++++++++++++-- tests/editor-conflict-reload.spec.tsx | 89 +++++++++++++++++++++++---- tests/text-editor-conflict.spec.tsx | 21 ++++++- 4 files changed, 152 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b579d80..4597863b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### 未发布 +- 🐞 **重新载入后保存不再死锁在 `fs-conflict`**([#1059](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1059)):文件内容没变、只有修改时间变了(`touch` / `git checkout` / 格式化工具)时,编辑器的保存基线只在内容变化时刷新,重新载入拿到同样的文本后仍发送旧 `expectedMtimeMs`,宿主持续拒绝保存。现在:① 保存基线也跟随每次重新载入的 `mtimeMs` 更新;②「Reload from disk」发现磁盘文本与载入内容一致时**就地更新基线并保留草稿**,不再经过会丢草稿的脏确认,只有文本确实变化时才走原来的脏保护重载。真正的文件切换仍走原来的模式 / 草稿 / 脏标记重置。`tests/text-editor-save-baseline.spec.tsx` + `tests/editor-conflict-reload.spec.tsx` 守护。 - ⚡ **页签内容不再因无关重渲染而重读整份文件**:页签 body 拿到的 `scope` 对象此前每次渲染都新建,而编辑器、差异预览、侧聊都拿它当记忆化/副作用的依赖;只要某个**被比较的字段**变了(在文件树里展开目录走 `expanded`,以及 `revealed`、语言切换、页签注册表更新),差异预览就会重跑全文改写、「内容」页重新读取整份文件并闪一下加载态。现在 `scope` 由 `useSessionScope` 按会话与 cwd 缓存,页签内容、差异页签、以及徽标 / 右侧动作区 / `+` 菜单的注册表接口共用同一份稳定对象(后三者是对外部插件公开的接口,插件对 `scope` 做记忆化不再逐渲染失效)。差异预览「内容」页的刷新改由表头刷新按钮驱动——它此前只靠这种副作用顺带刷新,改稳之后会失去刷新路径。 - **Markdown 链接里的 Windows 反斜杠**:`[x](C:\ws\_analysis\r.md)` 的 `\_` 被 Markdown 当作转义,路径少一个分隔符(变成 `C:\ws_analysis\r.md`),点击后 `ENOENT`。源代码改写现在把本地 destination 的反斜杠统一成正斜杠(Windows 两种写法都接受),UNC 前缀保持 `\\`,避免被解析成协议相对的 `//host/share`。修复 #1037。 - **右栏展开时仍可开关底部工作台**:会话头的底部工作台开关此前在宿主右侧面板展开时整枚隐藏,导致「先开右栏就再也打不开工作台」,必须先收起右栏。现在照常显示(它在会话头 utilities,与右栏那簇控件分属两列,不会重叠)。空白会话的 fixed 兜底入口保持原行为:那个入口锚在右栏控件左侧,展开时锚点落在面板内部。`tests/bottom-toggle.spec.tsx` 守护。 diff --git a/src/client/TextEditor.tsx b/src/client/TextEditor.tsx index 3fd71211..d398bf96 100644 --- a/src/client/TextEditor.tsx +++ b/src/client/TextEditor.tsx @@ -140,9 +140,16 @@ export function TextEditor(props: FileViewerProps) { const viewRef = useRef(null) const savingRef = useRef(false) /** The mtime the draft is based on (`null` = the file did not exist yet). - * Seeded from the load, refreshed by every successful save, and reset by - * the file-switch effect. */ + * 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. */ 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. */ + const savedTextRef = useRef(content ?? null) /** The theme compartment of the current view (reconfigured on scheme flip). */ const themeCompRef = useRef(null) /** The search-phrases compartment of the current view (reconfigured on a @@ -288,12 +295,24 @@ export function TextEditor(props: FileViewerProps) { setConflict(false) // The freshly loaded bytes are the new save baseline. mtimeRef.current = props.mtimeMs ?? null + savedTextRef.current = content ?? null selectionPopup.hide() // hide() reads a live ref; the reset must fire only on a content (file) // swap, and the hook object's identity churns on every render. // eslint-disable-next-line react-hooks/exhaustive-deps }, [content]) + // The save baseline follows every fresh load, not only a content swap: a + // reload can return the SAME bytes with a new mtime (`touch`, `git checkout`, + // a formatter rewriting identical text). `content` then never changes and + // the file-switch effect above never runs, so the stale baseline would keep + // being sent and the host would answer `fs-conflict` forever (#1059). + // Baseline only: the mode/draft/dirty reset above stays tied to a new + // document, not to a re-read of the same one. + useEffect(() => { + mtimeRef.current = props.mtimeMs ?? null + }, [props.mtimeMs]) + // A different file switches the remembered preview scroll position to that // file's own entry (first open: none, so the preview starts at the top). useEffect(() => { @@ -697,17 +716,21 @@ export function TextEditor(props: FileViewerProps) { const save = (): void => { const view = viewRef.current if (view === null || savingRef.current) return + // The bytes this request writes: the same string becomes the baseline text + // once the host accepts it (the draft may keep changing while in flight). + const text = view.state.doc.toString() savingRef.current = true setSaveState('saving') // Optimistic concurrency: the draft was based on the bytes read at // `mtimeMs`; a file that changed on disk since is REFUSED (fs-conflict) // instead of clobbering whatever wrote it (the model, another tab, an // external editor). `null` = the file did not exist when loaded. - api.fsWrite(scope, path, view.state.doc.toString(), mtimeRef.current ?? null).then((result) => { + api.fsWrite(scope, path, text, mtimeRef.current ?? null).then((result) => { savingRef.current = false // Adopt the fresh baseline the host reports (absent on a stat failure — // keep the old one, the next save just re-checks). if (typeof result.mtimeMs === 'number') mtimeRef.current = result.mtimeMs + savedTextRef.current = text setDraft(null) setDirty(false) setConflict(false) @@ -727,6 +750,35 @@ export function TextEditor(props: FileViewerProps) { }) } + /** + * The conflict banner's "Reload from disk". A reload whose bytes equal the + * ones the save baseline was taken from carries no content change — only a + * new mtime — so it is resolved IN PLACE: adopt the fresh baseline and keep + * the draft (see {@link savedTextRef}: the live draft legitimately differs, + * it holds the unsaved edit). + * No dirty-confirm is involved: it would ask to discard edits that are not + * discarded (and a shell that cannot surface that dialog treats it as a + * decline), which used to turn a touch-only change into an endless + * fs-conflict loop (#1059). A genuinely different document still defers to + * the host's explicit reload, its unsaved-edits guard included. + */ + const reloadAfterConflict = (): void => { + const baseline = savedTextRef.current + api.fsRead(scope, path).then((result) => { + if (result.kind !== 'text' || baseline === null || !sameDocument(result.content, baseline)) { + props.onReload?.() + return + } + // Same bytes on disk as the last load/save: only the baseline moved. + mtimeRef.current = result.mtimeMs ?? null + setConflict(false) + }).catch(() => { + // A failed probe must not swallow the user's explicit reload: the host + // owns the error surface (unreadable file, dead session). + props.onReload?.() + }) + } + /** The markdown source the preview renders (draft wins over saved content). */ const mdText = draft ?? content ?? '' /** Preview-only source with a closed leading YAML frontmatter block hidden. @@ -959,7 +1011,7 @@ export function TextEditor(props: FileViewerProps) { diff --git a/tests/editor-conflict-reload.spec.tsx b/tests/editor-conflict-reload.spec.tsx index d992f6dc..062d3bfe 100644 --- a/tests/editor-conflict-reload.spec.tsx +++ b/tests/editor-conflict-reload.spec.tsx @@ -46,8 +46,18 @@ const fsWrite = vi.mocked(api.fsWrite) const CONTENT = 'const a = 1\n' /** The user's unsaved edit (what the reload must NOT throw away). */ const DRAFT_PREFIX = '// draft\n' +const SECOND_PREFIX = '// second\n' const CHANGED_CONTENT = 'const a = 2\n' +interface ViewerSpec { + id: string + ext: string + path: string +} + +const CODE_VIEWER: ViewerSpec = { id: 'code', ext: 'ts', path: '/p/a.ts' } +const MARKDOWN_VIEWER: ViewerSpec = { id: 'markdown', ext: 'md', path: '/p/a.md' } + const readText = (content: string, mtimeMs: number): { kind: 'text'; content: string; size: number; mtimeMs: number } => ({ kind: 'text', content, size: content.length, mtimeMs }) @@ -56,13 +66,13 @@ interface Harness { unmount: () => void } -function setup(): { ctx: Context; store: ReturnType; tab: () => SidebarTab } { +function setup(viewer: ViewerSpec = CODE_VIEWER): { ctx: Context; store: ReturnType; tab: () => SidebarTab } { const store = createSidebarStore() const service = createBetterSidebarService(store) service.registerTab({ id: 'editor', title: 'Editor', dedupeKey: (tab) => tab.path, component: () => null }) service.registerFileViewer({ - id: 'code', - exts: ['ts'], + id: viewer.id, + exts: [viewer.ext], priority: 0, fetchStrategy: 'fsRead', component: (props: FileViewerProps) => createElement(TextEditor, props), @@ -73,14 +83,14 @@ function setup(): { ctx: Context; store: ReturnType; sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({ byId: { s1: { cwd: '/p' } }, current: 's1' }) } }, get: (name: string) => name === 'betterSidebar' ? service : undefined, } as unknown as Context - ctx.betterSidebar.openTab({ type: 'editor', title: 'a.ts', path: '/p/a.ts', id: 'editor:/p/a.ts' }) + ctx.betterSidebar.openTab({ type: 'editor', title: viewer.path.split('/').pop()!, path: viewer.path, id: `editor:${viewer.path}` }) const tab = (): SidebarTab => allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs) - .find(candidate => candidate.path === '/p/a.ts')! + .find(candidate => candidate.path === viewer.path)! return { ctx, store, tab } } -function mount(): Harness { - const { ctx, store, tab } = setup() +function mount(viewer: ViewerSpec = CODE_VIEWER): Harness { + const { ctx, store, tab } = setup(viewer) const root = renderRoot(createElement(EditorHost, { ctx, store: store as never, @@ -103,21 +113,40 @@ function viewOf(container: HTMLElement): EditorView { return view } -/** Type the user's edit through CodeMirror's own doc-change path. */ -function typeDraft(container: HTMLElement): void { +/** 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: DRAFT_PREFIX } }) + viewOf(container).dispatch({ changes: { from: 0, insert: text } }) }) } +/** The user's first unsaved edit. */ +function typeDraft(container: HTMLElement): void { + typeText(container, DRAFT_PREFIX) +} + function click(element: Element): void { act(() => { element.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) } +function saveButton(container: HTMLElement): HTMLButtonElement { + const button = container.querySelector('button[aria-label="Save"]') + if (button === null) throw new Error('the host header has no save button') + return button as HTMLButtonElement +} + +/** One of the host header's mode-toggle buttons, by label. */ +function modeButton(container: HTMLElement, label: string): HTMLButtonElement { + const button = Array.from(container.querySelectorAll('button')) + .find(candidate => candidate.textContent === label) + if (button === undefined) throw new Error(`no "${label}" mode button`) + return button as HTMLButtonElement +} + /** Save once and assert the host refused it as a conflict. */ async function saveIntoConflict(container: HTMLElement): Promise { fsWrite.mockRejectedValueOnce(new SidebarApiError('fs-conflict', 'changed on disk')) - click(container.querySelector('button[aria-label="Save"]')!) + click(saveButton(container)) await settle() expect(container.textContent ?? '').toContain('changed on disk since it was loaded') } @@ -166,7 +195,7 @@ describe('save-conflict banner: reload with a dirty draft (#1059)', () => { expect(viewOf(container), 'the same editor instance stays mounted').toBe(before) expect(viewOf(container).state.doc.toString()).toBe(`${DRAFT_PREFIX}${CONTENT}`) // The next save carries the fresh baseline (200) and is accepted. - click(container.querySelector('button[aria-label="Save"]')!) + click(saveButton(container)) await settle() expect(fsWrite).toHaveBeenCalledTimes(2) expect(fsWrite.mock.calls[1]![2]).toBe(`${DRAFT_PREFIX}${CONTENT}`) @@ -198,4 +227,40 @@ describe('save-conflict banner: reload with a dirty draft (#1059)', () => { unmount() } }) + + it('compares against the last SAVED bytes when an edit-mode save did not reload', async () => { + const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false) + fsRead.mockImplementation(() => Promise.resolve(readText(CONTENT, 100))) + const { container, unmount } = mount(MARKDOWN_VIEWER) + try { + await settle() + // Markdown opens in preview; the host header's Edit toggle shows source. + click(modeButton(container, 'Edit')) + typeDraft(container) + // A successful save in EDIT mode does not reload (the host keeps the + // caret), so `content` stays at the bytes loaded when the tab opened. + click(saveButton(container)) + await settle() + expect(fsWrite).toHaveBeenCalledTimes(1) + expect(fsWrite.mock.calls[0]![2]).toBe(`${DRAFT_PREFIX}${CONTENT}`) + // The tool touches the file: same bytes as the last SAVE, new mtime. + fsRead.mockImplementation(() => Promise.resolve(readText(`${DRAFT_PREFIX}${CONTENT}`, 200))) + typeText(container, SECOND_PREFIX) + await saveIntoConflict(container) + click(reloadButton(container)) + await settle() + // In-place: no confirm, the second draft survives, the comparison point + // was the saved bytes (not the stale `content` prop). + expect(confirm).not.toHaveBeenCalled() + expect(container.textContent ?? '').not.toContain('changed on disk since it was loaded') + expect(viewOf(container).state.doc.toString()).toBe(`${SECOND_PREFIX}${DRAFT_PREFIX}${CONTENT}`) + click(saveButton(container)) + await settle() + expect(fsWrite).toHaveBeenCalledTimes(3) + expect(fsWrite.mock.calls[2]![2]).toBe(`${SECOND_PREFIX}${DRAFT_PREFIX}${CONTENT}`) + expect(fsWrite.mock.calls[2]![3]).toBe(200) + } finally { + unmount() + } + }) }) diff --git a/tests/text-editor-conflict.spec.tsx b/tests/text-editor-conflict.spec.tsx index e0c44ac0..48506d51 100644 --- a/tests/text-editor-conflict.spec.tsx +++ b/tests/text-editor-conflict.spec.tsx @@ -18,14 +18,21 @@ import type { FileViewerProps } from '../src/client/service.ts' setupReactAct() const fsWrite = vi.fn() +const fsReadProbe = vi.fn() vi.mock('../src/client/api.ts', async (importOriginal) => { // The real error class: TextEditor narrows the failure with instanceof. const actual = await importOriginal() return { ...actual, - // The real api object with only the save call replaced: TextEditor also - // reads the shared git status store in the code viewer. - api: { ...actual.api, fsWrite: (...args: unknown[]) => fsWrite(...args) }, + // The real api object with only the two calls the editor owns replaced: + // the save, and the banner's on-disk probe (a reload whose bytes match the + // loaded text is resolved in place, see #1059 — a failed probe defers to + // the host's reload, which is what this spec asserts). + api: { + ...actual.api, + fsWrite: (...args: unknown[]) => fsWrite(...args), + fsRead: (...args: unknown[]) => fsReadProbe(...args), + }, } }) @@ -56,6 +63,10 @@ function click(element: HTMLElement): void { beforeEach(() => { fsWrite.mockReset() + fsReadProbe.mockReset() + // The probe cannot read the file in this spec: the banner must fall back to + // the host's reload. + fsReadProbe.mockRejectedValue(new Error('unreadable')) }) afterEach(() => { @@ -90,6 +101,10 @@ describe('TextEditor save conflict', () => { .find(button => button.textContent === 'Reload from disk') expect(reload).toBeDefined() click(reload!) + // The banner probes the disk first; the host's reload is the fallback, + // one microtask later (a probe that matches the loaded text resolves in + // place instead — see text-editor-save-baseline / editor-conflict-reload). + await act(async () => { await Promise.resolve() }) expect(onReload).toHaveBeenCalledTimes(1) } finally { mounted.unmount()