移植 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>
251 lines
11 KiB
TypeScript
251 lines
11 KiB
TypeScript
/**
|
|
* Commit-message suggestion: the prompt contract and the model-route
|
|
* vocabulary shared by the `git.suggest-message` host route (src/index.ts)
|
|
* and its tests. Deliberately free of cordis, git and the LLM service, so
|
|
* the wording and the route parse stay unit-testable without a host.
|
|
*
|
|
* The generation itself runs through the harness LLM service (`ctx.llm`) with
|
|
* the route the CONVERSATION runs on by default, or a route the user pinned in
|
|
* the Git card's settings (see {@link parseModelRoute}). The plugin never
|
|
* touches a credential: the harness resolves provider endpoints and keys.
|
|
*/
|
|
|
|
/** Max diff characters fed to the model. A huge change set is truncated (with
|
|
* an explicit marker) so bulk renames or generated-file diffs cannot flood
|
|
* the model context. */
|
|
export const SUGGEST_DIFF_LIMIT = 12_000
|
|
|
|
/** The prompt languages the suggestion supports (the panel's own locale). */
|
|
export type CommitPromptLanguage = 'zh' | 'en'
|
|
|
|
/** One assembled suggestion request (system + user halves). */
|
|
export interface CommitPrompt {
|
|
system: string
|
|
user: string
|
|
}
|
|
|
|
/** One provider/model route — the pair the LLM service dispatches on. */
|
|
export interface CommitModelRoute {
|
|
provider: string
|
|
model: string
|
|
}
|
|
|
|
/** Narrow an untrusted language value to the supported pair. */
|
|
export function normalizeLanguage(value: unknown): CommitPromptLanguage {
|
|
return value === 'zh' ? 'zh' : 'en'
|
|
}
|
|
|
|
/** Truncate one diff to {@link SUGGEST_DIFF_LIMIT}, marking the cut. */
|
|
export function truncateDiff(diff: string): string {
|
|
if (diff.length <= SUGGEST_DIFF_LIMIT) return diff
|
|
return `${diff.slice(0, SUGGEST_DIFF_LIMIT)}\n...(diff truncated)`
|
|
}
|
|
|
|
/**
|
|
* Parse a pinned route of the form `provider/model`. The FIRST slash splits:
|
|
* a model id may carry its own slashes (e.g. a vendor-prefixed id), the
|
|
* provider never does. Anything malformed (empty half, no slash) yields
|
|
* undefined so the caller falls back to the conversation's own route.
|
|
*/
|
|
export function parseModelRoute(value: unknown): CommitModelRoute | undefined {
|
|
if (typeof value !== 'string') return undefined
|
|
const trimmed = value.trim()
|
|
const slash = trimmed.indexOf('/')
|
|
if (slash <= 0 || slash === trimmed.length - 1) return undefined
|
|
const provider = trimmed.slice(0, slash).trim()
|
|
const model = trimmed.slice(slash + 1).trim()
|
|
if (provider === '' || model === '') return undefined
|
|
return { provider, model }
|
|
}
|
|
|
|
/** Render one route back into its stored form (the select value). */
|
|
export function formatModelRoute(route: CommitModelRoute): string {
|
|
return `${route.provider}/${route.model}`
|
|
}
|
|
|
|
/** Cap of the conversation-derived route list (the adapter catalog is
|
|
* capped separately, host-side). */
|
|
export const MODEL_ROUTE_HISTORY_LIMIT = 20
|
|
|
|
/** First non-empty string among the candidates (unknown-shape reads). */
|
|
function firstString(...values: readonly unknown[]): string {
|
|
for (const value of values) {
|
|
if (typeof value === 'string' && value.trim() !== '') return value.trim()
|
|
}
|
|
return ''
|
|
}
|
|
|
|
/**
|
|
* One provider entry of the harness LLM catalog, read tolerantly: the
|
|
* adapter-registration shape is not part of this plugin's contract, so every
|
|
* plausible field is probed and an entry that yields no route is dropped
|
|
* (never guessed) — a wrong route would fail at generation time instead.
|
|
* @param entry - one `listProviders()` element.
|
|
* @returns the provider route and a display label, or undefined.
|
|
*/
|
|
export function providerEntryOf(entry: unknown): { provider: string; label: string } | undefined {
|
|
if (entry === null || typeof entry !== 'object') return undefined
|
|
const record = entry as Record<string, unknown>
|
|
const provider = firstString(record.provider, record.route, record.id)
|
|
if (provider === '') return undefined
|
|
const label = firstString(record.name, record.displayName, record.label, record.title, provider)
|
|
return { provider, label }
|
|
}
|
|
|
|
/**
|
|
* One model entry of a provider's advertised catalog (same tolerant read as
|
|
* {@link providerEntryOf}).
|
|
* @param entry - one `listModels()` element.
|
|
* @returns the model id and a display name, or undefined.
|
|
*/
|
|
export function modelEntryOf(entry: unknown): { id: string; name: string } | undefined {
|
|
if (entry === null || typeof entry !== 'object') return undefined
|
|
const record = entry as Record<string, unknown>
|
|
const id = firstString(record.id, record.model, record.name)
|
|
if (id === '') return undefined
|
|
return { id, name: firstString(record.name, record.displayName, record.label, record.title, id) }
|
|
}
|
|
|
|
/**
|
|
* The reasoning-effort ladder, lowest first. Effort ids are adapter-owned, so
|
|
* this is only a RANKING hint: an id outside the ladder still forms a valid
|
|
* route, it just cannot be ordered against these.
|
|
*/
|
|
export const REASONING_LEVEL_ORDER = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const
|
|
|
|
/**
|
|
* The lowest reasoning effort a model advertises, from the `efforts` list of
|
|
* its resolved model info. Commit-message drafting is a one-line generation:
|
|
* the highest default (DSH's DeepSeek adapter defaults to `high` unless the
|
|
* connection configures otherwise) spends the output budget on thinking and
|
|
* can leave no text at all, so the cheapest supported level is requested
|
|
* explicitly. Mirrors pi-web's generate-commit.
|
|
*
|
|
* An UNKNOWN effort id never outranks a known one; when every id is unknown
|
|
* the adapter's own first entry wins (its declared order is the only signal
|
|
* available).
|
|
* @param efforts - `modelInfo.reasoning.efforts` (unknown shape).
|
|
* @returns the effort id to request, or undefined when the model advertises
|
|
* none (passing an effort to a non-reasoning model is rejected by the
|
|
* harness, so the caller must omit the field entirely).
|
|
*/
|
|
export function lowestReasoningEffortOf(efforts: unknown): string | undefined {
|
|
if (!Array.isArray(efforts)) return undefined
|
|
const ids: string[] = []
|
|
for (const entry of efforts) {
|
|
const id = entry !== null && typeof entry === 'object' ? (entry as { id?: unknown }).id : undefined
|
|
if (typeof id === 'string' && id !== '') ids.push(id)
|
|
}
|
|
const first = ids[0]
|
|
if (first === undefined) return undefined
|
|
let best = first
|
|
let bestRank = (REASONING_LEVEL_ORDER as readonly string[]).indexOf(best)
|
|
for (const id of ids.slice(1)) {
|
|
const rank = (REASONING_LEVEL_ORDER as readonly string[]).indexOf(id)
|
|
if (rank < 0) continue
|
|
if (bestRank < 0 || rank < bestRank) {
|
|
best = id
|
|
bestRank = rank
|
|
}
|
|
}
|
|
return best
|
|
}
|
|
|
|
/**
|
|
* The harness's default model selection (settings namespace
|
|
* `agent-default-model`), read tolerantly: it is the route a NEW conversation
|
|
* would use, so it is available before any message is sent — unlike the
|
|
* conversation-derived history.
|
|
* @param selection - `agentDefaultModel.currentSelection()`.
|
|
* @returns the default route, or undefined when the service or its value is
|
|
* unavailable.
|
|
*/
|
|
export function defaultRouteOf(selection: unknown): CommitModelRoute | undefined {
|
|
if (selection === null || typeof selection !== 'object') return undefined
|
|
const record = selection as Record<string, unknown>
|
|
const provider = firstString(record.provider)
|
|
const model = firstString(record.model)
|
|
if (provider === '' || model === '') return undefined
|
|
return { provider, model }
|
|
}
|
|
|
|
/**
|
|
* Every provider/model route a session's log has actually USED, newest first
|
|
* and de-duplicated: the newest `request/header` event wins, so the list is
|
|
* the routes this deployment really dispatched on — the fallback a pinned
|
|
* model picker can always offer, even when the harness advertises no catalog.
|
|
* @param events - the session's log events (newest last).
|
|
* @param limit - max routes to return.
|
|
* @returns the distinct routes, newest first.
|
|
*/
|
|
export function collectModelRoutes(
|
|
events: readonly { type?: unknown; data?: unknown }[],
|
|
limit = MODEL_ROUTE_HISTORY_LIMIT,
|
|
): CommitModelRoute[] {
|
|
const routes: CommitModelRoute[] = []
|
|
const seen = new Set<string>()
|
|
for (let index = events.length - 1; index >= 0 && routes.length < limit; index--) {
|
|
const event = events[index]
|
|
if (event === undefined || event.type !== 'request/header') continue
|
|
const config = (event.data as { header?: { config?: unknown } } | undefined)?.header?.config
|
|
if (config === null || typeof config !== 'object') continue
|
|
const provider = (config as { provider?: unknown }).provider
|
|
const model = (config as { model?: unknown }).model
|
|
if (typeof provider !== 'string' || provider === '') continue
|
|
if (typeof model !== 'string' || model === '') continue
|
|
const key = `${provider}/${model}`
|
|
if (seen.has(key)) continue
|
|
seen.add(key)
|
|
routes.push({ provider, model })
|
|
}
|
|
return routes
|
|
}
|
|
|
|
/**
|
|
* The Conventional-Commits prompt for one pending change set. Staged wins
|
|
* upstream (it is exactly what `git commit` records); `files` is the matching
|
|
* path list and `diff` the already-truncated patch text.
|
|
* @param language - the panel locale ('zh' | 'en').
|
|
* @param files - the changed paths the diff covers (repo-root relative).
|
|
* @param diff - the patch text (truncate with {@link truncateDiff} first).
|
|
* @returns the system and user halves, in that language.
|
|
*/
|
|
export function buildCommitPrompt(
|
|
language: CommitPromptLanguage,
|
|
files: readonly string[],
|
|
diff: string,
|
|
): CommitPrompt {
|
|
const fileList = files.join('\n')
|
|
if (language === 'zh') {
|
|
return {
|
|
system: '你是 git 提交信息生成助手。根据给定的文件清单与差异,生成一行 Conventional Commits 风格的中文提交信息'
|
|
+ '(类型前缀:feat/fix/refactor/chore/docs/test/perf/style,必要时可附简短正文)。'
|
|
+ '只输出提交信息本身,不要解释。',
|
|
user: `改动的文件:\n${fileList}\n\n差异:\n${diff}`,
|
|
}
|
|
}
|
|
return {
|
|
system: 'You are a git commit message assistant. Based on the given file list and diff, write a one-line'
|
|
+ ' Conventional Commits style commit message in English (type prefix: feat/fix/refactor/chore/docs/test/perf/style,'
|
|
+ ' with a short body when needed). Output only the commit message itself, no explanation.',
|
|
user: `Changed files:\n${fileList}\n\nDiff:\n${diff}`,
|
|
}
|
|
}
|
|
|
|
/** Drop the model's prose scaffolding: fenced blocks, quotes and blank runs.
|
|
* Models routinely wrap a one-line commit message in a code fence despite
|
|
* the instruction; the panel inserts the text straight into the commit box,
|
|
* so anything but the message itself would land in the commit. */
|
|
export function cleanSuggestion(text: string): string {
|
|
const withoutFence = text
|
|
.split('\n')
|
|
.filter(line => !line.trimStart().startsWith('```'))
|
|
.join('\n')
|
|
return withoutFence
|
|
.replace(/\r/g, '')
|
|
.split('\n')
|
|
.map(line => line.trimEnd())
|
|
.join('\n')
|
|
.trim()
|
|
}
|