merge #1059: 重新载入后不再死锁在 fs-conflict(仅 mtime 变化就地更新保存基线)
# Conflicts: # CHANGELOG.md
This commit is contained in:
commit
73fed1689d
5 files changed
+504
-7
No files matched your search
@@ -17,6 +17,7 @@
|
||||
- **[#1013] 超过 1000 个分支/远程跟踪引用时仍可访问提交历史**:界面显示明确标注的提交列表,保留提交选择与详情。列表读取本地分支、远程分支和当前 HEAD;分页通过 Git 引用、HEAD 与 shallow 边界的状态指纹校验,状态变化时要求刷新。引用输出上限为 8 MiB,引用数量上限为 100,000,shallow 元数据上限为 1 MiB。
|
||||
- **导出插件图标子路径**:增加 `dsh-better-sidebar/icon` 包入口,方便其他包按 `exports` 规则读取 `icon.svg`。
|
||||
- **恢复提交图的 tag 显示**(#983):lightweight 与 annotated tag 装饰对应提交,行内与详情卡使用中性描边 pill,不影响 HEAD 与分支样式。Tag 独立按引用名保留前 5,000 条,并复用 8 MiB 输出上限(超限省略完整行之外的 tag,不让整页失败);不计入 1,000 分支上限。Tag 清单纳入分页指纹,创建、移动或删除 tag 后旧游标要求刷新。
|
||||
- 🐞 **重新载入后保存不再死锁在 `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` 守护。
|
||||
|
||||
@@ -140,9 +140,16 @@ export function TextEditor(props: FileViewerProps) {
|
||||
const viewRef = useRef<CodeMirrorView | null>(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<number | null>(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<string | null>(content ?? null)
|
||||
/** The theme compartment of the current view (reconfigured on scheme flip). */
|
||||
const themeCompRef = useRef<CmThemeCompartment | null>(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) {
|
||||
<button
|
||||
type="button"
|
||||
className={css.editorBannerAction}
|
||||
onClick={() => { props.onReload?.() }}
|
||||
onClick={reloadAfterConflict}
|
||||
>
|
||||
{t('saveConflictReload')}
|
||||
</button>
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
/**
|
||||
* "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<typeof import('../src/client/api.ts')>()
|
||||
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 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 })
|
||||
|
||||
interface Harness {
|
||||
container: HTMLDivElement
|
||||
unmount: () => void
|
||||
}
|
||||
|
||||
function setup(viewer: ViewerSpec = CODE_VIEWER): { ctx: Context; store: ReturnType<typeof createSidebarStore>; tab: () => SidebarTab } {
|
||||
const store = createSidebarStore()
|
||||
const service = createBetterSidebarService(store)
|
||||
service.registerTab({ id: 'editor', title: 'Editor', dedupeKey: (tab) => tab.path, component: () => null })
|
||||
service.registerFileViewer({
|
||||
id: viewer.id,
|
||||
exts: [viewer.ext],
|
||||
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: 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 === viewer.path)!
|
||||
return { ctx, store, tab }
|
||||
}
|
||||
|
||||
function mount(viewer: ViewerSpec = CODE_VIEWER): Harness {
|
||||
const { ctx, store, tab } = setup(viewer)
|
||||
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 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 } })
|
||||
})
|
||||
}
|
||||
|
||||
/** 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<void> {
|
||||
fsWrite.mockRejectedValueOnce(new SidebarApiError('fs-conflict', 'changed on disk'))
|
||||
click(saveButton(container))
|
||||
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<void> {
|
||||
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(saveButton(container))
|
||||
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()
|
||||
}
|
||||
})
|
||||
|
||||
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()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -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<typeof import('../src/client/api.ts')>()
|
||||
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()
|
||||
|
||||
@@ -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<typeof import('../src/client/api.ts')>()
|
||||
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> = {}): 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<FileViewerProps>) => 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<FileViewerProps> = {}): Harness {
|
||||
const props = viewerProps(overrides)
|
||||
let toolbar: EditorToolbarState | undefined
|
||||
let controls: EditorToolbarControls | null = null
|
||||
const element = (next: Partial<FileViewerProps> = {}): ReturnType<typeof createElement> =>
|
||||
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<FileViewerProps>) => { 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()
|
||||
}
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user