From 6615f63602988dd0a151ed312078bd2b54ff7b9e Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Mon, 5 Oct 2026 02:19:58 +0800 Subject: [PATCH] =?UTF-8?q?feat(git):=20AI=20=E7=94=9F=E6=88=90=E6=8F=90?= =?UTF-8?q?=E4=BA=A4=E4=BF=A1=E6=81=AF=EF=BC=88Ctrl+G=E3=80=81=E5=A4=9A?= =?UTF-8?q?=E8=A1=8C=E6=8F=90=E4=BA=A4=E6=A1=86=E3=80=81=E5=8F=AF=E5=9B=BA?= =?UTF-8?q?=E5=AE=9A=E7=94=9F=E6=88=90=E6=A8=A1=E5=9E=8B=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 移植 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> --- src/client/api.ts | 51 ++++ src/client/builtins/tabs.tsx | 7 + src/client/changes/CommitModelSettings.tsx | 257 +++++++++++++++++++ src/client/changes/GitLens.tsx | 144 +++++++++-- src/client/changes/changes.module.css | 254 ++++++++++++++++++- src/client/locales-ar.ts | 18 +- src/client/locales-de.ts | 18 +- src/client/locales-fr.ts | 18 +- src/client/locales-hi.ts | 18 +- src/client/locales-id.ts | 18 +- src/client/locales-it.ts | 18 +- src/client/locales-ja.ts | 18 +- src/client/locales-ko.ts | 18 +- src/client/locales-nl.ts | 18 +- src/client/locales-pl.ts | 18 +- src/client/locales-pt.ts | 18 +- src/client/locales-ru.ts | 18 +- src/client/locales-sv.ts | 18 +- src/client/locales-th.ts | 18 +- src/client/locales-tr.ts | 18 +- src/client/locales-vi.ts | 18 +- src/client/locales-zh-HK.ts | 18 +- src/client/locales-zh-MO.ts | 18 +- src/client/locales-zh-TW.ts | 18 +- src/client/locales.ts | 36 ++- src/commit-message.ts | 250 ++++++++++++++++++ src/index.ts | 280 +++++++++++++++++++++ src/wire.ts | 2 + tests/builtins.spec.ts | 11 +- tests/changes-tab.spec.tsx | 2 +- tests/commit-message.spec.ts | 184 ++++++++++++++ tests/commit-model-settings.spec.tsx | 185 ++++++++++++++ tests/git-suggest.spec.tsx | 213 ++++++++++++++++ tests/git-view-worktree.spec.tsx | 2 +- 34 files changed, 2177 insertions(+), 43 deletions(-) create mode 100644 src/client/changes/CommitModelSettings.tsx create mode 100644 src/commit-message.ts create mode 100644 tests/commit-message.spec.ts create mode 100644 tests/commit-model-settings.spec.tsx create mode 100644 tests/git-suggest.spec.tsx diff --git a/src/client/api.ts b/src/client/api.ts index 3455e9cd..e8ed6756 100644 --- a/src/client/api.ts +++ b/src/client/api.ts @@ -75,6 +75,42 @@ export interface GitWorktree { changes: number } +/** One model a provider advertises (the pinned commit-message dropdown). */ +export interface GitModelInfo { + /** Provider-side model id (dispatched verbatim). */ + id: string + /** Display name; equals `id` when the adapter reports none. */ + name: string +} + +/** One provider route with the models its adapter advertises. */ +export interface GitModelProvider { + provider: string + name: string + models: GitModelInfo[] +} + +/** The model catalog `git.models` answers with. It merges three sources so + * the picker is usable even before a conversation has run: + * - `providers`: the adapters' own catalog (`llm.listModels`), + * - `recent`: routes THIS session already used (newest first), + * - `default`: the harness default selection (`agent-default-model`), which + * exists without any session at all. + * `llm` says whether the harness exposes an LLM surface: an empty catalog is + * then "no adapters registered", not "the route failed". */ +export interface GitModelCatalog { + llm: boolean + providers: GitModelProvider[] + recent: GitModelRoute[] + default?: GitModelRoute +} + +/** One pinned-model value: the route the host dispatches on. */ +export interface GitModelRoute { + provider: string + model: string +} + /** One git log row. */ export interface GitLogEntry { /** Short hash (7+ chars, display). */ @@ -340,6 +376,21 @@ export const api = { call<{ ok: true }>('git.unstage', gitPayload(scope, worktree, { ...(path !== undefined ? { path } : {}) })), gitCommit: (scope: SessionScope, message: string, worktree?: string) => call<{ ok: true }>('git.commit', gitPayload(scope, worktree, { message })), + /** Ask the host to generate a commit message from the pending changes: it + * streams the diff through the harness LLM on the pinned route (or the + * conversation's own) and answers with the route actually used. + * `language` follows the sidebar's active locale ('zh' | 'en'). */ + gitSuggestMessage: (scope: SessionScope, language: 'zh' | 'en', worktree?: string) => + call<{ message: string; provider: string; model: string }>('git.suggest-message', gitPayload(scope, worktree, { language })), + /** The discoverable provider/model catalog for the Git card's pinned-route + * setting (advisory; empty when the harness exposes no LLM service). */ + gitModels: (scope: SessionScope, signal?: AbortSignal) => + call('git.models', scopePayload(scope, {}), signal), + /** The route the NEXT commit-message suggestion would use (pinned → the + * conversation's own → the harness default); absent when none resolves. + * Cheaper than `gitModels`: no catalog discovery. */ + gitCommitModel: (scope: SessionScope, signal?: AbortSignal) => + call<{ route?: GitModelRoute; pinned: boolean }>('git.commit-model', scopePayload(scope, {}), signal), gitBranch: (scope: SessionScope, worktree?: string, signal?: AbortSignal) => call<{ current: string; names: string[] }>('git.branch', gitPayload(scope, worktree, {}), signal), gitCheckout: (scope: SessionScope, branch: string, worktree?: string) => diff --git a/src/client/builtins/tabs.tsx b/src/client/builtins/tabs.tsx index 03d06c7a..913239ae 100644 --- a/src/client/builtins/tabs.tsx +++ b/src/client/builtins/tabs.tsx @@ -20,6 +20,7 @@ import { t } from '../locales.ts' import { openSidebarFile } from '../sidebar-file.ts' import { EditorHost } from '../EditorHost.tsx' import { OpenWithSettings } from '../open-with-settings.tsx' +import { CommitModelSettings } from '../changes/CommitModelSettings.tsx' import { ChangesTab, opCountOf } from '../changes/ChangesTab.tsx' import { DiffTab } from '../DiffTab.tsx' import { SubagentView } from '../SubagentView.tsx' @@ -107,6 +108,12 @@ export function builtinTabs(): readonly TabDescriptor[] { icon: changesTabIcon, order: 20, single: true, + // Custom settings panel (not a declarative toggle row): the pinned + // commit-message model is picked from the DISCOVERED catalog, so the + // option list only exists at render time. + settings: { + render: CommitModelSettings, + }, badge: (_ctx, scope) => { const count = opCountOf(scope.sessionId) return count === undefined || count === 0 ? null : count diff --git a/src/client/changes/CommitModelSettings.tsx b/src/client/changes/CommitModelSettings.tsx new file mode 100644 index 00000000..eef546a1 --- /dev/null +++ b/src/client/changes/CommitModelSettings.tsx @@ -0,0 +1,257 @@ +/** + * The Git card's pinned-model setting: which provider/model drafts commit + * messages. It renders through the descriptor's `settings.render` seam because + * the option list is DISCOVERED at runtime (`git.models` asks the harness what + * it can serve) — a declarative toggle can only declare a static option set. + * + * Shape: a "follow the conversation" SWITCH plus a searchable `provider/model` + * box. Following is the default (an empty stored value), and it disables the + * box: while the panel tracks the conversation there is nothing to pin. The + * box is a filter over the discovered catalog AND accepts a hand-typed + * `provider/model` route, so a model the harness never advertises stays + * selectable. + * + * The value lives in the descriptor's own plugin-settings blob + * (`pluginSettings.git.commitModel`); empty/absent means "follow". + */ +import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' +import { Menu } from '@deepseek-ai/dsh-client-ui-primitives' +import { api, type GitModelCatalog } from '../api.ts' +import { t } from '../locales.ts' +import type { SidebarSettingsRenderProps } from '../service.ts' +import { Notice } from '../ui/index.ts' +import css from './changes.module.css' + +/** The plugin-owned setting key (mirrored host-side in src/index.ts). */ +export const COMMIT_MODEL_SETTING_KEY = 'commitModel' + +/** Cap of the filtered candidate list (a huge catalog stays scrollable). */ +const OPTION_LIMIT = 40 + +/** + * One selectable route. The displayed text IS the route (`provider/model`) — + * the same string the search box filters on and the host dispatches on — so a + * catalog entry and the harness default read identically instead of one being + * a decorated " · " rendering. + */ +interface ModelOption { + /** The stored and displayed `provider/model` route. */ + value: string + /** Source badge text ('' for a plain catalog entry). */ + note: string +} + +/** The stored `provider/model` route of one option ('' = follow). */ +function routeValue(provider: string, model: string): string { + return `${provider}/${model}` +} + +/** Build the candidate list: harness default and used routes first, then the + * adapter catalog. De-duplicated by route, newest/most-relevant first. */ +function optionsOf(catalog: GitModelCatalog | null): ModelOption[] { + if (catalog === null) return [] + const options: ModelOption[] = [] + const seen = new Set() + const push = (provider: string, model: string, note: string): void => { + const value = routeValue(provider, model) + if (seen.has(value)) return + seen.add(value) + options.push({ value, note }) + } + if (catalog.default !== undefined) { + push(catalog.default.provider, catalog.default.model, t('commitModelDefaultNote')) + } + for (const route of catalog.recent) { + push(route.provider, route.model, t('commitModelRecentNote')) + } + for (const provider of catalog.providers) { + for (const model of provider.models) { + push(provider.provider, model.id, '') + } + } + return options +} + +export function CommitModelSettings(props: SidebarSettingsRenderProps) { + const { store, pluginSettings, updatePluginSetting } = props + const sessionId = store.getSnapshot().sessionId + const stored = pluginSettings[COMMIT_MODEL_SETTING_KEY] + const value = typeof stored === 'string' ? stored : '' + const [catalog, setCatalog] = useState(null) + const [error, setError] = useState(null) + // Following is the DEFAULT (an empty stored value). The switch keeps its own + // draft so it can be turned off before any model is picked — the stored value + // then stays empty and generation still follows the conversation. + const [follow, setFollow] = useState(value === '') + // The search box is a FILTER, never a projection of the stored value: after + // picking a route it clears, so reopening the menu lists every candidate + // instead of filtering down to the one already selected. The selection + // itself is shown on its own line (below). + const [query, setQuery] = useState('') + const [invalid, setInvalid] = useState(false) + const [open, setOpen] = useState(false) + + useEffect(() => { + if (sessionId === undefined) return + let cancelled = false + setError(null) + api.gitModels({ sessionId }) + .then(view => { if (!cancelled) setCatalog(view) }) + .catch((reason: unknown) => { + if (cancelled) return + setError(reason instanceof Error ? reason.message : String(reason)) + }) + return () => { cancelled = true } + }, [sessionId]) + + const inputRef = useRef(null) + + const options = useMemo(() => optionsOf(catalog), [catalog]) + const needle = query.trim().toLowerCase() + const matches = useMemo( + () => (needle === '' + ? options.slice(0, OPTION_LIMIT) + : options.filter(option => option.value.toLowerCase().includes(needle)).slice(0, OPTION_LIMIT)), + [options, needle], + ) + const listOpen = open && !follow && matches.length > 0 + + /** + * The primitives Menu lays its portalled list out from the anchor rect but + * sizes it from CSS (`min-width: 218px`, `max-width: 360px`) — it has no + * "match the anchor width" mode, and its `className` only reaches the root + * wrapper. The list is a direct child of (portal), so it is reachable + * here: while open, pin its width to the input's own width so the dropdown + * is never narrower than the box it drops out of. + */ + useLayoutEffect(() => { + if (!listOpen) return + const sync = (): void => { + const input = inputRef.current + if (input === null) return + const width = Math.round(input.getBoundingClientRect().width) + if (width <= 0) return + const children: Element[] = Array.from(document.body.children) + for (let index = children.length - 1; index >= 0; index--) { + const element = children[index] + if (!(element instanceof HTMLElement) || element.getAttribute('role') !== 'menu') continue + // A floor, never a ceiling: the card may grow past the input to fit a + // long route plus its source badge (the Menu's own max-width caps it). + element.style.minWidth = `${width}px` + element.style.removeProperty('max-width') + return + } + } + sync() + window.addEventListener('resize', sync) + return () => { window.removeEventListener('resize', sync) } + }, [listOpen, matches.length]) + + /** Commit one typed/clicked route (both halves must be non-empty). */ + const commitRoute = (raw: string): boolean => { + const trimmed = raw.trim() + const slash = trimmed.indexOf('/') + const provider = slash <= 0 ? '' : trimmed.slice(0, slash).trim() + const model = slash < 0 ? '' : trimmed.slice(slash + 1).trim() + if (provider === '' || model === '') { + setInvalid(true) + return false + } + setInvalid(false) + setQuery('') + updatePluginSetting(COMMIT_MODEL_SETTING_KEY, routeValue(provider, model)) + return true + } + + const pick = (option: ModelOption): void => { + // Clear the filter (see the `query` note above) and close. + setQuery('') + setInvalid(false) + setOpen(false) + updatePluginSetting(COMMIT_MODEL_SETTING_KEY, option.value) + } + + return ( +
+
+ {t('commitModelTitle')} + +
+
{t('commitModelDesc')}
+ {/* The candidate menu is PORTALLED (the primitives Menu), like every + other dropdown in the side card: this panel renders inside the + settings modal, whose body clips overflow, so an in-flow or absolute + list would be cut off at the dialog edge. The input itself is the + menu's anchor, so typing filters the open menu in place. */} +
+ {!follow && value !== '' && ( +
{t('commitModelCurrent', { route: value })}
+ )} + 0} + className={css.commitModelMenuRoot} + anchor={( + { + setQuery(event.currentTarget.value) + setInvalid(false) + setOpen(true) + }} + onFocus={() => { setOpen(true) }} + onKeyDown={(event) => { + if (event.key === 'Enter') { + if (commitRoute(event.currentTarget.value)) setOpen(false) + } + if (event.key === 'Escape') setOpen(false) + }} + /> + )} + items={matches.map(option => ({ + id: option.value, + label: ( + + {option.value} + {option.note !== '' && {option.note}} + + ), + }))} + selectedId={value === '' ? undefined : value} + onSelect={(id) => { + const option = matches.find(candidate => candidate.value === id) + if (option !== undefined) pick(option) + }} + onClose={() => { setOpen(false) }} + portal + /> +
+ {invalid && {t('commitModelInvalid')}} + {catalog !== null && !catalog.llm && {t('commitModelUnavailable')}} + {catalog !== null && catalog.llm && options.length === 0 && ( + {t('commitModelEmpty')} + )} + {error !== null && {error}} +
+ ) +} diff --git a/src/client/changes/GitLens.tsx b/src/client/changes/GitLens.tsx index 2cb29f9a..2a41f8ed 100644 --- a/src/client/changes/GitLens.tsx +++ b/src/client/changes/GitLens.tsx @@ -26,19 +26,19 @@ * failures used to land under the commit box, which read as "your commit * failed" for an action the user never ran. */ -import { memo, useCallback, useEffect, useMemo, useRef, useState, type MouseEvent, type ReactNode } from 'react' +import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent, type ReactNode } from 'react' import { Button, IconChevronRightOutlineRegular, IconCodeOutlineRegular, IconCopyOutlineRegular, IconPlusOutlineRegular, - IconTrashOutlineRegular, Input, Menu, writeClipboard, + IconSparkleRegular, IconTrashOutlineRegular, Menu, writeClipboard, } from '@deepseek-ai/dsh-client-ui-primitives' import type { Context } from '../../context-types.ts' import type { GitLogEntry, GitStatusEntry, GitStatusResult, GitWorktree, SessionScope } from '../api.ts' -import { api } from '../api.ts' +import { api, SidebarApiError } from '../api.ts' import { builtinFileIcon, builtinFolderIcon } from '../file-icons.tsx' import { usePolling } from '../use-polling.ts' import { baseName, relativeTo } from '../paths.ts' import { resolveSidebarPath } from '../paths.ts' -import { relativeTime, t } from '../locales.ts' +import { isZh, relativeTime, t } from '../locales.ts' import type { SidebarDiffRef, SidebarStore } from '../state.ts' import { ConfirmDialog, IconButton, Notice, SectionHeader, StatusBadge, invalidateGitStatus, statusOfXY, @@ -121,6 +121,12 @@ const LOG_BATCH = 20 * within ~30s, without a second git process per status tick. */ const WORKTREE_POLL_MS = 30_000 +/** Commit-box growth contract: one line is 18px with 6px of padding above and + * below (mirrored by `changes.module.css`), and it scrolls past six lines. */ +const COMMIT_BOX_LINE_HEIGHT = 18 +const COMMIT_BOX_PADDING_Y = 6 +const COMMIT_BOX_MAX_ROWS = 6 + /** A stable empty entry list: the tree memo must not rebuild on every render * just because `snapshot?.entries ?? []` minted a new array. */ const NO_ENTRIES: readonly GitStatusEntry[] = [] @@ -296,6 +302,28 @@ export function GitLens(props: GitLensProps) { const [logFailed, setLogFailed] = useState(false) const [commitMsg, setCommitMsg] = useState('') const [busy, setBusy] = useState(false) + /** Whether a commit-message suggestion is being generated host-side (the + * host streams the diff through the harness LLM — no agent is spawned). */ + const [suggesting, setSuggesting] = useState(false) + /** The route the next suggestion would use, for the button's tooltip. */ + const [commitModel, setCommitModel] = useState(undefined) + /** Whether a COMMIT is in flight (a subset of `busy`, which also covers + * staging/checkout): the input reports it with its own busy label. */ + const [committing, setCommitting] = useState(false) + /** The commit box grows with its text, up to the scroll cap below. */ + const commitBoxRef = useRef(null) + useLayoutEffect(() => { + const box = commitBoxRef.current + // A layout-less environment (tests) reports 0: leave the CSS height alone. + if (box === null || box.scrollHeight === 0) return + const max = COMMIT_BOX_LINE_HEIGHT * COMMIT_BOX_MAX_ROWS + COMMIT_BOX_PADDING_Y * 2 + // Reset first: a scrollHeight measured against the current height can only + // ever grow, so a deleted line would leave the box too tall. + box.style.height = 'auto' + const next = Math.min(box.scrollHeight, max) + box.style.height = `${next}px` + box.style.overflowY = box.scrollHeight > max ? 'auto' : 'hidden' + }, [commitMsg]) /** The commit bar's ONE status line (commit / stage / discard / revert). */ const [actionError, setActionError] = useState(null) /** The lens-level error banner (refresh / branch switch / history paging). */ @@ -338,6 +366,23 @@ export function GitLens(props: GitLensProps) { return repoRootRef.current === undefined ? { ...base } : { ...base, repoRoot: repoRootRef.current } }, []) + /** Label the generate button with the model the next suggestion would use. + * Re-read whenever the panel becomes visible: the pinned route lives in the + * side card settings, so a change made there lands on the next visit. */ + const scopeSessionId = scope.sessionId + const scopeCwd = scope.cwd + useEffect(() => { + if (!visible) return + let cancelled = false + api.gitCommitModel({ sessionId: scopeSessionId, ...(scopeCwd === undefined ? {} : { cwd: scopeCwd }) }) + .then(view => { + if (cancelled) return + setCommitModel(view.route === undefined ? undefined : `${view.route.provider}/${view.route.model}`) + }) + .catch(() => { if (!cancelled) setCommitModel(undefined) }) + return () => { cancelled = true } + }, [visible, scopeSessionId, scopeCwd]) + // Keep the session cwd and pass the child selection explicitly: an attached // session overrides client cwd, so changing cwd alone still reads the first // repository. The status store includes repoRoot in its cache key. @@ -549,8 +594,39 @@ export function GitLens(props: GitLensProps) { const commit = (): void => { const message = commitMsg.trim() - if (message === '' || busy) return - void runAction(() => api.gitCommit(gitScopeNow(), message, selectedWorktree), errorMessage, () => { setCommitMsg('') }) + if (message === '' || busy || suggesting) return + setCommitting(true) + void runAction( + () => api.gitCommit(gitScopeNow(), message, selectedWorktree), + errorMessage, + () => { setCommitMsg('') }, + ).finally(() => { setCommitting(false) }) + } + + /** The generate button's label/tooltip: names the model when one resolves, + * so the user knows which provider the draft will run on. */ + const generateLabel = commitModel === undefined + ? t('generateCommitMessage') + : t('generateCommitMessageWith', { model: commitModel }) + + /** Ask the host to draft a commit message from the pending changes, then + * fill the message box (still editable; regenerating is allowed). */ + const suggestMessage = async (): Promise => { + if (busy || suggesting) return + setSuggesting(true) + setActionError(null) + try { + const { message } = await api.gitSuggestMessage(gitScopeNow(), isZh() ? 'zh' : 'en', selectedWorktree) + setCommitMsg(message) + } catch (reason) { + if (reason instanceof SidebarApiError && reason.code === 'git-suggest-empty') { + setActionError(t('suggestCommitEmpty')) + } else { + setActionError(`${t('suggestCommitError')}: ${errorMessage(reason)}`) + } + } finally { + setSuggesting(false) + } } /** Switching the selected checkout changes which rows are legitimate to act @@ -875,20 +951,54 @@ export function GitLens(props: GitLensProps) { {isRepo && (
- { setCommitMsg(event.target.value); setActionError(null) }} - onKeyDown={(event) => { - if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') commit() - }} - /> + + {/* A native textarea (the primitives ship no multiline input): + commit messages carry a subject AND a body, and Enter must + insert a newline — submitting stays on Ctrl/Cmd+Enter. */} +