diff --git a/docs/plans/2026-10-05-git-commit-suggest-and-remote-actions.md b/docs/plans/2026-10-05-git-commit-suggest-and-remote-actions.md new file mode 100644 index 00000000..334e06c8 --- /dev/null +++ b/docs/plans/2026-10-05-git-commit-suggest-and-remote-actions.md @@ -0,0 +1,70 @@ +# Git 面板:AI 提交信息建议 + Push/Pull — 移植记录(PR #434) + +> 分支 `port/pr-434`(基于 `dev`,DSH 0.2.0-rc.1 线)。上游 PR `Feat/git commit message ai` +> 三个 commit:`6b98216` AI 建议 + 提交框置顶、`3ec82f2` Push/Pull、 +> `80e64bc` 文件树 rename。**第三个 commit 整块丢弃**:`dev` 已有等价实现 +> (commit `e39ea92` / PR #550,`src/fs-operations.ts` + `FileTree.tsx` 内联改名 + 21 份词典的 +> rename 键),且 PR 的同名 `fs.rename` 路由读 `newName`、`dev` 读 `name`,机械合并会改成坏的; +> PR 那版还会在每个词典里重复插入 rename 键(TS1117,`pnpm typecheck` 必红)。 + +## 落地内容 + +两条用户可见能力,都在「文件变动」页的 Git 视角提交栏: + +- **✨ 提交信息建议**:读暂存区差异(无暂存则读工作区差异,只有未跟踪文件则只给文件清单), + 截断到 12 000 字符,经宿主 `ctx.get('llm')` 的 `LlmRuntime.stream()` 生成一行 Conventional + Commits 信息,填进输入框(仍可编辑、可重生成)。 +- **Push / Pull**:提交栏底部两个按钮,`git push` 与 `git pull --ff-only`。 + +## 设计要点 + +- **路由**:`git.push` / `git.pull` / `git.suggest-message` 三条,与其余 git 路由同样经 + `gitCwdOf` + `selectedRepoOf` 解析目标检出,git 自己的 stderr 原样上报(无 upstream、认证失败、 + 分支分叉都是用户去终端解决的问题)。`--ff-only` 是刻意的:无头面板里打开合并编辑器等于把用户 + 困住,分叉就必须响亮失败——由 `tests/git-remote-actions.spec.ts` 钉住「HEAD 不动、工作区干净、 + 没有 `MERGE_HEAD`」。 +- **模型路由取 `Session.requestHeader()`,不扫事件日志**:上游 PR 读 `ctx.sessions.get(id)?.events`, + 而 `Session.events` 自 DSH 0.1.2-alpha.4 起就改名 `snapshotEvents()`,0.2.0-rc.1 更把它标成 + `new calls are prohibited`——照现状落地必走 503。改用增量维护的 `requestHeader()`: + `EpochHeader.config`(`provider` / `model`)与 PR 从 `request/header` 事件里读的是同一份记录, + 但每次读是 O(新增事件) 而不是整段反扫。`src/context-types.ts` 的 `SidebarSessionStore` 镜像因此 + 加了 `requestHeader()`,并给 `snapshotEvents()` 标上 `@deprecated`。 +- **消息 source 用本插件自己的 producer kind**:`{ kind: 'plugin:dsh-better-sidebar' }`(复用 + `src/sidechat-routes.ts` 已有的 `MessageSourceMap` 增强)。会话格式 v4 硬拒裸 `plugin` kind, + 而 PR 写的正是 `{ kind: 'plugin', plugin: '…' }`。 +- **块装配走宿主自己的 `BlockAssembler`**,与 agent loop / `dsh-session-title-llm` 同一套 + 分块算法;并且**读 `assembler.finish`**——`LlmRuntime.stream()` 把适配器/超时失败规范成终结 + `finish` 块而不是抛错,不读它就会把「provider 拒绝了」报成「模型返回了空信息」。 + 30s 上限(`AbortSignal.timeout`,与 sidechat create 同一形状)防止挂死的 provider 一直占住请求和 + ✨ 的转圈。 +- **提交栏只有一个状态行**:Push/Pull 的失败与 commit/stage/discard 共用既有那条 `actionError` + (文案前缀区分是哪个动作),没有照搬 PR 的第二条 `remoteError`——这个文件的既有约定就是 + 「UI 两个错误通道,各司其职」,提交栏只拥有自己那一条。 +- **提交框不置顶**:PR 把提交行搬到面板顶部,动机是当时它被夹在暂存/未暂存列表中间、要滚动才够得着; + `dev` 的提交栏已经是 `position: sticky; bottom: 0` 的常驻底栏(`changes.module.css` 的 + `.commitBar` 注释写明了这个取舍),那个问题不存在了。改动因此只保留 Push/Pull 行落在栏内, + 且**状态行仍紧贴消息行**(`tests/changes-tab.spec.tsx` 钉住的既成契约)。 + +## i18n + +8 个键(`generateCommitMessage` / `generatingCommitMessage` / `suggestCommitError` / +`suggestCommitEmpty` / `push` / `pull` / `pushError` / `pullError`)沿用上游 PR 的译文, +按 `commit` 键为锚点插入 zh、en 与 19 份第三语言词典。`generatingCommitMessage` 用在 +✨ 按钮的 `aria-label` 上:转圈本身对读屏器什么也没说。 + +## 测试 + +- `tests/git-remote-actions.spec.ts`(11 例,宿主半区,真 git):push 真把远端 main 推到本地 + commit;无 upstream 报 `git-error`;pull 快进;分叉拒绝且不留合并现场;建议走暂存差异优先、 + 回退工作区差异、仅未跟踪只给文件清单;截断;空改动 `git-suggest-empty` 且不调模型; + 无 header / 无 llm 双 503;provider 终结失败 502 与空回答 500 分开;语言按面板。 + **变异验证**:把 `requestHeader()` 换回 PR 的 `snapshotEvents()` 反扫,5 个用例立刻转红。 +- `tests/git-suggest-ui.spec.tsx`(5 例,jsdom):按钮按是否有改动禁用、调用参数(locale + + 选中的检出)、只填框不提交、`git-suggest-empty` 与 provider 失败文案分开、Push/Pull 的 + 调用参数与失败落在提交栏状态行。 + +## 未做 + +- 上游 PR 的提交框置顶(理由见上)。 +- 上游 PR 未给这两个功能任何测试;这里补齐(见上两节)。 +- 未做真机 `dsh web` 挂载验证:本节点的门禁是 typecheck + 全量 vitest + eslint。 diff --git a/src/client/api.ts b/src/client/api.ts index 3455e9cd..c27a7186 100644 --- a/src/client/api.ts +++ b/src/client/api.ts @@ -340,6 +340,19 @@ 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 })), + /** Push the selected checkout's branch to its upstream; git's own failure + * message (no upstream, auth, non-fast-forward) crosses the wire as-is. */ + gitPush: (scope: SessionScope, worktree?: string) => + call<{ ok: true }>('git.push', gitPayload(scope, worktree, {})), + /** Pull into the selected checkout (`--ff-only` host-side: a diverged branch + * fails loudly rather than opening a merge editor nobody can answer). */ + gitPull: (scope: SessionScope, worktree?: string) => + call<{ ok: true }>('git.pull', gitPayload(scope, worktree, {})), + /** Ask the host to write a commit message from the pending changes (it + * streams the diff through the conversation's own LLM route). + * `language` follows the sidebar's active locale ('zh' | 'en'). */ + gitSuggestMessage: (scope: SessionScope, language: 'zh' | 'en', worktree?: string, signal?: AbortSignal) => + call<{ message: string }>('git.suggest-message', gitPayload(scope, worktree, { language }), 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/changes/GitLens.tsx b/src/client/changes/GitLens.tsx index 2cb29f9a..cdd50e6a 100644 --- a/src/client/changes/GitLens.tsx +++ b/src/client/changes/GitLens.tsx @@ -29,16 +29,16 @@ import { memo, useCallback, useEffect, useMemo, useRef, useState, type MouseEvent, type ReactNode } from 'react' import { Button, IconChevronRightOutlineRegular, IconCodeOutlineRegular, IconCopyOutlineRegular, IconPlusOutlineRegular, - IconTrashOutlineRegular, Input, Menu, writeClipboard, + IconSparkleRegular, IconTrashOutlineRegular, Input, 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 { relativeTime, isZh, t } from '../locales.ts' import type { SidebarDiffRef, SidebarStore } from '../state.ts' import { ConfirmDialog, IconButton, Notice, SectionHeader, StatusBadge, invalidateGitStatus, statusOfXY, @@ -296,6 +296,8 @@ 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 streaming from the host LLM. */ + const [suggesting, setSuggesting] = useState(false) /** 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). */ @@ -533,6 +535,11 @@ export function GitLens(props: GitLensProps) { const stageError = (reason: unknown): string => t('changesStageFailed', { message: errorMessage(reason) }) + /** The remote actions prepend their own label: git's message for a missing + * upstream or a diverged branch says nothing about which button ran. */ + const pushError = (reason: unknown): string => `${t('pushError')}: ${errorMessage(reason)}` + const pullError = (reason: unknown): string => `${t('pullError')}: ${errorMessage(reason)}` + const stageEntry = (path: string, staged: boolean): void => { void runAction( () => (staged ? api.gitUnstage(gitScopeNow(), path, selectedWorktree) : api.gitStage(gitScopeNow(), path, selectedWorktree)), @@ -549,10 +556,45 @@ export function GitLens(props: GitLensProps) { const commit = (): void => { const message = commitMsg.trim() - if (message === '' || busy) return + if (message === '' || busy || suggesting) return void runAction(() => api.gitCommit(gitScopeNow(), message, selectedWorktree), errorMessage, () => { setCommitMsg('') }) } + /** Ask the host to write a Conventional-Commits message from the pending + * changes and fill the box. The text stays editable and re-generable, and + * the call is a read (no git mutation), so it neither locks the bar's git + * actions nor refreshes the status — only its own `suggesting` flag. */ + 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) { + // An empty pending set is the button's own precondition racing with a + // status poll, not a failure worth the provider's message. + setActionError(reason instanceof SidebarApiError && reason.code === 'git-suggest-empty' + ? t('suggestCommitEmpty') + : `${t('suggestCommitError')}: ${errorMessage(reason)}`) + } finally { + setSuggesting(false) + } + } + + /** Push the selected checkout's branch. Local commits and the remote ride the + * SAME status line as every other git action — the failures share one cause + * (no upstream, auth, divergence), so a second error channel would only + * split the user's attention. */ + const push = (): void => { + void runAction(() => api.gitPush(gitScopeNow(), selectedWorktree), pushError) + } + + /** Pull into the selected checkout (fast-forward only host-side). */ + const pull = (): void => { + void runAction(() => api.gitPull(gitScopeNow(), selectedWorktree), pullError) + } + /** Switching the selected checkout changes which rows are legitimate to act * on: clear the derived surfaces before the asynchronous refresh resolves * so a stale history row can never run over the new checkout's repository. */ @@ -879,22 +921,43 @@ export function GitLens(props: GitLensProps) { className={css.commitInput} placeholder={t('commitPlaceholder')} value={commitMsg} - disabled={busy} + disabled={busy || suggesting} onChange={(event) => { setCommitMsg(event.target.value); setActionError(null) }} onKeyDown={(event) => { if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') commit() }} /> + {/* The suggestion reads the pending changes, so it is offered + exactly while there is something to describe (the host also + refuses an empty set). The accessible name follows the state — + the spinner alone says nothing to a screen reader. */} + : } + onClick={() => { void suggestMessage() }} + /> + {/* The bar's ONE status line stays directly under the message row it + belongs to (the placement `changes-tab.spec.tsx` pins), so it keeps + reading as "your commit/stage/push failed" rather than as a tab-level + banner. */} {actionError !== null && {actionError}} + {/* Shipping the commit without leaving the panel: two hairlines at + the foot of the bar, sharing its busy lock and status line. */} +
+ + +
)} diff --git a/src/client/changes/changes.module.css b/src/client/changes/changes.module.css index a98c11c1..c7c68c51 100644 --- a/src/client/changes/changes.module.css +++ b/src/client/changes/changes.module.css @@ -210,6 +210,33 @@ .commitRow { display: flex; align-items: center; gap: 6px; } .commitInput { flex: 1; min-width: 0; } +/* Push / Pull: the two remote actions sit at the foot of the commit bar, so a + commit can be shipped without leaving the panel. */ +.commitRemoteRow { display: flex; align-items: center; gap: 6px; } + +/* The inline spinner the suggest button swaps in while the host streams a + message: same 14px footprint as the sparkle it replaces, so the row's layout + does not shift mid-generation. */ +.suggestSpinner { + display: block; + width: 14px; + height: 14px; + border: 1.5px solid var(--dsw-alias-border-l2); + border-top-color: var(--dsw-alias-label-primary); + border-radius: 50%; + animation: dsh-suggest-spin 800ms linear infinite; +} + +@keyframes dsh-suggest-spin { + to { transform: rotate(360deg); } +} + +/* Respect a reduced-motion preference: the button still shows its busy state + (the spinner replaces the icon), it just stops rotating. */ +@media (prefers-reduced-motion: reduce) { + .suggestSpinner { animation: none; } +} + /* ── History ───────────────────────────────────────────────────────────── */ /* A history row: line 1 = short-hash badge + subject, line 2 = ref pills + diff --git a/src/client/locales-ar.ts b/src/client/locales-ar.ts index 9075c183..a2e85919 100644 --- a/src/client/locales-ar.ts +++ b/src/client/locales-ar.ts @@ -176,6 +176,14 @@ export const ar: Record = { unstageAll: 'إلغاء إدراج الكل', commitPlaceholder: 'رسالة التثبيت (Ctrl+Enter)', commit: 'تثبيت', + generateCommitMessage: 'إنشاء رسالة التثبيت', + generatingCommitMessage: 'جارٍ إنشاء رسالة التثبيت…', + suggestCommitError: 'فشل إنشاء رسالة التثبيت', + suggestCommitEmpty: 'لا توجد تغييرات معلقة', + push: 'دفع', + pull: 'سحب', + pushError: 'فشل الدفع', + pullError: 'فشل السحب', branch: 'الفرع', worktree: 'شجرة العمل', checkoutError: 'فشل تبديل الفرع', diff --git a/src/client/locales-de.ts b/src/client/locales-de.ts index ec01af62..1f465abc 100644 --- a/src/client/locales-de.ts +++ b/src/client/locales-de.ts @@ -161,6 +161,14 @@ export const de: Record = { unstageAll: 'Alle unstagen', commitPlaceholder: 'Commit-Nachricht (Ctrl+Enter)', commit: 'Committen', + generateCommitMessage: 'Commit-Nachricht generieren', + generatingCommitMessage: 'Commit-Nachricht wird generiert…', + suggestCommitError: 'Generieren der Commit-Nachricht fehlgeschlagen', + suggestCommitEmpty: 'Keine ausstehenden Änderungen', + push: 'Pushen', + pull: 'Pullen', + pushError: 'Pushen fehlgeschlagen', + pullError: 'Pullen fehlgeschlagen', branch: 'Branch', worktree: 'Worktree', checkoutError: 'Branchenwechsel fehlgeschlagen', diff --git a/src/client/locales-fr.ts b/src/client/locales-fr.ts index 3f6324cf..caa94198 100644 --- a/src/client/locales-fr.ts +++ b/src/client/locales-fr.ts @@ -168,6 +168,14 @@ export const fr: Record = { unstageAll: 'Tout retirer de la scène', commitPlaceholder: 'Message de commit (Ctrl+Entrée)', commit: 'Valider', + generateCommitMessage: 'Générer un message de commit', + generatingCommitMessage: 'Génération du message de commit…', + suggestCommitError: 'Échec de la génération du message de commit', + suggestCommitEmpty: 'Aucune modification en attente', + push: 'Pousser', + pull: 'Tirer', + pushError: 'Échec du push', + pullError: 'Échec du pull', branch: 'Branche', worktree: 'Arborescence de travail', checkoutError: 'Échec du changement de branche', diff --git a/src/client/locales-hi.ts b/src/client/locales-hi.ts index 33b6e8e7..772df8e6 100644 --- a/src/client/locales-hi.ts +++ b/src/client/locales-hi.ts @@ -175,6 +175,14 @@ export const hi: Record = { unstageAll: 'सभी अनस्टेज करें', commitPlaceholder: 'कमिट संदेश (Ctrl+Enter)', commit: 'कमिट', + generateCommitMessage: 'कमिट संदेश उत्पन्न करें', + generatingCommitMessage: 'कमिट संदेश उत्पन्न हो रहा है…', + suggestCommitError: 'कमिट संदेश उत्पन्न करने में विफल', + suggestCommitEmpty: 'कोई लंबित परिवर्तन नहीं', + push: 'पुश करें', + pull: 'पुल करें', + pushError: 'पुश विफल', + pullError: 'पुल विफल', branch: 'ब्रांच', worktree: 'वर्कट्री', checkoutError: 'ब्रांच स्विच विफल', diff --git a/src/client/locales-id.ts b/src/client/locales-id.ts index 71845308..fa73a5e4 100644 --- a/src/client/locales-id.ts +++ b/src/client/locales-id.ts @@ -173,6 +173,14 @@ export const id: Record = { unstageAll: 'Unstage semua', commitPlaceholder: 'Pesan commit (Ctrl+Enter)', commit: 'Commit', + generateCommitMessage: 'Buat pesan commit', + generatingCommitMessage: 'Membuat pesan commit…', + suggestCommitError: 'Gagal membuat pesan commit', + suggestCommitEmpty: 'Tidak ada perubahan yang tertunda', + push: 'Dorong', + pull: 'Tarik', + pushError: 'Dorong gagal', + pullError: 'Tarik gagal', branch: 'Branch', worktree: 'Worktree', checkoutError: 'Beralih branch gagal', diff --git a/src/client/locales-it.ts b/src/client/locales-it.ts index 1f2094d8..9527ced1 100644 --- a/src/client/locales-it.ts +++ b/src/client/locales-it.ts @@ -166,6 +166,14 @@ export const it: Record = { unstageAll: 'Rimuovi tutto dalla preparazione', commitPlaceholder: 'Messaggio di commit (Ctrl+Enter)', commit: 'Commit', + generateCommitMessage: 'Genera messaggio di commit', + generatingCommitMessage: 'Generazione del messaggio di commit…', + suggestCommitError: 'Generazione del messaggio di commit non riuscita', + suggestCommitEmpty: 'Nessuna modifica in sospeso', + push: 'Push', + pull: 'Pull', + pushError: 'Push non riuscito', + pullError: 'Pull non riuscito', branch: 'Ramo', worktree: 'Albero di lavoro', checkoutError: 'Cambio di ramo non riuscito', diff --git a/src/client/locales-ja.ts b/src/client/locales-ja.ts index 02cb4cc4..79ecf580 100644 --- a/src/client/locales-ja.ts +++ b/src/client/locales-ja.ts @@ -175,6 +175,14 @@ export const ja: Record = { unstageAll: 'すべてステージ解除', commitPlaceholder: 'コミットメッセージ (Ctrl+Enter)', commit: 'コミット', + generateCommitMessage: 'コミットメッセージを生成', + generatingCommitMessage: 'コミットメッセージを生成中…', + suggestCommitError: 'コミットメッセージの生成に失敗', + suggestCommitEmpty: 'コミット対象の変更がありません', + push: 'プッシュ', + pull: 'プル', + pushError: 'プッシュに失敗', + pullError: 'プルに失敗', branch: 'ブランチ', worktree: 'ワークツリー', checkoutError: 'ブランチ切り替えに失敗', diff --git a/src/client/locales-ko.ts b/src/client/locales-ko.ts index ed7b7baa..d50e875a 100644 --- a/src/client/locales-ko.ts +++ b/src/client/locales-ko.ts @@ -167,6 +167,14 @@ export const ko: Record = { unstageAll: '모두 스테이징 해제', commitPlaceholder: '커밋 메시지 (Ctrl+Enter)', commit: '커밋', + generateCommitMessage: '커밋 메시지 생성', + generatingCommitMessage: '커밋 메시지 생성 중…', + suggestCommitError: '커밋 메시지 생성 실패', + suggestCommitEmpty: '대기 중인 변경 사항이 없습니다', + push: '푸시', + pull: '풀', + pushError: '푸시 실패', + pullError: '풀 실패', branch: '브랜치', worktree: '워크트리', checkoutError: '브랜치 전환 실패', diff --git a/src/client/locales-nl.ts b/src/client/locales-nl.ts index 9747a675..056c246b 100644 --- a/src/client/locales-nl.ts +++ b/src/client/locales-nl.ts @@ -173,6 +173,14 @@ export const nl: Record = { unstageAll: 'Alles unstagen', commitPlaceholder: 'Commitbericht (Ctrl+Enter)', commit: 'Commit', + generateCommitMessage: 'Commitbericht genereren', + generatingCommitMessage: 'Commitbericht wordt gegenereerd…', + suggestCommitError: 'Genereren van commitbericht mislukt', + suggestCommitEmpty: 'Geen openstaande wijzigingen', + push: 'Pushen', + pull: 'Pullen', + pushError: 'Pushen mislukt', + pullError: 'Pullen mislukt', branch: 'Branch', worktree: 'Worktree', checkoutError: 'Wisselen van branch mislukt', diff --git a/src/client/locales-pl.ts b/src/client/locales-pl.ts index 966a08a1..7b202c56 100644 --- a/src/client/locales-pl.ts +++ b/src/client/locales-pl.ts @@ -177,6 +177,14 @@ export const pl: Record = { unstageAll: 'Usuń wszystko z indeksu', commitPlaceholder: 'Komunikat commitu (Ctrl+Enter)', commit: 'Commit', + generateCommitMessage: 'Wygeneruj wiadomość commita', + generatingCommitMessage: 'Generowanie wiadomości commita…', + suggestCommitError: 'Nie udało się wygenerować wiadomości commita', + suggestCommitEmpty: 'Brak oczekujących zmian', + push: 'Wypchnij', + pull: 'Pociągnij', + pushError: 'Nie udało się wypchnąć', + pullError: 'Nie udało się pociągnąć', branch: 'Gałąź', worktree: 'Drzewo robocze', checkoutError: 'Przełączenie gałęzi nie powiodło się', diff --git a/src/client/locales-pt.ts b/src/client/locales-pt.ts index e99bff66..4c3eb7b0 100644 --- a/src/client/locales-pt.ts +++ b/src/client/locales-pt.ts @@ -158,6 +158,14 @@ export const pt: Record = { unstageAll: 'Desfazer stage de tudo', commitPlaceholder: 'Mensagem de commit (Ctrl+Enter)', commit: 'Commit', + generateCommitMessage: 'Gerar mensagem de commit', + generatingCommitMessage: 'Gerando mensagem de commit…', + suggestCommitError: 'Falha ao gerar mensagem de commit', + suggestCommitEmpty: 'Nenhuma alteração pendente', + push: 'Enviar', + pull: 'Puxar', + pushError: 'Falha ao enviar', + pullError: 'Falha ao puxar', branch: 'Branch', worktree: 'Worktree', checkoutError: 'Falha ao alternar de branch', diff --git a/src/client/locales-ru.ts b/src/client/locales-ru.ts index e8a13e15..32ff2182 100644 --- a/src/client/locales-ru.ts +++ b/src/client/locales-ru.ts @@ -171,6 +171,14 @@ export const ru: Record = { unstageAll: 'Убрать всё из индекса', commitPlaceholder: 'Сообщение коммита (Ctrl+Enter)', commit: 'Закоммитить', + generateCommitMessage: 'Создать сообщение коммита', + generatingCommitMessage: 'Создание сообщения коммита…', + suggestCommitError: 'Не удалось создать сообщение коммита', + suggestCommitEmpty: 'Нет ожидающих изменений', + push: 'Отправить', + pull: 'Получить', + pushError: 'Не удалось отправить', + pullError: 'Не удалось получить', branch: 'Ветка', worktree: 'Рабочее дерево', checkoutError: 'Сбой переключения ветки', diff --git a/src/client/locales-sv.ts b/src/client/locales-sv.ts index 662d3f9f..72720485 100644 --- a/src/client/locales-sv.ts +++ b/src/client/locales-sv.ts @@ -158,6 +158,14 @@ export const sv: Record = { unstageAll: 'Avköa alla', commitPlaceholder: 'Commit-meddelande (Ctrl+Enter)', commit: 'Commit', + generateCommitMessage: 'Generera commit-meddelande', + generatingCommitMessage: 'Genererar commit-meddelande…', + suggestCommitError: 'Kunde inte generera commit-meddelande', + suggestCommitEmpty: 'Inga väntande ändringar', + push: 'Skicka', + pull: 'Hämta', + pushError: 'Kunde inte skicka', + pullError: 'Kunde inte hämta', branch: 'Gren', worktree: 'Arbetsträd', checkoutError: 'Grenbyte misslyckades', diff --git a/src/client/locales-th.ts b/src/client/locales-th.ts index d8ab894a..b4b73e42 100644 --- a/src/client/locales-th.ts +++ b/src/client/locales-th.ts @@ -175,6 +175,14 @@ export const th: Record = { unstageAll: 'Unstage ทั้งหมด', commitPlaceholder: 'ข้อความ commit (Ctrl+Enter)', commit: 'Commit', + generateCommitMessage: 'สร้างข้อความ commit', + generatingCommitMessage: 'กำลังสร้างข้อความ commit…', + suggestCommitError: 'สร้างข้อความ commit ไม่สำเร็จ', + suggestCommitEmpty: 'ไม่มีการเปลี่ยนแปลงที่รอดำเนินการ', + push: 'ผลัก', + pull: 'ดึง', + pushError: 'ผลักไม่สำเร็จ', + pullError: 'ดึงไม่สำเร็จ', branch: 'Branch', worktree: 'เวิร์กทรี', checkoutError: 'สลับ branch ล้มเหลว', diff --git a/src/client/locales-tr.ts b/src/client/locales-tr.ts index d67b1c61..a6839062 100644 --- a/src/client/locales-tr.ts +++ b/src/client/locales-tr.ts @@ -175,6 +175,14 @@ export const tr: Record = { unstageAll: 'Tümünü sahnelemeden kaldır', commitPlaceholder: 'İşleme iletisi (Ctrl+Enter)', commit: 'İşle', + generateCommitMessage: 'Commit mesajı oluştur', + generatingCommitMessage: 'Commit mesajı oluşturuluyor…', + suggestCommitError: 'Commit mesajı oluşturulamadı', + suggestCommitEmpty: 'Bekleyen değişiklik yok', + push: 'İt', + pull: 'Çek', + pushError: 'İtme başarısız', + pullError: 'Çekme başarısız', branch: 'Dal', worktree: 'Çalışma ağacı', checkoutError: 'Dal değiştirme başarısız', diff --git a/src/client/locales-vi.ts b/src/client/locales-vi.ts index 93041e85..3c5d7b83 100644 --- a/src/client/locales-vi.ts +++ b/src/client/locales-vi.ts @@ -175,6 +175,14 @@ export const vi: Record = { unstageAll: 'Unstage tất cả', commitPlaceholder: 'Thông điệp commit (Ctrl+Enter)', commit: 'Commit', + generateCommitMessage: 'Tạo thông điệp commit', + generatingCommitMessage: 'Đang tạo thông điệp commit…', + suggestCommitError: 'Không thể tạo thông điệp commit', + suggestCommitEmpty: 'Không có thay đổi đang chờ', + push: 'Đẩy', + pull: 'Kéo', + pushError: 'Đẩy thất bại', + pullError: 'Kéo thất bại', branch: 'Branch', worktree: 'Worktree', checkoutError: 'Chuyển branch thất bại', diff --git a/src/client/locales-zh-HK.ts b/src/client/locales-zh-HK.ts index 56c76d2f..9f649721 100644 --- a/src/client/locales-zh-HK.ts +++ b/src/client/locales-zh-HK.ts @@ -190,6 +190,14 @@ export const zhHK: Record = { unstageAll: '全部取消暫存', commitPlaceholder: '提交訊息 (Ctrl+Enter)', commit: '提交', + generateCommitMessage: '生成提交資訊', + generatingCommitMessage: '正在生成提交資訊…', + suggestCommitError: '生成提交資訊失敗', + suggestCommitEmpty: '目前沒有可提交的變更', + push: '推送', + pull: '拉取', + pushError: '推送失敗', + pullError: '拉取失敗', branch: '分支', worktree: '工作樹', checkoutError: '切換分支失敗', diff --git a/src/client/locales-zh-MO.ts b/src/client/locales-zh-MO.ts index ba2712a2..b4673c4f 100644 --- a/src/client/locales-zh-MO.ts +++ b/src/client/locales-zh-MO.ts @@ -190,6 +190,14 @@ export const zhMO: Record = { unstageAll: '全部取消暫存', commitPlaceholder: '提交訊息 (Ctrl+Enter)', commit: '提交', + generateCommitMessage: '生成提交資訊', + generatingCommitMessage: '正在生成提交資訊…', + suggestCommitError: '生成提交資訊失敗', + suggestCommitEmpty: '目前沒有可提交的變更', + push: '推送', + pull: '拉取', + pushError: '推送失敗', + pullError: '拉取失敗', branch: '分支', worktree: '工作樹', checkoutError: '切換分支失敗', diff --git a/src/client/locales-zh-TW.ts b/src/client/locales-zh-TW.ts index d7d0f505..ba0d6b6f 100644 --- a/src/client/locales-zh-TW.ts +++ b/src/client/locales-zh-TW.ts @@ -190,6 +190,14 @@ export const zhTW: Record = { unstageAll: '全部取消暫存', commitPlaceholder: '提交訊息 (Ctrl+Enter)', commit: '提交', + generateCommitMessage: '生成提交資訊', + generatingCommitMessage: '正在生成提交資訊…', + suggestCommitError: '生成提交資訊失敗', + suggestCommitEmpty: '目前沒有可提交的變更', + push: '推送', + pull: '拉取', + pushError: '推送失敗', + pullError: '拉取失敗', branch: '分支', worktree: '工作樹', checkoutError: '切換分支失敗', diff --git a/src/client/locales.ts b/src/client/locales.ts index f39512f4..185fb93a 100644 --- a/src/client/locales.ts +++ b/src/client/locales.ts @@ -186,6 +186,14 @@ export const zh = { unstageAll: '全部取消暂存', commitPlaceholder: '提交信息 (Ctrl+Enter)', commit: '提交', + generateCommitMessage: '生成提交信息', + generatingCommitMessage: '正在生成提交信息…', + suggestCommitError: '生成提交信息失败', + suggestCommitEmpty: '当前没有可提交的改动', + push: '推送', + pull: '拉取', + pushError: '推送失败', + pullError: '拉取失败', branch: '分支', worktree: '工作树', checkoutError: '切换分支失败', @@ -727,6 +735,14 @@ export const en: Record = { unstageAll: 'Unstage all', commitPlaceholder: 'Commit message (Ctrl+Enter)', commit: 'Commit', + generateCommitMessage: 'Generate commit message', + generatingCommitMessage: 'Generating commit message…', + suggestCommitError: 'Failed to generate commit message', + suggestCommitEmpty: 'No pending changes to summarize', + push: 'Push', + pull: 'Pull', + pushError: 'Push failed', + pullError: 'Pull failed', branch: 'Branch', worktree: 'Worktree', checkoutError: 'Branch switch failed', diff --git a/src/context-types.ts b/src/context-types.ts index fc887e71..15fc7843 100644 --- a/src/context-types.ts +++ b/src/context-types.ts @@ -83,6 +83,12 @@ export interface SidebarSessionHeader { cwd?: string } +/** The provider/model route of one session's current request header. */ +export interface SidebarSessionRoute { + provider?: string + model?: string +} + /** The host session store face (`ctx.sessions.get(id)` returns the live session). */ export interface SidebarSessionStore { get(id: string): { @@ -92,8 +98,20 @@ export interface SidebarSessionStore { * Read-only access — the jobs.output route replays `job_output` * tool/result rows from it. (The `Session.events` property this face * mirrored was renamed to `snapshotEvents()` in DSH 0.1.2-alpha.4.) + * @deprecated in the host (`new calls are prohibited`); prefer the + * `requestHeader()` fold below. This face stays for the historical rows + * it reads. */ snapshotEvents(): readonly SidebarSessionEvent[] + /** + * The {@link SidebarSessionRoute} in force after the log's last + * `request/header` — the header the NEXT request will be compared + * against — or undefined before the first header event. The host + * maintains it incrementally, so this is O(new events) where a reverse + * scan of `snapshotEvents()` is O(log): the commit-message suggestion + * reads its provider/model from here instead of replaying the log. + */ + requestHeader(): { config?: SidebarSessionRoute } | undefined } | undefined } diff --git a/src/git.ts b/src/git.ts index 05402a94..081296aa 100644 --- a/src/git.ts +++ b/src/git.ts @@ -488,3 +488,19 @@ export async function revert(cwd: string, hash: string, selected?: string): Prom export async function cherryPick(cwd: string, hash: string, selected?: string): Promise { await runGit(await repoRoot(cwd, selected), ['cherry-pick', '--end-of-options', hash]) } + +/** Push the current branch to its upstream (`git push`). A branch without a + * tracking remote fails loudly with git's own message — the panel shows it and + * the user fixes the tracking in a terminal. No operands, so there is nothing + * for a caller-supplied value to smuggle in as an option. */ +export async function push(cwd: string, selected?: string): Promise { + await runGit(await repoRoot(cwd, selected), ['push']) +} + +/** Pull upstream changes into the current branch (`git pull --ff-only`). + * Fast-forward-only keeps a headless panel out of merge/conflict editors: a + * diverged branch fails with git's own message instead of opening an + * interactive merge, so the user resolves it in a terminal. */ +export async function pull(cwd: string, selected?: string): Promise { + await runGit(await repoRoot(cwd, selected), ['pull', '--ff-only']) +} diff --git a/src/index.ts b/src/index.ts index 6ad91a95..453bba67 100644 --- a/src/index.ts +++ b/src/index.ts @@ -42,6 +42,7 @@ import { launchExternal } from './open-external.ts' import { archiveNameOf, collectZipEntries, createArchiveTasks, disambiguateArchiveNames, respondArchiveDownload, type ArchiveTasks } from './archive-route.ts' import type { ZipEntry } from './zip.ts' import * as git from './git.ts' +import { BlockAssembler, createUserMessage, type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm' import { SettingsConflictError } from '@deepseek-ai/dsh-settings' import { AgentOpenRegistry, registerOpenTool, type AgentOpenRequest } from './agent-opens.ts' import { buildSubagentLiveApi, type SidebarSubagentLiveRoutes } from './subagent-live-route.ts' @@ -207,6 +208,38 @@ async function resolveStatusPath(cwd: string, raw: string, selected?: string): P /** How many leading bytes a binary read returns for client-side detect sniffing. */ const READ_HEAD_LIMIT = 4096 +/** + * Max diff characters fed to the commit-message suggestion model. A huge + * change set is truncated (with an explicit marker) so the prompt stays within + * a reasonable context even for bulk renames or generated-file diffs. + */ +const SUGGEST_DIFF_LIMIT = 12_000 + +/** Wall-clock bound of one commit-message suggestion call (same shape as the + * sidechat create deadline: an abort settles the stream as a terminal + * `finish`, which the route then reports). */ +const SUGGEST_TIMEOUT_MS = 30_000 + +/** + * Resolve the provider/model route the current conversation runs on, read from + * the session's folded `request/header` — the header the NEXT request will be + * compared against. The commit-message suggestion reuses that route so it + * follows the user's configured LLM without spawning an agent: credentials and + * endpoints stay inside the harness's LLM service, the sidebar never touches an + * API key. Returns undefined while the session is unavailable or has no header + * yet (a cold, not-yet-attached conversation), or when the folded config does + * not name both fields — the route then degrades to a 503 instead of a + * TypeError. + */ +function sessionModelRoute(ctx: Context, sessionId: string): { provider: string; model: string } | undefined { + const config = ctx.sessions.get(sessionId)?.requestHeader()?.config + if (config === undefined) return undefined + const { provider, model } = config + return typeof provider === 'string' && provider !== '' && typeof model === 'string' && model !== '' + ? { provider, model } + : undefined +} + /** Text read of a file with the size cap; text encoding is detected before * the NUL-based binary fallback so UTF-16/UTF-32 text remains editable. * Binary reads also return the first {@link READ_HEAD_LIMIT} bytes (base64) @@ -508,6 +541,20 @@ function buildApi( await git.commit(cwd, message, selectedRepoOf(payload)) return { ok: true } }, + // Ship a commit without leaving the panel. Both target the selected + // checkout through gitCwdOf/selectedRepoOf like every other git route, and + // both report git's own stderr: a missing upstream (push) or a diverged + // branch (pull is --ff-only) is the user's to resolve in a terminal. + 'git.push': async (payload) => { + const { cwd } = await gitCwdOf(payload) + await git.push(cwd, selectedRepoOf(payload)) + return { ok: true } + }, + 'git.pull': async (payload) => { + const { cwd } = await gitCwdOf(payload) + await git.pull(cwd, selectedRepoOf(payload)) + return { ok: true } + }, 'git.branch': async (payload) => { const { cwd } = await gitCwdOf(payload) return git.branches(cwd, selectedRepoOf(payload)) @@ -561,6 +608,91 @@ function buildApi( const rev = requireString(payload, 'rev') return { content: await git.show(cwd, rev, path, repoRoot) } }, + // Commit-message suggestion: build a prompt from the pending changes and + // stream it through the harness's LLM service (`ctx.get('llm')`) on the + // route the conversation itself runs on — no agent is spawned, no session + // event is written, and the sidebar never sees a credential. Staged changes + // win because they are exactly what `git commit` records; with nothing + // staged the unstaged diff is used, and a lone untracked set still yields a + // file-list-based message. The diff is truncated so a bulk change cannot + // flood the model context. + 'git.suggest-message': async (payload) => { + const { cwd, sessionId } = await gitCwdOf(payload) + const repoRoot = selectedRepoOf(payload) + const record = payload as { language?: unknown } + const language = record.language === 'zh' ? 'zh' : 'en' + const status = await git.status(cwd, repoRoot) + const staged = status.entries.filter((entry) => entry.xy[0] !== ' ' && entry.xy[0] !== '?') + const untracked = status.entries.filter((entry) => entry.xy === '??') + const unstaged = status.entries.filter((entry) => entry.xy !== '??' && entry.xy[1] !== ' ' && entry.xy[1] !== '?') + if (staged.length === 0 && unstaged.length === 0 && untracked.length === 0) { + throw new SidebarError('git-suggest-empty', 'no pending changes', 400) + } + const focus = staged.length > 0 + ? { diff: await git.diff(cwd, undefined, true, repoRoot), files: staged } + : unstaged.length > 0 + ? { diff: await git.diff(cwd, undefined, false, repoRoot), files: unstaged } + : { diff: '', files: untracked } + const route = sessionModelRoute(ctx, sessionId) + if (route === undefined) { + throw new SidebarError('git-suggest-error', 'cannot resolve the session model route', 503) + } + const diffText = focus.diff.length > SUGGEST_DIFF_LIMIT + ? `${focus.diff.slice(0, SUGGEST_DIFF_LIMIT)}\n…(diff truncated)` + : focus.diff + const fileList = focus.files.map((entry) => entry.path).join('\n') + const system = language === 'zh' + ? '你是 git 提交信息生成助手。根据给定的文件清单与差异,生成一行 Conventional Commits 风格的中文提交信息(类型前缀:feat/fix/refactor/chore/docs/test/perf/style,必要时可附简短正文)。只输出提交信息本身,不要解释。' + : '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.' + const user = language === 'zh' + ? `改动的文件:\n${fileList}\n\n差异:\n${diffText}` + : `Changed files:\n${fileList}\n\nDiff:\n${diffText}` + // The LLM surface is a harness-provided service this plugin does not + // inject, so it is read through `ctx.get` and checked before use: a + // deployment without it gets a clean 503 instead of a TypeError. The + // stream is assembled with the harness's own BlockAssembler — the same + // chunk-to-message algorithm the agent loop and dsh-session-title-llm + // use — and the message source is the plugin's own producer kind, the + // one DSH's v3→v4 migration derives for this plugin (a bare `plugin` + // kind was rejected outright in format v4). + const llm = ctx.get('llm') as { stream(options: GenerateOptions): AsyncIterable } | undefined + if (llm === undefined) { + throw new SidebarError('git-suggest-error', 'the harness LLM service is unavailable', 503) + } + const assembler = new BlockAssembler() + // A bounded call: an unresponsive provider must not hold the request (and + // the panel's spinner) open forever, and the abort settles the stream as + // a terminal `finish` this route reports like any other failure. + const signal = AbortSignal.timeout(SUGGEST_TIMEOUT_MS) + for await (const chunk of llm.stream({ + provider: route.provider, + model: route.model, + messages: [createUserMessage({ + content: [{ type: 'text', text: user }], + source: { kind: 'plugin:dsh-better-sidebar' }, + })], + system, + maxTokens: 200, + signal, + })) { + assembler.push(chunk) + } + // `llm.stream()` normalizes an adapter or timeout failure into a + // terminal `finish` chunk instead of throwing; unchecked, the provider's + // real reason would surface as "the model returned an empty message". + const finish = assembler.finish + if (finish.kind === 'error' || finish.kind === 'aborted') { + throw new SidebarError('git-suggest-error', finish.failure.message, 502) + } + const message = assembler.blocks() + .map((block) => (block.type === 'text' ? block.text : '')) + .join('') + .trim() + if (message === '') { + throw new SidebarError('git-suggest-error', 'the model returned an empty message', 500) + } + return { message } + }, // The session's file-tool events for the changes tab's session lens // (and its badge): the CLIENT runtime's sessions face has no event-log // access, so the events cross the wire here — live session log first, diff --git a/src/wire.ts b/src/wire.ts index f4469e57..13339004 100644 --- a/src/wire.ts +++ b/src/wire.ts @@ -20,6 +20,8 @@ export type SidebarErrorCode = | 'fs-error' | 'fs-conflict' | 'git-error' + | 'git-suggest-empty' + | 'git-suggest-error' | 'job-error' | 'team-error' | 'team-conflict' diff --git a/tests/git-remote-actions.spec.ts b/tests/git-remote-actions.spec.ts new file mode 100644 index 00000000..981e213c --- /dev/null +++ b/tests/git-remote-actions.spec.ts @@ -0,0 +1,420 @@ +/** + * The Git panel's remote + AI routes over the real `/sidebar/api` surface: + * `git.push` / `git.pull` against a real bare remote, and `git.suggest-message` + * — which diff becomes the prompt, which provider/model route it runs on, and + * every degradation branch (nothing pending, no session header, no LLM service, + * a provider-side stream failure, an empty model answer). + * + * The route is mounted exactly as the plugin mounts it (see smoke.spec.ts). The + * provider/model assertion is the point of the first case: the suggestion must + * read the SESSION's folded `request/header`, not replay the deprecated + * full-log snapshot it used to reverse-scan. + */ +import { describe, expect, it } from 'vitest' +import { spawnSync } from 'node:child_process' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm' +import { apply } from '../src/index.ts' +import type { SidebarWebRoute, SidebarWebUpgradeRoute } from '../src/context-types.ts' + +/** Fixture commit identity, confined to this process: no git config is touched. */ +const FIXTURE_IDENTITY = { + GIT_AUTHOR_NAME: 'dsh-better-sidebar-test', + GIT_AUTHOR_EMAIL: 'test@dsh.invalid', + GIT_COMMITTER_NAME: 'dsh-better-sidebar-test', + GIT_COMMITTER_EMAIL: 'test@dsh.invalid', +} + +/** Run one git command (throws on a non-zero exit). */ +function gitRun(cwd: string, args: string[]): string { + const result = spawnSync('git', ['-C', cwd, '--no-pager', '-c', 'color.ui=false', ...args], { + encoding: 'utf8', + env: { ...process.env, ...FIXTURE_IDENTITY }, + }) + if (result.status !== 0) throw new Error(result.stderr || `git ${args[0] ?? ''} exited with ${String(result.status)}`) + return result.stdout +} + +/** A repo on `main` with one commit. */ +function makeRepo(): string { + const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-remote-')) + gitRun(dir, ['init', '-q']) + // Pin the eol policy: Git for Windows defaults to core.autocrlf=true, which + // would smudge the byte-exact diff assertions below. + gitRun(dir, ['config', 'core.autocrlf', 'false']) + gitRun(dir, ['checkout', '-q', '-b', 'main']) + writeFileSync(join(dir, 'a.txt'), 'one\ntwo\n') + gitRun(dir, ['add', '-A']) + gitRun(dir, ['commit', '-q', '-m', 'base']) + return dir +} + +/** A working clone, a bare `origin` it tracks, and a peer clone of the same remote. */ +interface RemoteFixture { + /** The scratch directory holding all three (the only thing to clean up). */ + scratch: string + origin: string + work: string + peer: string +} + +function makeRemoteFixture(): RemoteFixture { + const scratch = mkdtempSync(join(tmpdir(), 'dsh-sidebar-origin-')) + const origin = join(scratch, 'origin.git') + const work = join(scratch, 'work') + const peer = join(scratch, 'peer') + gitRun(scratch, ['init', '-q', '--bare', origin]) + // A bare repo's HEAD defaults to the machine's init.defaultBranch, and a + // clone whose HEAD names a branch that does not exist yet checks out + // NOTHING. Pin it so both clones start on the branch the tests push. + gitRun(origin, ['symbolic-ref', 'HEAD', 'refs/heads/main']) + gitRun(scratch, ['clone', '-q', origin, work]) + gitRun(work, ['config', 'core.autocrlf', 'false']) + writeFileSync(join(work, 'a.txt'), 'one\n') + gitRun(work, ['add', '-A']) + gitRun(work, ['commit', '-q', '-m', 'base']) + gitRun(work, ['push', '-q', '-u', 'origin', 'main']) + gitRun(scratch, ['clone', '-q', origin, peer]) + gitRun(peer, ['config', 'core.autocrlf', 'false']) + return { scratch, origin, work, peer } +} + +/** One `llm.stream` answer: the chunks that fake adapter replies with. */ +type StreamAnswer = (options: GenerateOptions) => StreamChunk[] + +/** A stream that answers with `text`, framed the way a real adapter frames it. */ +function textStream(text: string): StreamChunk[] { + return [ + { type: 'block-start', index: 0, blockType: 'text' }, + { type: 'text-delta', index: 0, text }, + { type: 'block-end', index: 0, block: { type: 'text', text } }, + { type: 'finish', reason: { kind: 'stop' } }, + ] +} + +/** + * Mount the plugin's `/sidebar/api` route against a minimal fake context. + * `stream` answers every LLM call; `requestHeader` is the session's folded + * header the suggestion reads its route from (undefined = no header yet). The + * session carries NO header cwd on purpose: the payload's cwd must win, which + * is how the real client addresses a session's workspace. + */ +function mount(options: { + stream?: StreamAnswer + requestHeader?: () => unknown + llm?: boolean + session?: boolean +} = {}): { route: SidebarWebRoute; calls: GenerateOptions[] } { + const routes: SidebarWebRoute[] = [] + const calls: GenerateOptions[] = [] + const respond = options.stream ?? (() => textStream('feat: suggested')) + const llm = { + stream(streamOptions: GenerateOptions): AsyncIterable { + calls.push(streamOptions) + const chunks = respond(streamOptions) + return (async function* () { for (const chunk of chunks) yield chunk })() + }, + } + const ctx = { + webRuntime: { trustedHosts: [] }, + webServer: { + register: (route: SidebarWebRoute) => { routes.push(route); return () => {} }, + registerUpgrade: (_route: SidebarWebUpgradeRoute) => () => {}, + }, + sessions: { + get: (_id: string) => (options.session === false + ? undefined + : { + header: {}, + snapshotEvents: () => [], + requestHeader: options.requestHeader ?? (() => ({ config: { provider: 'test-provider', model: 'test-model' } })), + }), + }, + tools: { register: () => () => {} }, + // The vendored cordis runs registration effects immediately. + effect: (fn: () => void | (() => void)) => { fn() }, + inject: () => () => {}, + on: () => () => {}, + get: (key: string) => (key === 'llm' && options.llm !== false ? llm : undefined), + } + apply(ctx as never) + const route = routes.find(entry => entry.path === '/sidebar/api') + if (route === undefined) throw new Error('the /sidebar/api route was not registered') + return { route, calls } +} + +interface Invoked { + ok: boolean + status: number + value?: T + error?: { code?: string; message: string } +} + +async function invoke(route: SidebarWebRoute, method: string, payload: unknown): Promise> { + const body = Buffer.from(JSON.stringify(payload)) + const req = { + method: 'POST', + url: `/sidebar/api/${method}`, + headers: { host: '127.0.0.1:3080' }, + [Symbol.asyncIterator]: async function* () { yield body }, + } as never + const out = { status: 200, body: '' } + const res = { + writeHead: (status: number) => { out.status = status }, + end: (chunk: unknown) => { out.body += String(chunk ?? '') }, + } as never + await route.handler(req, res) + return { ...JSON.parse(out.body) as Invoked, status: out.status } +} + +/** The prompt the last LLM call carried (the user message's text blocks). */ +function promptOf(options: GenerateOptions): string { + const first = options.messages[0] + if (first === undefined) return '' + return first.content.map(block => (block.type === 'text' ? block.text : '')).join('') +} + +describe('git remote routes (real repository + bare origin)', () => { + it('pushes the current branch to its upstream', async () => { + const fixture = makeRemoteFixture() + try { + writeFileSync(join(fixture.work, 'a.txt'), 'one\ntwo\n') + gitRun(fixture.work, ['add', '-A']) + gitRun(fixture.work, ['commit', '-q', '-m', 'second']) + const local = gitRun(fixture.work, ['rev-parse', 'main']).trim() + + const { route } = mount() + const result = await invoke(route, 'git.push', { sessionId: 's-push', cwd: fixture.work }) + + expect(result).toMatchObject({ ok: true, value: { ok: true } }) + // The remote actually moved — the route ran a real `git push`. + expect(gitRun(fixture.origin, ['rev-parse', 'main']).trim()).toBe(local) + } finally { + rmSync(fixture.scratch, { recursive: true, force: true }) + } + }) + + it('reports git\'s own failure for a branch with no upstream', async () => { + const dir = makeRepo() + try { + const { route } = mount() + const result = await invoke(route, 'git.push', { sessionId: 's-noup', cwd: dir }) + + // git-error, never a silent success: the panel shows the message and the + // user sets the tracking in a terminal. + expect(result.ok).toBe(false) + expect(result.error?.code).toBe('git-error') + expect(result.error?.message ?? '').not.toBe('') + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('pulls a fast-forward onto the peer\'s commit', async () => { + const fixture = makeRemoteFixture() + try { + writeFileSync(join(fixture.peer, 'b.txt'), 'from peer\n') + gitRun(fixture.peer, ['add', '-A']) + gitRun(fixture.peer, ['commit', '-q', '-m', 'peer work']) + gitRun(fixture.peer, ['push', '-q', 'origin', 'main']) + + const { route } = mount() + const pulled = await invoke(route, 'git.pull', { sessionId: 's-pull', cwd: fixture.work }) + + expect(pulled).toMatchObject({ ok: true, value: { ok: true } }) + expect(readFileSync(join(fixture.work, 'b.txt'), 'utf8')).toBe('from peer\n') + } finally { + rmSync(fixture.scratch, { recursive: true, force: true }) + } + }) + + it('refuses a diverged branch instead of merging, leaving no merge to resolve', async () => { + const fixture = makeRemoteFixture() + try { + writeFileSync(join(fixture.work, 'local.txt'), 'local\n') + gitRun(fixture.work, ['add', '-A']) + gitRun(fixture.work, ['commit', '-q', '-m', 'local work']) + writeFileSync(join(fixture.peer, 'peer.txt'), 'peer\n') + gitRun(fixture.peer, ['add', '-A']) + gitRun(fixture.peer, ['commit', '-q', '-m', 'peer work']) + gitRun(fixture.peer, ['push', '-q', 'origin', 'main']) + const headBefore = gitRun(fixture.work, ['rev-parse', 'HEAD']).trim() + + const { route } = mount() + const diverged = await invoke(route, 'git.pull', { sessionId: 's-pull', cwd: fixture.work }) + + // --ff-only: the failure is the point. A merge here would strand a + // headless panel inside an editor nobody can answer. + expect(diverged.ok).toBe(false) + expect(diverged.error?.code).toBe('git-error') + expect(gitRun(fixture.work, ['rev-parse', 'HEAD']).trim()).toBe(headBefore) + expect(gitRun(fixture.work, ['status', '--porcelain'])).toBe('') + expect(() => readFileSync(join(fixture.work, '.git', 'MERGE_HEAD'), 'utf8')).toThrow() + } finally { + rmSync(fixture.scratch, { recursive: true, force: true }) + } + }) +}) + +describe('git.suggest-message', () => { + it('prompts with the STAGED diff on the session\'s own provider/model route', async () => { + const dir = makeRepo() + try { + writeFileSync(join(dir, 'a.txt'), 'one\nSTAGED\n') + gitRun(dir, ['add', 'a.txt']) + writeFileSync(join(dir, 'a.txt'), 'one\nSTAGED\nUNSTAGED\n') + + const { route, calls } = mount() + const result = await invoke<{ message: string }>(route, 'git.suggest-message', { + sessionId: 's-suggest', cwd: dir, language: 'en', + }) + + expect(result).toMatchObject({ ok: true, value: { message: 'feat: suggested' } }) + expect(calls).toHaveLength(1) + const call = calls[0]! + // The route comes from the session's folded header. + expect(call.provider).toBe('test-provider') + expect(call.model).toBe('test-model') + expect(call.maxTokens).toBe(200) + // Staged wins: that is exactly what `git commit` would record, so the + // unstaged edit must not leak into the prompt. + const prompt = promptOf(call) + expect(prompt).toContain('+STAGED') + expect(prompt).not.toContain('+UNSTAGED') + expect(prompt).toContain('a.txt') + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('falls back to the unstaged diff, then to a bare file list for untracked-only', async () => { + const dir = makeRepo() + try { + writeFileSync(join(dir, 'a.txt'), 'one\nWORKTREE\n') + const unstaged = mount() + const first = await invoke<{ message: string }>(unstaged.route, 'git.suggest-message', { sessionId: 's', cwd: dir }) + expect(first.ok).toBe(true) + expect(promptOf(unstaged.calls[0]!)).toContain('+WORKTREE') + + // Only an untracked file left: `git diff` has nothing to say, so the + // prompt carries the file list alone. + gitRun(dir, ['checkout', '--', 'a.txt']) + writeFileSync(join(dir, 'brand-new.txt'), 'new\n') + const untracked = mount() + const second = await invoke<{ message: string }>(untracked.route, 'git.suggest-message', { sessionId: 's', cwd: dir }) + expect(second.ok).toBe(true) + const prompt = promptOf(untracked.calls[0]!) + expect(prompt).toContain('brand-new.txt') + expect(prompt).not.toContain('@@') + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('truncates a diff larger than the prompt budget', async () => { + const dir = makeRepo() + try { + // ~40K of changed lines: well past the 12 000-character budget. + const line = 'x'.repeat(80) + writeFileSync(join(dir, 'big.txt'), Array.from({ length: 500 }, (_value, index) => `${String(index)}-${line}`).join('\n')) + gitRun(dir, ['add', 'big.txt']) + + const { route, calls } = mount() + const result = await invoke<{ message: string }>(route, 'git.suggest-message', { sessionId: 's', cwd: dir }) + + expect(result.ok).toBe(true) + const prompt = promptOf(calls[0]!) + expect(prompt).toContain('…(diff truncated)') + // 12 000 chars of diff + the wrapper text, never the whole 40K file. + expect(prompt.length).toBeLessThan(13_500) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('refuses an empty pending set without calling the model', async () => { + const dir = makeRepo() + try { + const { route, calls } = mount() + const result = await invoke(route, 'git.suggest-message', { sessionId: 's', cwd: dir }) + + expect(result.ok).toBe(false) + // The client renders its own copy for this code, so the code — not a + // generic git failure — is the contract. + expect(result.error?.code).toBe('git-suggest-empty') + expect(result.status).toBe(400) + expect(calls).toHaveLength(0) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('degrades to 503 for a session with no request header and for an absent LLM service', async () => { + const dir = makeRepo() + try { + writeFileSync(join(dir, 'a.txt'), 'one\nDIRTY\n') + + // A cold session: the fold has no header yet, so there is no route to run on. + const noHeader = mount({ requestHeader: () => undefined }) + const first = await invoke(noHeader.route, 'git.suggest-message', { sessionId: 's', cwd: dir }) + expect(first.ok).toBe(false) + expect(first.error?.code).toBe('git-suggest-error') + expect(first.status).toBe(503) + expect(noHeader.calls).toHaveLength(0) + + // A deployment without the LLM surface: a clean 503, never a TypeError. + const noLlm = mount({ llm: false }) + const second = await invoke(noLlm.route, 'git.suggest-message', { sessionId: 's', cwd: dir }) + expect(second.ok).toBe(false) + expect(second.error?.code).toBe('git-suggest-error') + expect(second.status).toBe(503) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('surfaces a provider stream failure and an empty answer as distinct errors', async () => { + const dir = makeRepo() + try { + writeFileSync(join(dir, 'a.txt'), 'one\nDIRTY\n') + + // `llm.stream()` reports an adapter failure as a terminal finish chunk + // rather than throwing: unchecked, the provider's real reason would be + // reported as "the model returned an empty message". + const failed = mount({ + stream: () => [{ type: 'finish', reason: { kind: 'error', failure: { code: 'RATE_LIMIT', message: 'provider said no' } } }], + }) + const first = await invoke(failed.route, 'git.suggest-message', { sessionId: 's', cwd: dir }) + expect(first.ok).toBe(false) + expect(first.status).toBe(502) + expect(first.error?.message).toBe('provider said no') + + const empty = mount({ stream: () => textStream(' ') }) + const second = await invoke(empty.route, 'git.suggest-message', { sessionId: 's', cwd: dir }) + expect(second.ok).toBe(false) + expect(second.status).toBe(500) + expect(second.error?.message).toContain('empty') + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('asks for the panel language, defaulting to en for anything else', async () => { + const dir = makeRepo() + try { + writeFileSync(join(dir, 'a.txt'), 'one\nDIRTY\n') + const zh = mount() + await invoke(zh.route, 'git.suggest-message', { sessionId: 's', cwd: dir, language: 'zh' }) + expect(zh.calls[0]!.system).toContain('Conventional Commits') + expect(promptOf(zh.calls[0]!)).toContain('改动的文件') + + const other = mount() + await invoke(other.route, 'git.suggest-message', { sessionId: 's', cwd: dir, language: 'ja' }) + expect(promptOf(other.calls[0]!)).toContain('Changed files') + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/tests/git-suggest-ui.spec.tsx b/tests/git-suggest-ui.spec.tsx new file mode 100644 index 00000000..7cd49ffd --- /dev/null +++ b/tests/git-suggest-ui.spec.tsx @@ -0,0 +1,220 @@ +/** + * The commit bar's two new affordances: the sparkle button that asks the host + * for a commit message, and the Push / Pull row under the message box. + * + * These pin the WIRING the host routes cannot see — which args each action + * sends (scope, locale, selected checkout), that a suggestion only FILLS the + * box instead of committing, and that every failure lands on the bar's one + * status line (`changes-tab.spec.tsx` pins that channel's placement). + * + * The copy assertions go through `t()`, so they follow the active locale + * rather than pinning one language's strings. + */ +// @vitest-environment jsdom +import { afterEach, beforeEach, 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, type GitWorktree } from '../src/client/api.ts' +import { t } from '../src/client/locales.ts' + +import { setupReactAct } from './test-utils.ts' +setupReactAct() + +const MAIN = 'C:/repo/main' + +/** Install one inventory whose status carries `entries`. */ +function mockGit(entries: Array<{ path: string; xy: string }>): void { + vi.spyOn(api, 'gitWorktrees').mockResolvedValue([ + { path: MAIN, branch: 'main', current: true, changes: entries.length }, + ] as GitWorktree[]) + vi.spyOn(api, 'gitStatus').mockResolvedValue({ isRepo: true, branch: 'main', entries } as GitStatusResult) + vi.spyOn(api, 'gitBranch').mockResolvedValue({ current: 'main', names: ['main'] }) + vi.spyOn(api, 'gitLog').mockResolvedValue([]) +} + +function mountGit(root: Root): void { + act(() => { + root.render(createElement(GitLens, { + scope: { sessionId: 'session', cwd: MAIN }, + store: createSidebarStore(), + onOpenFile: () => {}, + onPreview: () => {}, + selectedRef: null, + visible: true, + refreshTick: 0, + })) + }) +} + +async function flushEffects(): Promise { + // The refresh chain (inventory → branches/log → state) is several promise + // hops deep, so a shallow flush asserts on rows still in flight. + for (let round = 0; round < 5; round += 1) await act(async () => { await Promise.resolve() }) +} + +function makeRoot(): { container: HTMLDivElement; root: Root } { + const container = document.createElement('div') + document.body.append(container) + return { container, root: createRoot(container) } +} + +/** The sparkle button (its accessible name is the generate/suggesting copy). */ +function suggestButton(container: HTMLElement): HTMLButtonElement { + const button = container.querySelector(`button[aria-label="${t('generateCommitMessage')}"]`) + if (button === null) throw new Error('the commit-message suggestion button is not rendered') + return button +} + +/** One text button of the commit bar, by its label. */ +function textButton(container: HTMLElement, label: string): HTMLButtonElement { + const button = [...container.querySelectorAll('button')] + .find(candidate => candidate.textContent === label) + if (button === undefined) throw new Error(`no commit-bar button labelled "${label}"`) + return button +} + +/** The commit message box. */ +function commitInput(container: HTMLElement): HTMLInputElement { + const input = container.querySelector(`input[placeholder="${t('commitPlaceholder')}"]`) + if (input === null) throw new Error('the commit message box is not rendered') + return input +} + +/** One rendered error line of the commit bar. */ +function errorLine(container: HTMLElement, text: string): HTMLElement | undefined { + return [...container.querySelectorAll('[role="alert"]')] + .find(node => (node.textContent ?? '').includes(text)) +} + +beforeEach(() => { + Object.defineProperty(globalThis.navigator, 'language', { value: 'zh-CN', configurable: true }) +}) + +afterEach(() => { + vi.restoreAllMocks() + document.body.innerHTML = '' +}) + +describe('GitLens commit bar: AI suggestion and remote actions', () => { + it('offers the suggestion only while something is pending, then fills the box', async () => { + mockGit([{ path: 'src/a.ts', xy: ' M' }]) + const suggest = vi.spyOn(api, 'gitSuggestMessage').mockResolvedValue({ message: 'feat: from the model' }) + const commit = vi.spyOn(api, 'gitCommit').mockResolvedValue({ ok: true }) + + const { container, root } = makeRoot() + try { + mountGit(root) + await flushEffects() + + await act(async () => { suggestButton(container).click() }) + await flushEffects() + + // The panel's own locale and selected checkout ride the call; the scope + // is the live one every other git call uses. The first inventory pass + // selects the clean primary checkout, so that is what travels. + expect(suggest).toHaveBeenCalledWith( + expect.objectContaining({ sessionId: 'session', cwd: MAIN }), + 'zh', + MAIN, + ) + // The suggestion FILLS the box — it is a draft the user still edits and + // commits, never a commit of its own. + expect(commitInput(container).value).toBe('feat: from the model') + expect(commit).not.toHaveBeenCalled() + } finally { + act(() => { root.unmount() }) + container.remove() + } + }) + + it('disables the suggestion button when the tree is clean', async () => { + mockGit([]) + + const { container, root } = makeRoot() + try { + mountGit(root) + await flushEffects() + + expect(suggestButton(container).disabled).toBe(true) + } finally { + act(() => { root.unmount() }) + container.remove() + } + }) + + it('asks for English when the panel is not Chinese', async () => { + Object.defineProperty(globalThis.navigator, 'language', { value: 'en-US', configurable: true }) + mockGit([{ path: 'src/a.ts', xy: ' M' }]) + const suggest = vi.spyOn(api, 'gitSuggestMessage').mockResolvedValue({ message: 'feat: english' }) + + const { container, root } = makeRoot() + try { + mountGit(root) + await flushEffects() + + await act(async () => { suggestButton(container).click() }) + await flushEffects() + + expect(suggest).toHaveBeenCalledWith(expect.anything(), 'en', MAIN) + } finally { + act(() => { root.unmount() }) + container.remove() + } + }) + + it('separates an empty pending set from a provider failure on the bar\'s status line', async () => { + mockGit([{ path: 'src/a.ts', xy: ' M' }]) + vi.spyOn(api, 'gitSuggestMessage') + // The host's own precondition code: the client renders its dedicated copy + // rather than prefixing a provider message nobody needs. + .mockRejectedValueOnce(new SidebarApiError('git-suggest-empty', 'no pending changes')) + .mockRejectedValueOnce(new SidebarApiError('git-suggest-error', 'the harness LLM service is unavailable')) + + const { container, root } = makeRoot() + try { + mountGit(root) + await flushEffects() + + await act(async () => { suggestButton(container).click() }) + await flushEffects() + expect(errorLine(container, t('suggestCommitEmpty'))).toBeDefined() + + await act(async () => { suggestButton(container).click() }) + await flushEffects() + expect(errorLine(container, `${t('suggestCommitError')}: the harness LLM service is unavailable`)).toBeDefined() + + // The box keeps whatever it held: a failed suggestion never commits or clears. + expect(commitInput(container).value).toBe('') + } finally { + act(() => { root.unmount() }) + container.remove() + } + }) + + it('pushes and pulls the selected checkout, reporting failures on the same status line', async () => { + mockGit([{ path: 'src/a.ts', xy: ' M' }]) + const push = vi.spyOn(api, 'gitPush').mockResolvedValue({ ok: true }) + const pull = vi.spyOn(api, 'gitPull').mockRejectedValue(new Error('Not possible to fast-forward')) + + const { container, root } = makeRoot() + try { + mountGit(root) + await flushEffects() + + await act(async () => { textButton(container, t('push')).click() }) + await flushEffects() + expect(push).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'session' }), MAIN) + + await act(async () => { textButton(container, t('pull')).click() }) + await flushEffects() + expect(pull).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'session' }), MAIN) + expect(errorLine(container, `${t('pullError')}: Not possible to fast-forward`)).toBeDefined() + } finally { + act(() => { root.unmount() }) + container.remove() + } + }) +})