fix(editor): blame memo 在变更集消失时也失效(#212)

effect 原先在「文件已无变更集」(提交 / 丢弃后 entry === undefined)的
早退分支里直接 setKinds(EMPTY_KINDS) 返回,forgetBlame 只在有变更集的
分支才跑。于是提交前 hover 过的行继续返回提交前的 blame——包括
「Not Committed Yet」这类未提交占位——直到该文件再次产生变更集,或
memo 触顶 500 被整体清空。

把 forgetBlame 提到早退之前:变更集被重算与被清空都是失效条件。不改
过期时间,也不加缓存层。

测试:
- 新增(判别性)「提交前 hover → 变更集消失 → 再取同一行」用例,断言第
  二次重新请求且不再返回提交前答案;还原源码改动后该用例红在
  `expected "vi.fn()" to be called 2 times, but got 1 times`。
- 补一条原无守护的用例:挂载 code 视图后 api.gitBlame 调用数为 0(不预
  取),同时断言变更集确实读到了(gitDiffHead 1 次 + 色条 gutter 在
  DOM 里),避免断言因「gutter 根本没装」而空过。
- 既有的「同一行 hover 两次只打一次 git」保持为 memo 生效的守护。
This commit is contained in:
Menghuan1918 committed 2026-10-05 22:36:10 +08:00
1 parent bce22cfaf1
commit ce8366fb11
2 files changed
+84 -8

No files matched your search

+12 -6
View File
@@ -19,8 +19,10 @@
* file tree already uses for its rows.
* - Blame is fetched ON HOVER for the hovered line only, memoized per
* session + path + line. Scrolling never re-requests a range, a file is
* never prefetched, and the memo is dropped when the file's change set is
* recomputed (a new diff means new commits may be involved).
* never prefetched, and the memo is dropped whenever the file's change set
* is recomputed OR cleared — a new diff means new commits may be involved,
* and a vanished diff (the file was committed or discarded) must not leave
* the pre-commit line answering the next hover.
*/
import { useEffect, useMemo, useState } from 'react'
import { RangeSet, Compartment, StateEffect, StateField, type EditorState, type Extension } from '@codemirror/state'
@@ -247,7 +249,7 @@ const blameCache = new Map<string, Promise<GitBlameLine | null>>()
const blameKey = (sessionId: string, path: string, line: number): string =>
`${sessionId}\u0000${path}\u0000${String(line)}`
/** Drop the memo of one file (its change set was recomputed). */
/** Drop the memo of one file (its change set was recomputed or cleared). */
export function forgetBlame(sessionId: string, path: string): void {
const prefix = `${sessionId}\u0000${path}\u0000`
for (const key of [...blameCache.keys()]) {
@@ -321,14 +323,18 @@ export function useEditorGitGutter(options: EditorGitGutterOptions): ReadonlyMap
const [kinds, setKinds] = useState<ReadonlyMap<number, GitLineKind>>(EMPTY_KINDS)
useEffect(() => {
// A fresh change set invalidates the file's blame memo (the lines that
// moved may now belong to other commits) — and so does a change set that
// DISAPPEARS, which is the branch below: once the file is committed or
// discarded there is no diff to recompute, so an invalidation kept inside
// the enabled branch would never run and the next hover would be answered
// with the pre-commit line (the '[Not Committed Yet]' placeholder too).
forgetBlame(scope.sessionId, path)
if (!enabled || entry === undefined) {
setKinds(EMPTY_KINDS)
return undefined
}
let cancelled = false
// A fresh change set invalidates the file's blame memo (the lines that
// moved may now belong to other commits).
forgetBlame(scope.sessionId, path)
if (entry.tone === 'untracked') {
setKinds(addedLineKinds(content === undefined || content === '' ? 0 : content.split('\n').length))
return undefined
+72 -2
View File
@@ -9,8 +9,10 @@
* - the DECORATION GATE: the extensions are absent — not merely empty — for
* every viewer but `code` and while the ONE setting is switched off,
* checked against the real CodeMirror DOM the editor builds;
* - the BLAME MEMO: hovering the same line twice asks git once, and a fresh
* change set drops the file's memo (nothing is prefetched).
* - the BLAME MEMO: hovering the same line twice asks git once, a fresh
* change set drops the file's memo, and so does a change set that vanishes
* (commit / discard) — nothing is prefetched, and no hover is ever answered
* with a line git blamed before the commit (#212).
*/
// @vitest-environment jsdom
import { readFileSync } from 'node:fs'
@@ -284,6 +286,74 @@ describe('TextEditor wiring (code viewer only, one switch)', () => {
const MODIFIED: GitStatusResult = { isRepo: true, root: '/p', entries: [{ path: 'a.ts', xy: ' M' }] }
/** The scope the mounted editor subscribes to (and the memo is keyed by). */
const wiringScope = { sessionId: 's1', cwd: '/p' }
/** A second file, so this describe block never shares a memo entry with the
* hover-only cases above (the memo is a module-level singleton). */
const COMMITTED = '/p/committed.ts'
const MODIFIED_COMMITTED: GitStatusResult = {
isRepo: true, root: '/p', entries: [{ path: 'committed.ts', xy: ' M' }],
}
/** Flush the status store's fetch chain: the mocked git answer resolves, the
* slot publishes and the subscribed editor re-renders with the new entry. */
async function flushStatus(): Promise<void> {
await act(async () => {
invalidateGitStatus('s1')
for (let round = 0; round < 5; round += 1) await Promise.resolve()
})
}
it('never prefetches blame for the mounted code view (hover is the only trigger)', async () => {
gitStatus.mockResolvedValue(MODIFIED_COMMITTED)
gitDiffHead.mockResolvedValue({ diff: patch('committed.ts', '@@ -1,2 +1,3 @@\n one\n+inserted\n two\n') })
const mounted = renderRoot(createElement(TextEditor, viewerProps({ path: COMMITTED })))
try {
await flushStatus()
// The gutter really engaged — the change set was read and its bar is in
// the DOM — so the blame count below is not zero for want of a gutter.
expect(gitDiffHead).toHaveBeenCalledTimes(1)
expect(mounted.container.querySelector(`.${GIT_BAR_GUTTER_CLASS}`)).not.toBeNull()
expect(gitBlame).not.toHaveBeenCalled()
} finally {
mounted.unmount()
}
})
it('never answers with the pre-commit blame once the file leaves the change set (#212)', async () => {
gitStatus.mockResolvedValue(MODIFIED_COMMITTED)
gitDiffHead.mockResolvedValue({ diff: patch('committed.ts', '@@ -1,2 +1,3 @@\n one\n+inserted\n two\n') })
// What git blames a modified worktree line BEFORE the commit: the
// '[Not Committed Yet]' placeholder, no summary, no real hash.
gitBlame.mockResolvedValueOnce({
lines: [{ line: 2, hash: '0'.repeat(40), author: 'Not Committed Yet', date: '', summary: '' }],
})
const mounted = renderRoot(createElement(TextEditor, viewerProps({ path: COMMITTED })))
try {
await flushStatus()
// The hover the tooltip source performs for line 2.
const before = await loadBlameLine(wiringScope, COMMITTED, 2)
expect(before?.author).toBe('Not Committed Yet')
expect(gitBlame).toHaveBeenCalledTimes(1)
// The user commits (or discards): the status answer stops listing the
// file, so the editor's change set for it goes away.
gitStatus.mockResolvedValue({ isRepo: true, root: '/p', entries: [] })
gitBlame.mockResolvedValue({
lines: [{ line: 2, hash: 'a'.repeat(40), author: 'Ada', date: '2026-01-01T10:00:00+08:00', summary: 'feat: committed' }],
})
await flushStatus()
// The same line, hovered again. The memo of a CLEARED change set must
// not answer with the line git blamed before the commit.
const after = await loadBlameLine(wiringScope, COMMITTED, 2)
expect(gitBlame).toHaveBeenCalledTimes(2)
expect(after?.summary).toBe('feat: committed')
} finally {
mounted.unmount()
}
})
it('installs the gutter for the code viewer (default on)', async () => {
gitStatus.mockResolvedValue(MODIFIED)
gitDiffHead.mockResolvedValue({ diff: patch('a.ts', '@@ -1,2 +1,3 @@\n one\n+inserted\n two\n') })