Files
apes-sidebar/tests/git-suggest.spec.tsx
T
Menghuan1918andrainmanhhh 6615f63602 feat(git): AI 生成提交信息(Ctrl+G、多行提交框、可固定生成模型)
移植 PR #642(refs/tmp/pr642 → 当前 dev 重写,不机械解冲突)。

复用(与 dev clean 或纯逻辑无冲突面):
- src/commit-message.ts 纯逻辑模块原样取用:prompt 契约、provider/model 路由
  词法、reasoning effort 取最低档、宽容的 provider/model 目录读取、建议文本清理。
- host 半边(git.suggest-message / git.commit-model / git.models 三条路由 +
  pinned / 会话 / agent-default-model 三级路由解析)按 dev 现状重贴:ctx.llm、
  agentDefaultModel、git.status/diff、sessionId 参数名逐条对照本机 0.2.0-rc.1 核实。
- 设置缝复用 dev 已有的 SidebarSettingsRenderProps + settings.render(PR 侧写在
  同一接口上,零适配)。
- 三个新 spec 原样取用,只有 git-suggest 的 harness 改了「visible 默认 true」——
  dev 的共享 git-status store 只在可见时订阅,不可见时 snapshot 恒 null,
  commit bar 根本不渲染(PR 作者当年跑绿的是本机未提交状态)。

丢弃 / 按 dev 重写:
- PR 的 GitLens 客户端半边基于 #471 重写前的 GitLens:提交栏在 dev 已是
  primitives Input + commitBar/commitRow/commitInput,且 Ctrl/Cmd+Enter 提交
  已存在(重复实现)。现按 dev 的 .commitRow 结构重做多行 textarea + 自动增高,
  保留既有快捷键,并追加 Ctrl/Cmd+G。
- 六个 Icon*16 具名导入在 0.2.0-rc.1 一个不剩(§3.1 第 2 条:缺导出 = render 期
  Element type is invalid),改用 IconSparkleRegular size={14}。
- CSS 类名跟随 dev 的 commit* 前缀(PR 的 gitCommit*/gitSuggest*/gitError 在 dev
  已不存在;错误行改走 dev 的 Notice,不新增自绘错误样式)。
- 消息 source kind 用生产者自有值 plugin:dsh-better-sidebar:0.1.7 起
  kind:'plugin' 会被 format v4 硬拒。
- locales:dev 已删 commitError 锚点,且 19 份词典与 locales.ts 必须键集相等,
  故按各文件在 commit 行后逐份插入,不整份取 PR 侧。

验收:pnpm typecheck 0;pnpm exec vitest run --maxWorkers=3 全绿(163 files /
1836 tests);新增 spec 单独跑绿;真机挂载冒烟未跑(见报告)。

Refs #642

Co-authored-by: rainmanhhh <13862623+rainmanhhh@users.noreply.github.com>
2026-10-05 02:19:58 +08:00

214 lines
8.7 KiB
TypeScript

/**
* The Git lens' AI commit-message button: it asks the HOST (never a provider
* directly) for a suggestion and drops the text into the commit box, still
* editable and regenerable. The empty-changeset case is a dedicated wire code
* (`git-suggest-empty`) so the panel can say "nothing to summarize" instead
* of a generic generation failure.
*
* The commit bar only exists once the git status says the directory is a
* repository, and the shared status store subscribes only while the lens is
* VISIBLE — so the harness mounts a visible lens and waits for that first
* answer (the model tooltip rides the same mount, its route read fires on
* visibility too).
*/
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { GitLens } from '../src/client/changes/GitLens.tsx'
import { createSidebarStore } from '../src/client/state.ts'
import { api, SidebarApiError, type GitStatusResult } from '../src/client/api.ts'
import { setupReactAct } from './test-utils.ts'
setupReactAct()
const CWD = 'C:/repo/main'
/** One promise the test resolves by hand (in-flight states). */
function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
let resolvePromise!: (value: T) => void
const promise = new Promise<T>((resolve) => { resolvePromise = resolve })
return { promise, resolve: resolvePromise }
}
function pendingStatus(): GitStatusResult {
return { isRepo: true, branch: 'main', entries: [{ path: 'src/app.ts', xy: ' M' }] }
}
async function mount(options: {
visible?: boolean
model?: { route?: { provider: string; model: string }; pinned: boolean }
} = {}): Promise<{ container: HTMLElement; unmount: () => void }> {
vi.spyOn(api, 'gitWorktrees').mockResolvedValue([{ path: CWD, branch: 'main', current: true, changes: 1 }])
vi.spyOn(api, 'gitStatus').mockResolvedValue(pendingStatus())
vi.spyOn(api, 'gitBranch').mockResolvedValue({ current: 'main', names: ['main'] })
vi.spyOn(api, 'gitLog').mockResolvedValue([])
vi.spyOn(api, 'gitCommitModel').mockResolvedValue(options.model ?? { pinned: false })
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
await act(async () => {
root.render(createElement(GitLens, {
scope: { sessionId: 'session', cwd: CWD },
store: createSidebarStore(),
onOpenFile: () => {},
onPreview: () => {},
selectedRef: null,
visible: options.visible ?? true,
}))
})
await act(async () => { await Promise.resolve() })
await act(async () => { await Promise.resolve() })
return {
container,
unmount: () => {
act(() => { root.unmount() })
container.remove()
},
}
}
/** The suggest button (aria-label carries the localized copy; default en). */
function suggestButton(container: HTMLElement): HTMLButtonElement {
// Prefix match: the label gains a model suffix once one resolves.
const button = container.querySelector<HTMLButtonElement>('button[aria-label^="Generate commit message"]')
if (button === null) throw new Error('the suggest button is missing')
return button
}
function commitInput(container: HTMLElement): HTMLTextAreaElement {
const input = container.querySelector<HTMLTextAreaElement>('textarea')
if (input === null) throw new Error('the commit input is missing')
return input
}
afterEach(() => { vi.restoreAllMocks() })
describe('GitLens commit-message suggestion', () => {
it('fills the commit box with the host-generated message', async () => {
const suggest = vi.spyOn(api, 'gitSuggestMessage')
.mockResolvedValue({ message: 'fix: guard the empty diff', provider: 'deepseek', model: 'deepseek-chat' })
const { container, unmount } = await mount()
try {
await act(async () => { suggestButton(container).click() })
await act(async () => { await Promise.resolve() })
expect(suggest).toHaveBeenCalledTimes(1)
// The panel locale drives the prompt language (this test runs on en).
expect(suggest.mock.calls[0]?.[1]).toBe('en')
expect(commitInput(container).value).toBe('fix: guard the empty diff')
} finally {
unmount()
}
})
it('says "nothing to summarize" for the dedicated empty-changeset code', async () => {
vi.spyOn(api, 'gitSuggestMessage').mockRejectedValue(new SidebarApiError('git-suggest-empty', 'no pending changes'))
const { container, unmount } = await mount()
try {
await act(async () => { suggestButton(container).click() })
await act(async () => { await Promise.resolve() })
expect(container.textContent).toContain('No pending changes to summarize')
expect(commitInput(container).value).toBe('')
} finally {
unmount()
}
})
it('prefixes any other failure as a generation error', async () => {
vi.spyOn(api, 'gitSuggestMessage').mockRejectedValue(new SidebarApiError('git-suggest-error', 'llm down'))
const { container, unmount } = await mount()
try {
await act(async () => { suggestButton(container).click() })
await act(async () => { await Promise.resolve() })
expect(container.textContent).toContain('Failed to generate commit message')
} finally {
unmount()
}
})
it('drafts the message from the commit input with Ctrl+G', async () => {
const suggest = vi.spyOn(api, 'gitSuggestMessage')
.mockResolvedValue({ message: 'chore: shortcut', provider: 'deepseek', model: 'deepseek-chat' })
const { container, unmount } = await mount()
try {
await act(async () => {
commitInput(container).dispatchEvent(new KeyboardEvent('keydown', { key: 'g', ctrlKey: true, bubbles: true }))
})
await act(async () => { await Promise.resolve() })
expect(suggest).toHaveBeenCalledTimes(1)
expect(commitInput(container).value).toBe('chore: shortcut')
} finally {
unmount()
}
})
it('keeps a bare Enter as a newline and submits on Ctrl+Enter', async () => {
const commit = vi.spyOn(api, 'gitCommit').mockResolvedValue({ ok: true })
const { container, unmount } = await mount()
try {
const box = commitInput(container)
await act(async () => {
box.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }))
})
expect(commit).not.toHaveBeenCalled()
await act(async () => {
const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!
setter.call(box, 'feat: multiline\n\nbody line')
box.dispatchEvent(new Event('input', { bubbles: true }))
})
await act(async () => {
box.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', ctrlKey: true, bubbles: true }))
})
await act(async () => { await Promise.resolve() })
// The message (second arg) is the whole multiline text; the worktree
// argument depends on the auto-selection above, so it stays unasserted.
expect(commit).toHaveBeenCalledTimes(1)
expect(commit.mock.calls[0]?.[1]).toBe('feat: multiline\n\nbody line')
} finally {
unmount()
}
})
it('locks the box and shows the sweep label while a suggestion is in flight', async () => {
const pending = deferred<{ message: string; provider: string; model: string }>()
vi.spyOn(api, 'gitSuggestMessage').mockReturnValue(pending.promise)
const { container, unmount } = await mount()
try {
await act(async () => { suggestButton(container).click() })
expect(commitInput(container).disabled).toBe(true)
expect(container.textContent).toContain('Generating commit message…')
await act(async () => {
pending.resolve({ message: 'feat: done', provider: 'deepseek', model: 'deepseek-chat' })
await Promise.resolve()
})
expect(commitInput(container).disabled).toBe(false)
expect(commitInput(container).value).toBe('feat: done')
expect(container.textContent).not.toContain('Generating commit message…')
} finally {
unmount()
}
})
it('names the resolved model in the generate button label', async () => {
const { container, unmount } = await mount({
visible: true,
model: { route: { provider: 'deepseek', model: 'deepseek-chat' }, pinned: true },
})
try {
await act(async () => { await Promise.resolve() })
expect(suggestButton(container).title).toBe('Generate commit message (using deepseek/deepseek-chat)')
} finally {
unmount()
}
})
})