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. */} +