Merge port/pr-642:AI 生成提交信息(Ctrl+G / 多行提交框 / 可固定生成模型)

无冲突。本分支是「建议提交信息」的唯一实现来源(纯逻辑 src/commit-message.ts +
三条宿主路由 ctx.llm / agentDefaultModel / 设置缝 + CommitModelSettings.tsx +
多行 textarea / Ctrl+G / ✨ 按钮);随后合入的 port/pr-434 只取其 Push/Pull 部分,
434 的重复 suggest 接线/图标/CSS/词典键在那一批里删除。

Co-authored-by: rainmanhhh <13862623+rainmanhhh@users.noreply.github.com>
This commit is contained in:
Menghuan1918andrainmanhhh committed 2026-10-05 02:38:21 +08:00
commit 4c61cc59cd
34 files changed
+2177 -43

No files matched your search

+9 -2
View File
@@ -82,9 +82,16 @@ describe('built-in tab registrations', () => {
expect(new Set(lines).size, 'descriptions must differ per tab').toBe(visible.length)
})
it('the changes tab declares no settings of its own (the diff always docks)', () => {
it('the changes tab declares only its pinned commit-model settings panel', () => {
// The Git card's gear renders ONE custom panel: which provider/model
// drafts commit messages (rendered, not a declarative toggle row,
// because the option list is discovered at runtime through git.models).
// No declarative toggle rows ride along with it.
const { service } = setup()
expect(service.getTab('git')?.settings).toBeUndefined()
const settings = service.getTab('git')?.settings
expect(typeof settings?.render).toBe('function')
expect(settings?.toggles ?? []).toEqual([])
expect(settings?.pluginToggles ?? []).toEqual([])
})
it('only diff is hidden from the + menu; editor is the visible files window (order 10)', () => {
+1 -1
View File
@@ -263,7 +263,7 @@ describe('ChangesTab', () => {
.find(node => (node.textContent ?? '').includes(t('changesStageFailed', { message: 'index.lock exists' })))
expect(alert).toBeDefined()
// The ONE status line sits in the commit bar, directly under its input row.
const input = container.querySelector(`input[placeholder="${t('commitPlaceholder')}"]`)
const input = container.querySelector(`textarea[placeholder="${t('commitPlaceholder')}"]`)
expect(input).not.toBeNull()
expect(alert!.previousElementSibling?.contains(input)).toBe(true)
} finally {
+184
View File
@@ -0,0 +1,184 @@
/**
* Commit-message suggestion contract: the prompt halves the host sends, the
* `provider/model` route vocabulary behind the Git card's pinned-model
* setting, and the cleanup the panel applies before the text lands in the
* commit box. Pure module (no cordis, no git, no LLM) — every case here is a
* wire/contract guarantee, not an implementation detail.
*/
import { describe, expect, it } from 'vitest'
import {
buildCommitPrompt,
cleanSuggestion,
collectModelRoutes,
defaultRouteOf,
formatModelRoute,
lowestReasoningEffortOf,
modelEntryOf,
normalizeLanguage,
parseModelRoute,
providerEntryOf,
SUGGEST_DIFF_LIMIT,
truncateDiff,
} from '../src/commit-message.ts'
describe('parseModelRoute', () => {
it('splits on the FIRST slash (a model id may carry its own)', () => {
expect(parseModelRoute('deepseek/deepseek-chat')).toEqual({ provider: 'deepseek', model: 'deepseek-chat' })
expect(parseModelRoute('openai/vendor/gpt-4o')).toEqual({ provider: 'openai', model: 'vendor/gpt-4o' })
})
it('trims surrounding whitespace', () => {
expect(parseModelRoute(' deepseek / deepseek-chat ')).toEqual({ provider: 'deepseek', model: 'deepseek-chat' })
})
it('rejects anything that cannot form a route (the caller falls back)', () => {
for (const value of [undefined, null, '', ' ', 'deepseek', '/model', 'provider/', 42, {}]) {
expect(parseModelRoute(value), String(value)).toBeUndefined()
}
})
})
describe('formatModelRoute', () => {
it('round-trips through parseModelRoute', () => {
const route = { provider: 'deepseek', model: 'deepseek-chat' }
expect(parseModelRoute(formatModelRoute(route))).toEqual(route)
})
})
describe('normalizeLanguage', () => {
it('is zh only on the exact marker, en otherwise', () => {
expect(normalizeLanguage('zh')).toBe('zh')
for (const value of ['en', 'ja', undefined, 0, {}]) {
expect(normalizeLanguage(value), String(value)).toBe('en')
}
})
})
describe('truncateDiff', () => {
it('leaves a short diff untouched and marks a truncated one', () => {
expect(truncateDiff('abc')).toBe('abc')
const long = 'x'.repeat(SUGGEST_DIFF_LIMIT + 100)
const cut = truncateDiff(long)
// The cut keeps exactly SUGGEST_DIFF_LIMIT characters of the patch and
// appends the marker — a huge diff can no longer grow without bound.
expect(cut).toBe(`${'x'.repeat(SUGGEST_DIFF_LIMIT)}\n...(diff truncated)`)
expect(cut.length).toBeLessThan(long.length)
})
})
describe('buildCommitPrompt', () => {
it('carries the file list and the diff in the user half', () => {
const prompt = buildCommitPrompt('en', ['a.ts', 'b.ts'], '+added')
expect(prompt.user).toContain('a.ts')
expect(prompt.user).toContain('b.ts')
expect(prompt.user).toContain('+added')
expect(prompt.system).toContain('Conventional Commits')
})
it('asks for the message alone (no prose the panel would commit)', () => {
expect(buildCommitPrompt('en', [], '').system).toContain('Output only the commit message')
expect(buildCommitPrompt('zh', [], '').system).toContain('只输出提交信息本身')
})
it('differs by language', () => {
expect(buildCommitPrompt('zh', [], '').system).not.toBe(buildCommitPrompt('en', [], '').system)
})
})
describe('collectModelRoutes', () => {
/** One `request/header` event as the session log carries it. */
function header(provider: string, model: string): { type: string; data: unknown } {
return { type: 'request/header', data: { header: { config: { provider, model } } } }
}
it('collects the routes a session actually used, newest first and de-duplicated', () => {
const events = [
{ type: 'user/message', data: {} },
header('deepseek', 'deepseek-chat'),
header('openai', 'gpt-4o'),
header('deepseek', 'deepseek-chat'),
]
expect(collectModelRoutes(events)).toEqual([
{ provider: 'deepseek', model: 'deepseek-chat' },
{ provider: 'openai', model: 'gpt-4o' },
])
})
it('honors the cap and ignores headerless / malformed rows', () => {
const events = [
header('p1', 'm1'),
{ type: 'request/header', data: {} },
{ type: 'request/header', data: { header: {} } },
header('p2', 'm2'),
header('p3', 'm3'),
]
expect(collectModelRoutes(events, 2).map(route => route.model)).toEqual(['m3', 'm2'])
expect(collectModelRoutes([])).toEqual([])
})
})
describe('lowestReasoningEffortOf', () => {
const effort = (id: string): { id: string; name: string } => ({ id, name: id })
it('picks the cheapest advertised level, whatever the adapter order', () => {
expect(lowestReasoningEffortOf([effort('high'), effort('off'), effort('max')])).toBe('off')
expect(lowestReasoningEffortOf([effort('high'), effort('low')])).toBe('low')
expect(lowestReasoningEffortOf([effort('medium'), effort('minimal')])).toBe('minimal')
})
it('never lets an unknown id outrank a known one, and falls back to the first entry', () => {
expect(lowestReasoningEffortOf([effort('turbo'), effort('high')])).toBe('high')
expect(lowestReasoningEffortOf([effort('turbo'), effort('brisk')])).toBe('turbo')
})
it('reports "no effort" for a model that advertises none', () => {
for (const value of [undefined, null, [], 'off', [{}], [{ id: '' }]]) {
expect(lowestReasoningEffortOf(value), JSON.stringify(value)).toBeUndefined()
}
})
})
describe('catalog reads (unknown harness shapes)', () => {
it('reads a provider from any plausible field and never invents one', () => {
expect(providerEntryOf({ provider: 'deepseek', name: 'DeepSeek' }))
.toEqual({ provider: 'deepseek', label: 'DeepSeek' })
// A differently-named registration must not become an empty route.
expect(providerEntryOf({ id: 'openai' })).toEqual({ provider: 'openai', label: 'openai' })
for (const value of [undefined, null, '', 42, {}, { name: 'no route' }]) {
expect(providerEntryOf(value), String(value)).toBeUndefined()
}
})
it('reads a model id/name tolerantly', () => {
expect(modelEntryOf({ id: 'deepseek-chat' })).toEqual({ id: 'deepseek-chat', name: 'deepseek-chat' })
expect(modelEntryOf({ model: 'gpt-4o', displayName: 'GPT-4o' })).toEqual({ id: 'gpt-4o', name: 'GPT-4o' })
// A display-only title is never an id: sending a localized label to a
// provider would fail at generation time instead of falling back.
expect(modelEntryOf({ title: 'unnamed' })).toBeUndefined()
expect(modelEntryOf(null)).toBeUndefined()
})
it('reads the harness default selection, or nothing', () => {
expect(defaultRouteOf({ provider: 'deepseek', model: 'deepseek-chat' }))
.toEqual({ provider: 'deepseek', model: 'deepseek-chat' })
for (const value of [undefined, null, {}, { provider: 'deepseek' }, { model: 'm' }]) {
expect(defaultRouteOf(value), String(value)).toBeUndefined()
}
})
})
describe('cleanSuggestion', () => {
it('drops a code fence the model wrapped around the message', () => {
expect(cleanSuggestion('```\nfeat: add a thing\n```')).toBe('feat: add a thing')
expect(cleanSuggestion('```text\nfix: broken\n```')).toBe('fix: broken')
})
it('keeps a legitimate multi-line message (subject + body)', () => {
expect(cleanSuggestion('feat: add a thing\n\n- one\n- two')).toBe('feat: add a thing\n\n- one\n- two')
})
it('trims blank runs and carriage returns', () => {
expect(cleanSuggestion('\r\n chore: tidy \n\n')).toBe('chore: tidy')
expect(cleanSuggestion(' ')).toBe('')
})
})
+185
View File
@@ -0,0 +1,185 @@
/**
* The Git card's pinned-model panel: the follow switch gates the route box,
* and every candidate is displayed as the SAME string the host dispatches on
* (`provider/model`) — a catalog entry must not read as a decorated
* "<provider> · <model>" while the default reads as a route.
*/
// @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 { CommitModelSettings } from '../src/client/changes/CommitModelSettings.tsx'
import { createSidebarStore } from '../src/client/state.ts'
import { api, type GitModelCatalog } from '../src/client/api.ts'
import type { BetterSidebarService } from '../src/client/service.ts'
import { setupReactAct } from './test-utils.ts'
setupReactAct()
const CATALOG: GitModelCatalog = {
llm: true,
providers: [{
provider: 'deepseek',
name: 'DeepSeek',
models: [{ id: 'deepseek-chat', name: 'DeepSeek Chat' }],
}],
recent: [{ provider: 'openai', model: 'gpt-4o' }],
default: { provider: 'deepseek', model: 'deepseek-chat' },
}
/** Mount the panel with one session attached and the catalog already loaded. */
async function mount(pluginSettings: Record<string, unknown>): Promise<{
container: HTMLElement
writes: unknown[]
unmount: () => void
}> {
vi.spyOn(api, 'gitModels').mockResolvedValue(CATALOG)
const writes: unknown[] = []
const store = createSidebarStore()
store.setSession('session')
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
await act(async () => {
root.render(createElement(CommitModelSettings, {
store,
service: {} as unknown as BetterSidebarService,
prefs: store.getPrefs(),
pluginSettings,
updatePluginSetting: (_key: string, value: unknown) => { writes.push(value) },
close: () => {},
}))
})
await act(async () => { await Promise.resolve() })
await act(async () => { await Promise.resolve() })
return {
container,
writes,
unmount: () => {
act(() => { root.unmount() })
container.remove()
},
}
}
function routeInput(container: HTMLElement): HTMLInputElement {
const input = container.querySelector<HTMLInputElement>('input[type="text"]')
if (input === null) throw new Error('the route input is missing')
return input
}
function followSwitch(container: HTMLElement): HTMLInputElement {
const box = container.querySelector<HTMLInputElement>('input[type="checkbox"]')
if (box === null) throw new Error('the follow switch is missing')
return box
}
afterEach(() => { vi.restoreAllMocks() })
describe('CommitModelSettings', () => {
it('follows the conversation by default and disables the route box while it does', async () => {
const { container, unmount } = await mount({})
try {
expect(followSwitch(container).checked).toBe(true)
expect(routeInput(container).disabled).toBe(true)
} finally {
unmount()
}
})
it('enables the box when following is switched off', async () => {
const { container, unmount } = await mount({})
try {
const box = followSwitch(container)
await act(async () => { box.click() })
expect(box.checked).toBe(false)
expect(routeInput(container).disabled).toBe(false)
} finally {
unmount()
}
})
it('lists every candidate as the route it would dispatch on', async () => {
const { container, unmount } = await mount({})
try {
await act(async () => { followSwitch(container).click() })
const input = routeInput(container)
await act(async () => {
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!
setter.call(input, 'deepseek')
input.dispatchEvent(new Event('input', { bubbles: true }))
})
await act(async () => { await Promise.resolve() })
// The portalled menu renders outside this container.
const menuText = document.body.textContent ?? ''
expect(menuText).toContain('deepseek/deepseek-chat')
// The decorated catalog rendering would show the provider label instead.
expect(menuText).not.toContain('DeepSeek · DeepSeek Chat')
} finally {
unmount()
}
})
it('shows the stored route on its own line and keeps the search box empty', async () => {
const { container, unmount } = await mount({ commitModel: 'openai/gpt-4o' })
try {
// A stored route means the switch starts OFF; the route is displayed,
// but it is NOT projected into the search box (which would then filter
// the menu down to the already-selected model).
expect(followSwitch(container).checked).toBe(false)
expect(container.textContent).toContain('Current: openai/gpt-4o')
expect(routeInput(container).value).toBe('')
} finally {
unmount()
}
})
it('reopens the menu over every candidate while a model is already pinned', async () => {
const { container, unmount } = await mount({ commitModel: 'deepseek/deepseek-chat' })
try {
const input = routeInput(container)
await act(async () => { input.focus() })
await act(async () => { await Promise.resolve() })
const menuText = document.body.textContent ?? ''
expect(menuText).toContain('deepseek/deepseek-chat')
// The other candidate proves the list is not filtered by the selection.
expect(menuText).toContain('openai/gpt-4o')
} finally {
unmount()
}
})
it('commits a hand-typed route and clears the filter', async () => {
const { container, writes, unmount } = await mount({})
try {
await act(async () => { followSwitch(container).click() })
const input = routeInput(container)
await act(async () => {
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!
setter.call(input, 'vendor/model-x')
input.dispatchEvent(new Event('input', { bubbles: true }))
})
await act(async () => {
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }))
})
expect(writes.at(-1)).toBe('vendor/model-x')
expect(input.value).toBe('')
} finally {
unmount()
}
})
it('clears the pinned route when following is restored', async () => {
const { container, writes, unmount } = await mount({ commitModel: 'openai/gpt-4o' })
try {
await act(async () => { followSwitch(container).click() })
expect(writes.at(-1)).toBe('')
} finally {
unmount()
}
})
})
+213
View File
@@ -0,0 +1,213 @@
/**
* 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()
}
})
})
+1 -1
View File
@@ -431,7 +431,7 @@ describe('GitLens (changes tab, git lens) linked-worktree consistency', () => {
const banner = [...container.querySelectorAll<HTMLElement>('[role="alert"]')]
.find(node => (node.textContent ?? '').includes(`${t('checkoutError')}: dirty worktree`))
expect(banner).toBeDefined()
const input = container.querySelector(`input[placeholder="${t('commitPlaceholder')}"]`)
const input = container.querySelector(`textarea[placeholder="${t('commitPlaceholder')}"]`)
expect(input).not.toBeNull()
// The commit bar owns only its own status line: the branch failure is
// rendered ABOVE it, never under the commit input.