gitCommitMessageGenerator.test.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { GitDiffResult, GitFileChange, ZCodeWorkspaceGenerateTextParams } from "@zcode/shared";
  3. type ZCodeSelection = ZCodeWorkspaceGenerateTextParams["selection"];
  4. import {
  5. GitCommitMessageGenerationError,
  6. GitCommitMessageGenerator,
  7. } from "../src/git/gitCommitMessageGenerator.js";
  8. const DEFAULT_SELECTION: ZCodeSelection = {
  9. providerId: "openai-compatible",
  10. modelId: "test-model",
  11. };
  12. function createTextGenerator(responseText: string) {
  13. return {
  14. generateText: vi.fn(async (params: { selection: ZCodeSelection }) => ({
  15. text: responseText,
  16. selection: params.selection,
  17. })),
  18. };
  19. }
  20. function createGenerator(params: { responseText: string; selection?: ZCodeSelection }): {
  21. generator: GitCommitMessageGenerator;
  22. textGenerator: ReturnType<typeof createTextGenerator>;
  23. } {
  24. const textGenerator = createTextGenerator(params.responseText);
  25. const selection = params.selection ?? DEFAULT_SELECTION;
  26. return {
  27. generator: new GitCommitMessageGenerator({
  28. textGenerator,
  29. currentModelProvider: {
  30. async readCurrentModel() {
  31. return selection;
  32. },
  33. },
  34. }),
  35. textGenerator,
  36. };
  37. }
  38. function createFileChange(overrides?: Partial<GitFileChange>): GitFileChange {
  39. return {
  40. path: "/repo/packages/ui/src/GitActionMenu.tsx",
  41. repoRelativePath: "packages/ui/src/GitActionMenu.tsx",
  42. workspaceRelativePath: "packages/ui/src/GitActionMenu.tsx",
  43. kind: "modified",
  44. section: "unstaged",
  45. added: 12,
  46. removed: 4,
  47. isStaged: false,
  48. isUntracked: false,
  49. isConflicted: false,
  50. ...overrides,
  51. };
  52. }
  53. function createDiff(overrides?: Partial<GitDiffResult>): GitDiffResult {
  54. return {
  55. path: "packages/ui/src/GitActionMenu.tsx",
  56. availability: "patch",
  57. patch: "@@ -1 +1 @@\n-old\n+new",
  58. beforeContent: null,
  59. afterContent: null,
  60. ...overrides,
  61. };
  62. }
  63. describe("GitCommitMessageGenerator", () => {
  64. it("returns a valid Conventional Commit message from the selected model", async () => {
  65. const { generator, textGenerator } = createGenerator({
  66. responseText: "```text\nfix(git): generate commit messages\n```",
  67. });
  68. const result = await generator.generate({
  69. workspacePath: "/repo",
  70. workspaceIdentity: "ssh://host/repo",
  71. branchName: "main",
  72. files: [createFileChange()],
  73. diffs: [createDiff()],
  74. });
  75. expect(result).toEqual({
  76. message: "fix(git): generate commit messages",
  77. providerId: "openai-compatible",
  78. model: "test-model",
  79. });
  80. expect(textGenerator.generateText).toHaveBeenCalledWith(
  81. expect.objectContaining({
  82. workspacePath: "/repo",
  83. workspaceIdentity: "ssh://host/repo",
  84. selection: DEFAULT_SELECTION,
  85. querySource: "git_commit_message",
  86. }),
  87. );
  88. expect(textGenerator.generateText.mock.calls[0]?.[0]).not.toHaveProperty("maxOutputTokens");
  89. });
  90. it("preserves the complete selected model until the auxiliary execution boundary", async () => {
  91. const selectedSelection: ZCodeSelection = {
  92. providerId: "openai-compatible",
  93. modelId: "deepseek-v4-flash",
  94. options: { reasoningLevel: "max" },
  95. };
  96. const { generator, textGenerator } = createGenerator({
  97. selection: selectedSelection,
  98. responseText: "fix(git): generate message",
  99. });
  100. await generator.generate({
  101. workspacePath: "/repo",
  102. branchName: "main",
  103. files: [createFileChange()],
  104. diffs: [createDiff()],
  105. });
  106. expect(textGenerator.generateText).toHaveBeenCalledWith(
  107. expect.objectContaining({
  108. selection: {
  109. providerId: selectedSelection.providerId,
  110. modelId: selectedSelection.modelId,
  111. options: { reasoningLevel: "max" },
  112. },
  113. }),
  114. );
  115. });
  116. it("adds Chinese as the current commit message language", async () => {
  117. const { generator, textGenerator } = createGenerator({
  118. responseText: "fix(git): 生成提交消息",
  119. });
  120. await generator.generate({
  121. workspacePath: "/repo",
  122. branchName: "main",
  123. locale: "zh-CN",
  124. files: [],
  125. diffs: [],
  126. });
  127. const prompt = textGenerator.generateText.mock.calls[0]?.[0].prompt;
  128. expect(prompt).toContain("Current language: Chinese");
  129. expect(prompt).toContain("- Write the subject and any body in the current language.");
  130. });
  131. it("falls back to English when runtime locale is unavailable", async () => {
  132. const dateTimeFormatSpy = vi.spyOn(Intl, "DateTimeFormat").mockImplementation(() => {
  133. throw new Error("locale unavailable");
  134. });
  135. const { generator, textGenerator } = createGenerator({
  136. responseText: "fix(git): generate message",
  137. });
  138. try {
  139. await generator.generate({
  140. workspacePath: "/repo",
  141. branchName: "main",
  142. files: [],
  143. diffs: [],
  144. });
  145. } finally {
  146. dateTimeFormatSpy.mockRestore();
  147. }
  148. const prompt = textGenerator.generateText.mock.calls[0]?.[0].prompt;
  149. expect(prompt).toContain("Current language: English");
  150. });
  151. it("clips diff excerpts before calling the text generator", async () => {
  152. const { generator, textGenerator } = createGenerator({
  153. responseText: "fix(git): generate message",
  154. });
  155. await generator.generate({
  156. workspacePath: "/repo",
  157. branchName: "main",
  158. files: [createFileChange()],
  159. diffs: [createDiff({ patch: "a".repeat(3_000) })],
  160. });
  161. const prompt = textGenerator.generateText.mock.calls[0]?.[0].prompt;
  162. expect(prompt).toContain("...diff truncated...");
  163. expect(prompt.length).toBeLessThan(3_000);
  164. });
  165. it("includes current session conversation context in the prompt", async () => {
  166. const { generator, textGenerator } = createGenerator({
  167. responseText: "fix(git): 生成提交消息",
  168. });
  169. await generator.generate({
  170. workspacePath: "/repo",
  171. branchName: "main",
  172. locale: "zh-CN",
  173. files: [createFileChange()],
  174. diffs: [createDiff()],
  175. conversationContext: {
  176. sessionId: "session-1",
  177. omittedMessageCount: 2,
  178. messages: [
  179. {
  180. role: "user",
  181. content: "把自动生成内容和自动提交分开",
  182. },
  183. {
  184. role: "assistant",
  185. content: "已改为先生成提交信息,再由用户手动提交。",
  186. },
  187. ],
  188. },
  189. });
  190. const prompt = textGenerator.generateText.mock.calls[0]?.[0].prompt;
  191. expect(prompt).toContain("Current session conversation context:");
  192. expect(prompt).toContain("- 2 earlier messages omitted");
  193. expect(prompt).toContain("User: 把自动生成内容和自动提交分开");
  194. expect(prompt).toContain("Assistant: 已改为先生成提交信息,再由用户手动提交。");
  195. expect(prompt).toContain(
  196. "- Do not mention the conversation, chat, prompt, or user request explicitly.",
  197. );
  198. });
  199. it("throws a short invalid-output error when the model repeats the prompt", async () => {
  200. const { generator } = createGenerator({
  201. responseText: "Generate a Git commit message based on the workspace changes described below.",
  202. });
  203. await expect(
  204. generator.generate({
  205. workspacePath: "/repo",
  206. branchName: "main",
  207. files: [],
  208. diffs: [],
  209. }),
  210. ).rejects.toMatchObject({
  211. name: "GitCommitMessageGenerationError",
  212. reason: "invalid-output",
  213. message: "模型没有返回可用的 Conventional Commit 提交消息。",
  214. } satisfies Partial<GitCommitMessageGenerationError>);
  215. });
  216. it("throws model-unavailable when current model is missing", async () => {
  217. const textGenerator = createTextGenerator("fix(git): generate message");
  218. const generator = new GitCommitMessageGenerator({
  219. textGenerator,
  220. currentModelProvider: {
  221. async readCurrentModel() {
  222. return null;
  223. },
  224. },
  225. });
  226. await expect(
  227. generator.generate({
  228. workspacePath: "/repo",
  229. branchName: "main",
  230. files: [],
  231. diffs: [],
  232. }),
  233. ).rejects.toMatchObject({
  234. reason: "model-unavailable",
  235. message: "未读取到当前模型。",
  236. } satisfies Partial<GitCommitMessageGenerationError>);
  237. expect(textGenerator.generateText).not.toHaveBeenCalled();
  238. });
  239. });