plugin-git-manager 1.2.28 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +58 -40
  2. package/dist/client/941.1793e67472872992.js +10 -0
  3. package/dist/client/index.js +1 -1
  4. package/dist/client-v2/941.b0d55429cd053f32.js +10 -0
  5. package/dist/client-v2/index.js +1 -1
  6. package/dist/locale/en-US.json +90 -1
  7. package/dist/locale/vi-VN.json +90 -1
  8. package/dist/locale/zh-CN.json +90 -1
  9. package/dist/node_modules/simple-git/package.json +1 -1
  10. package/dist/node_modules/zod/package.json +1 -1
  11. package/dist/server/actions/review-cutover.js +137 -0
  12. package/dist/server/actions/review.js +132 -43
  13. package/dist/server/actions/role-permissions.js +1 -0
  14. package/dist/server/ai-tools.js +8 -9
  15. package/dist/server/collections/gitCodeReviews.js +10 -0
  16. package/dist/server/collections/gitReviewCutover.js +44 -0
  17. package/dist/server/collections/gitReviewFlows.js +3 -0
  18. package/dist/server/collections/gitReviewInbox.js +51 -0
  19. package/dist/server/collections/gitReviewProjects.js +43 -0
  20. package/dist/server/collections/gitReviewRequests.js +56 -0
  21. package/dist/server/index.js +8 -2
  22. package/dist/server/plugin.js +51 -16
  23. package/dist/server/poller.js +54 -34
  24. package/dist/server/repository-access.js +23 -5
  25. package/dist/server/request-method-policy.js +2 -1
  26. package/dist/server/review-control-access.js +79 -0
  27. package/dist/server/services/legacy-post-service.js +412 -0
  28. package/dist/server/services/review-service.js +1451 -0
  29. package/dist/server/services/review-source.js +325 -0
  30. package/package.json +2 -2
  31. package/src/client/__tests__/CommitHistory.test.tsx +79 -0
  32. package/src/client/__tests__/ReviewHistory.test.tsx +126 -0
  33. package/src/client/__tests__/RunReviewButton.test.tsx +46 -35
  34. package/src/client/__tests__/workflowRoutes.test.ts +65 -0
  35. package/src/client/components/CommitHistory.tsx +61 -6
  36. package/src/client/components/ReviewFlows.tsx +90 -41
  37. package/src/client/components/ReviewHistory.tsx +245 -15
  38. package/src/client/components/RunReviewButton.tsx +12 -136
  39. package/src/client/workflowRoutes.ts +42 -0
  40. package/src/locale/en-US.json +90 -1
  41. package/src/locale/vi-VN.json +90 -1
  42. package/src/locale/zh-CN.json +90 -1
  43. package/src/server/__tests__/repository-access.test.ts +11 -3
  44. package/src/server/__tests__/review-service.integration.test.ts +1263 -0
  45. package/src/server/__tests__/review.test.ts +37 -98
  46. package/src/server/actions/review-cutover.ts +121 -0
  47. package/src/server/actions/review.ts +148 -38
  48. package/src/server/actions/role-permissions.ts +10 -0
  49. package/src/server/ai-tools.ts +23 -8
  50. package/src/server/collections/gitCodeReviews.ts +19 -0
  51. package/src/server/collections/gitReviewCutover.ts +23 -0
  52. package/src/server/collections/gitReviewFlows.ts +12 -0
  53. package/src/server/collections/gitReviewInbox.ts +30 -0
  54. package/src/server/collections/gitReviewProjects.ts +22 -0
  55. package/src/server/collections/gitReviewRequests.ts +35 -0
  56. package/src/server/index.ts +12 -0
  57. package/src/server/plugin.ts +43 -6
  58. package/src/server/poller.ts +54 -40
  59. package/src/server/repository-access.ts +32 -2
  60. package/src/server/request-method-policy.ts +1 -0
  61. package/src/server/review-control-access.ts +71 -0
  62. package/src/server/services/__tests__/review-source.test.ts +226 -0
  63. package/src/server/services/legacy-post-service.ts +550 -0
  64. package/src/server/services/review-service.ts +1899 -0
  65. package/src/server/services/review-source.ts +359 -0
  66. package/dist/client/900.a48beac7e2ebee7d.js +0 -10
  67. package/dist/client-v2/900.e6155002a9c97e7f.js +0 -10
@@ -0,0 +1,325 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var review_source_exports = {};
28
+ __export(review_source_exports, {
29
+ assertCurrentMrHead: () => assertCurrentMrHead,
30
+ findLegacyPublishedReview: () => findLegacyPublishedReview,
31
+ findPublishedReview: () => findPublishedReview,
32
+ publishPinnedReview: () => publishPinnedReview,
33
+ readPinnedReviewSource: () => readPinnedReviewSource,
34
+ resolveReviewProjectKey: () => resolveReviewProjectKey,
35
+ resolveReviewSource: () => resolveReviewSource
36
+ });
37
+ module.exports = __toCommonJS(review_source_exports);
38
+ var import_crypto = require("crypto");
39
+ var import_git_actions = require("../actions/git-actions");
40
+ var import_get_repo_account = require("../utils/get-repo-account");
41
+ var import_gitlab_url = require("../utils/gitlab-url");
42
+ function object(value) {
43
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
44
+ }
45
+ function text(value) {
46
+ return typeof value === "string" && value ? value : null;
47
+ }
48
+ function sha(value) {
49
+ var _a;
50
+ const result = (_a = text(value)) == null ? void 0 : _a.toLowerCase();
51
+ if (!result || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(result)) {
52
+ throw new Error("Unable to resolve an immutable Git commit");
53
+ }
54
+ return result;
55
+ }
56
+ async function responseJson(url, headers) {
57
+ const response = await fetch(url, { headers, redirect: "error" });
58
+ if (!response.ok) throw new Error(`Git provider request failed (${response.status})`);
59
+ const size = Number(response.headers.get("content-length") || 0);
60
+ if (size > 4e6) throw new Error("Git provider response is too large");
61
+ const body = await response.text();
62
+ if (Buffer.byteLength(body) > 4e6) throw new Error("Git provider response is too large");
63
+ return object(JSON.parse(body));
64
+ }
65
+ async function provider(db, repo) {
66
+ const repoUrl = String(repo.get("repoUrl") || "");
67
+ const account = await (0, import_get_repo_account.getRepoAccount)(db, repo);
68
+ const parsed = (0, import_gitlab_url.parseGitLabProject)(repoUrl);
69
+ const isGitHub = new URL(repoUrl).hostname.toLowerCase() === "github.com";
70
+ if ((account == null ? void 0 : account.provider) === "github" && !isGitHub) throw new Error("Unsupported GitHub origin");
71
+ if (!isGitHub && !(account == null ? void 0 : account.pat)) throw new Error("GitLab account is required");
72
+ const headers = { Accept: "application/json" };
73
+ if (account == null ? void 0 : account.pat)
74
+ headers[isGitHub ? "Authorization" : "PRIVATE-TOKEN"] = isGitHub ? `Bearer ${account.pat}` : account.pat;
75
+ const root = isGitHub ? `https://api.github.com/repos/${parsed.projectPath}` : `${parsed.apiBase}/projects/${parsed.encodedProject}`;
76
+ const project = await responseJson(root, headers);
77
+ const projectId = project.id;
78
+ const canonical = text(isGitHub ? project.html_url : project.web_url);
79
+ if (typeof projectId !== "number" && typeof projectId !== "string" || !canonical) {
80
+ throw new Error("Git provider did not return a canonical project identity");
81
+ }
82
+ const canonicalUrl = new URL(canonical);
83
+ if (canonicalUrl.protocol !== "https:" || canonicalUrl.username || canonicalUrl.password) {
84
+ throw new Error("Invalid canonical project origin");
85
+ }
86
+ const identity = `${isGitHub ? "github" : "gitlab"}:${canonicalUrl.origin.toLowerCase()}:${projectId}`;
87
+ return {
88
+ root,
89
+ headers,
90
+ isGitHub,
91
+ userApi: isGitHub ? "https://api.github.com/user" : `${parsed.apiBase}/user`,
92
+ projectKey: (0, import_crypto.createHash)("sha256").update(identity).digest("hex"),
93
+ pat: (account == null ? void 0 : account.pat) || ""
94
+ };
95
+ }
96
+ async function resolveReviewProjectKey(db, repo) {
97
+ return (await provider(db, repo)).projectKey;
98
+ }
99
+ async function validateCheckoutProject(db, repo, expectedProjectKey) {
100
+ const git = (0, import_git_actions.createGit)((0, import_git_actions.validateLocalPath)(String(repo.get("localPath") || "")));
101
+ let origin;
102
+ try {
103
+ origin = (await git.raw(["remote", "get-url", "origin"])).trim();
104
+ const remote = new URL(origin);
105
+ if (remote.protocol !== "https:" || remote.username || remote.password) throw new Error("Invalid origin");
106
+ } catch {
107
+ throw new Error("Checkout origin is missing or unsupported");
108
+ }
109
+ const checkout = { get: (name) => name === "repoUrl" ? origin : repo.get(name) };
110
+ let projectKey;
111
+ try {
112
+ projectKey = (await provider(db, checkout)).projectKey;
113
+ } catch {
114
+ throw new Error("Checkout origin project could not be verified");
115
+ }
116
+ if (projectKey !== expectedProjectKey) throw new Error("Checkout origin does not match the configured project");
117
+ }
118
+ function safeFolder(value) {
119
+ const folder = value.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
120
+ if (folder.split("/").some((part) => part === ".." || part === ".") || value.includes("\0")) {
121
+ throw new Error("Invalid folder path");
122
+ }
123
+ return folder;
124
+ }
125
+ async function resolveReviewSource(db, repo, input) {
126
+ const remote = await provider(db, repo);
127
+ let headSha;
128
+ let baseSha = null;
129
+ let branch = input.branch || null;
130
+ const folderPath = input.targetType === "folder" ? safeFolder(input.folderPath || "") : null;
131
+ if (input.targetType === "mr") {
132
+ if (!input.mrIid || !Number.isSafeInteger(input.mrIid) || input.mrIid < 1) throw new Error("Invalid merge request");
133
+ const mr = await responseJson(
134
+ `${remote.root}/${remote.isGitHub ? "pulls" : "merge_requests"}/${input.mrIid}`,
135
+ remote.headers
136
+ );
137
+ headSha = sha(remote.isGitHub ? object(mr.head).sha : mr.sha || object(mr.diff_refs).head_sha);
138
+ baseSha = sha(remote.isGitHub ? object(mr.base).sha : object(mr.diff_refs).base_sha);
139
+ branch = text(remote.isGitHub ? object(mr.head).ref : mr.source_branch);
140
+ if (input.headSha && sha(input.headSha) !== headSha)
141
+ throw new Error("Merge request head changed before review admission");
142
+ } else {
143
+ await validateCheckoutProject(db, repo, remote.projectKey);
144
+ const git = (0, import_git_actions.createGit)((0, import_git_actions.validateLocalPath)(String(repo.get("localPath") || "")));
145
+ const ref = input.headSha || (input.targetType === "commit" ? input.commitSha : input.branch || "HEAD");
146
+ if (!ref) throw new Error("Git ref is required");
147
+ (0, import_git_actions.validateRef)(ref);
148
+ headSha = sha((await git.raw(["rev-parse", "--verify", `${ref}^{commit}`])).trim());
149
+ if (input.targetType === "branch") {
150
+ const base = (0, import_git_actions.validateBranch)(String(repo.get("defaultBranch") || "main"));
151
+ const baseCommit = sha((await git.raw(["rev-parse", "--verify", `${base}^{commit}`])).trim());
152
+ baseSha = sha((await git.raw(["merge-base", baseCommit, headSha])).trim());
153
+ }
154
+ }
155
+ return {
156
+ projectKey: remote.projectKey,
157
+ repositoryId: Number(repo.get("id")),
158
+ targetType: input.targetType,
159
+ mrIid: input.targetType === "mr" ? input.mrIid || null : null,
160
+ branch,
161
+ folderPath,
162
+ headSha,
163
+ baseSha
164
+ };
165
+ }
166
+ async function readPinnedReviewSource(db, repo, source) {
167
+ const remote = await provider(db, repo);
168
+ if (remote.projectKey !== source.projectKey) throw new Error("Repository project changed after admission");
169
+ let content = "";
170
+ if (source.targetType === "mr") {
171
+ const base = sha(source.baseSha);
172
+ const head = sha(source.headSha);
173
+ if (remote.isGitHub) {
174
+ const comparison = await responseJson(`${remote.root}/compare/${base}...${head}?per_page=100`, remote.headers);
175
+ const files = comparison.files;
176
+ if (!Array.isArray(files) || files.length >= 300) throw new Error("GitHub comparison is incomplete");
177
+ content = files.map((item) => {
178
+ const file = object(item);
179
+ if (typeof file.filename !== "string" || typeof file.patch !== "string")
180
+ throw new Error("GitHub comparison contains an unavailable patch");
181
+ if (/[\r\n]/.test(file.filename)) throw new Error("GitHub comparison has an unsupported filename");
182
+ return `--- a/${file.filename}
183
+ +++ b/${file.filename}
184
+ ${file.patch}`;
185
+ }).join("\n");
186
+ } else {
187
+ const comparison = await responseJson(
188
+ `${remote.root}/repository/compare?from=${base}&to=${head}`,
189
+ remote.headers
190
+ );
191
+ if (comparison.compare_timeout || comparison.overflow || !Array.isArray(comparison.diffs)) {
192
+ throw new Error("GitLab comparison is incomplete");
193
+ }
194
+ content = comparison.diffs.map((item) => {
195
+ const file = object(item);
196
+ if (file.too_large || file.collapsed || typeof file.diff !== "string")
197
+ throw new Error("GitLab comparison contains an unavailable patch");
198
+ const oldPath = String(file.old_path || "");
199
+ const newPath = String(file.new_path || "");
200
+ if (/[\r\n]/.test(oldPath + newPath)) throw new Error("GitLab comparison has an unsupported filename");
201
+ return `--- a/${oldPath}
202
+ +++ b/${newPath}
203
+ ${file.diff}`;
204
+ }).join("\n");
205
+ }
206
+ } else {
207
+ await validateCheckoutProject(db, repo, source.projectKey);
208
+ const git = (0, import_git_actions.createGit)((0, import_git_actions.validateLocalPath)(String(repo.get("localPath") || "")));
209
+ const head = sha(source.headSha);
210
+ if (source.targetType === "folder") {
211
+ const folder = safeFolder(source.folderPath || "");
212
+ const tree = await git.raw(["ls-tree", "-r", "--name-only", "-z", head, "--", folder || "."]);
213
+ const paths = tree.split("\0").filter(Boolean);
214
+ if (paths.length > 200) throw new Error("Folder contains too many files to review safely");
215
+ for (const path of paths) {
216
+ if (/[\r\n]/.test(path)) throw new Error("Folder contains an unsupported filename");
217
+ const file = await git.raw(["show", `${head}:${path}`]);
218
+ if (file.includes("\0")) throw new Error("Folder contains an unsupported binary file");
219
+ const lines = file.split("\n");
220
+ content += `
221
+ --- /dev/null
222
+ +++ b/${path}
223
+ @@ -0,0 +1,${lines.length} @@
224
+ ${lines.map((line) => `+${line}`).join("\n")}`;
225
+ if (Buffer.byteLength(content) > 2e5) throw new Error("Review context exceeds the size limit");
226
+ }
227
+ } else if (source.targetType === "commit") {
228
+ content = await git.raw(["show", "--format=", "--no-ext-diff", "--no-color", head]);
229
+ } else {
230
+ content = await git.raw(["diff", "--no-ext-diff", "--no-color", sha(source.baseSha), head, "--"]);
231
+ }
232
+ }
233
+ if (Buffer.byteLength(content) > 2e5) throw new Error("Review context exceeds the size limit");
234
+ return remote.pat ? content.split(remote.pat).join("[REDACTED]") : content;
235
+ }
236
+ async function assertCurrentMrHead(db, repo, source) {
237
+ const current = await resolveReviewSource(db, repo, { targetType: "mr", mrIid: source.mrIid });
238
+ if (current.projectKey !== source.projectKey || current.headSha !== source.headSha) {
239
+ throw new Error("Merge request head changed after review");
240
+ }
241
+ if (!source.baseSha || current.baseSha !== source.baseSha) {
242
+ throw new Error("Merge request base changed after review");
243
+ }
244
+ }
245
+ async function findPublishedReview(db, repo, source, markdown, marker) {
246
+ const result = await findReviewComment(db, repo, source, markdown, marker, false);
247
+ return (result == null ? void 0 : result.noteId) ?? null;
248
+ }
249
+ async function findLegacyPublishedReview(db, repo, source, markdown, marker) {
250
+ return findReviewComment(db, repo, source, markdown, marker, true);
251
+ }
252
+ async function findReviewComment(db, repo, source, markdown, marker, includeUnmarked) {
253
+ if (!source.mrIid) throw new Error("Only merge request reviews can be published");
254
+ const remote = await provider(db, repo);
255
+ if (!remote.pat || remote.projectKey !== source.projectKey)
256
+ throw new Error("Repository credentials or project changed");
257
+ const authenticated = await responseJson(remote.userApi, remote.headers);
258
+ if (typeof authenticated.id !== "number" && typeof authenticated.id !== "string")
259
+ throw new Error("Unable to verify Git account identity");
260
+ const expectedBody = `${markdown}
261
+
262
+ ${marker}`;
263
+ const url = `${remote.root}/${remote.isGitHub ? `issues/${source.mrIid}/comments` : `merge_requests/${source.mrIid}/notes`}`;
264
+ let unmarkedNoteId = null;
265
+ for (let page = 1; page <= 100; page++) {
266
+ const response = await fetch(`${url}?per_page=100&page=${page}`, { headers: remote.headers, redirect: "error" });
267
+ if (!response.ok) throw new Error(`Unable to check existing review comments (${response.status})`);
268
+ const notes = await response.json();
269
+ if (!Array.isArray(notes)) throw new Error("Invalid review comment response");
270
+ for (const note of notes.map(object)) {
271
+ if (typeof note.body !== "string") continue;
272
+ const author = object(remote.isGitHub ? note.user : note.author);
273
+ if (note.body.includes(marker)) {
274
+ if (note.body !== expectedBody || String(author.id) !== String(authenticated.id))
275
+ throw new Error("Review comment marker is ambiguous");
276
+ if (typeof note.id !== "number" && typeof note.id !== "string")
277
+ throw new Error("Review comment identifier is unavailable");
278
+ return { kind: "marked", noteId: String(note.id) };
279
+ }
280
+ if (includeUnmarked && note.body === markdown && String(author.id) === String(authenticated.id)) {
281
+ if (typeof note.id !== "number" && typeof note.id !== "string")
282
+ throw new Error("Review comment identifier is unavailable");
283
+ unmarkedNoteId = String(note.id);
284
+ }
285
+ }
286
+ if (notes.length < 100) break;
287
+ if (page === 100) throw new Error("Too many review comments to check safely");
288
+ }
289
+ return unmarkedNoteId ? { kind: "unmarked", noteId: unmarkedNoteId } : null;
290
+ }
291
+ async function publishPinnedReview(db, repo, source, markdown, marker, initiate) {
292
+ const existing = await findPublishedReview(db, repo, source, markdown, marker);
293
+ if (existing) return existing;
294
+ const remote = await provider(db, repo);
295
+ if (!remote.pat || remote.projectKey !== source.projectKey || !source.mrIid)
296
+ throw new Error("Repository credentials or project changed");
297
+ const url = `${remote.root}/${remote.isGitHub ? `issues/${source.mrIid}/comments` : `merge_requests/${source.mrIid}/notes`}`;
298
+ await assertCurrentMrHead(db, repo, source);
299
+ const { response: pending } = await initiate(
300
+ () => fetch(url, {
301
+ method: "POST",
302
+ redirect: "error",
303
+ headers: { ...remote.headers, "Content-Type": "application/json" },
304
+ body: JSON.stringify({ body: `${markdown}
305
+
306
+ ${marker}` })
307
+ })
308
+ );
309
+ const response = await pending;
310
+ if (!response.ok) throw new Error(`Review comment outcome is unknown (${response.status})`);
311
+ const result = object(await response.json());
312
+ if (typeof result.id !== "number" && typeof result.id !== "string")
313
+ throw new Error("Review comment outcome is unknown");
314
+ return String(result.id);
315
+ }
316
+ // Annotate the CommonJS export names for ESM import in node:
317
+ 0 && (module.exports = {
318
+ assertCurrentMrHead,
319
+ findLegacyPublishedReview,
320
+ findPublishedReview,
321
+ publishPinnedReview,
322
+ readPinnedReviewSource,
323
+ resolveReviewProjectKey,
324
+ resolveReviewSource
325
+ });
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "displayName": "Git Manager",
4
4
  "displayName.zh-CN": "Git 管理器",
5
5
  "description": "Manage Git repositories with PAT authentication - pull, push, fetch, diff, file browsing",
6
- "version": "1.2.28",
6
+ "version": "1.3.1",
7
7
  "license": "Apache-2.0",
8
8
  "main": "dist/server/index.js",
9
9
  "files": [
@@ -53,7 +53,7 @@
53
53
  "url": "git+https://github.com/OrgGem/nocobase-beta.git",
54
54
  "directory": "packages/plugins/plugin-git-manager"
55
55
  },
56
- "gitHead": "4c1fe95b5f725713505c59944232259eb386bcf7",
56
+ "gitHead": "8c03d274bef1d07bed5b40f79db9fe946c43adc8",
57
57
  "publishConfig": {
58
58
  "access": "public",
59
59
  "registry": "https://registry.npmjs.org/"
@@ -0,0 +1,79 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import React from 'react';
11
+ import { cleanup, render, screen, waitFor } from '@testing-library/react';
12
+ import { CommitHistory } from '../components/CommitHistory';
13
+
14
+ const mocks = vi.hoisted(() => {
15
+ const request = vi.fn();
16
+ return {
17
+ request,
18
+ apiClient: { request },
19
+ selectedRepo: { id: 7, status: 'connected' },
20
+ };
21
+ });
22
+
23
+ vi.mock('@nocobase/client-v2', () => ({
24
+ useApp: () => ({ apiClient: mocks.apiClient }),
25
+ }));
26
+ vi.mock('../context/GitManagerContext', () => ({
27
+ useGitManager: () => ({ selectedRepo: mocks.selectedRepo }),
28
+ }));
29
+ vi.mock('../locale', () => ({ useT: () => (key: string) => key }));
30
+ vi.mock('../components/RunReviewButton', () => ({
31
+ RunReviewButton: ({ target }: { target: { type: string; branch?: string } }) => (
32
+ <button data-testid="run-review" data-branch={target.branch} data-target-type={target.type} />
33
+ ),
34
+ }));
35
+
36
+ describe('CommitHistory branch review entry point', () => {
37
+ beforeEach(() => {
38
+ vi.clearAllMocks();
39
+ mocks.request.mockImplementation(async ({ url }: { url: string }) => {
40
+ if (url === 'gitManager:branches') {
41
+ return {
42
+ data: {
43
+ data: { current: 'main', all: ['main', 'feature'], detached: false },
44
+ },
45
+ };
46
+ }
47
+ return { data: { data: { all: [] } } };
48
+ });
49
+ });
50
+ afterEach(cleanup);
51
+
52
+ it('mounts branch review only for a confirmed current branch', async () => {
53
+ render(<CommitHistory />);
54
+
55
+ const reviewButton = await screen.findByTestId('run-review');
56
+ expect(reviewButton).toHaveAttribute('data-target-type', 'branch');
57
+ expect(reviewButton).toHaveAttribute('data-branch', 'main');
58
+ expect(mocks.request).toHaveBeenCalledWith({ url: 'gitManager:branches', params: { repositoryId: 7 } });
59
+ });
60
+
61
+ it('does not treat a detached HEAD as a branch', async () => {
62
+ mocks.request.mockImplementation(async ({ url }: { url: string }) => {
63
+ if (url === 'gitManager:branches') {
64
+ return {
65
+ data: {
66
+ data: { current: 'main', all: ['main'], detached: true },
67
+ },
68
+ };
69
+ }
70
+ return { data: { data: { all: [] } } };
71
+ });
72
+ render(<CommitHistory />);
73
+
74
+ await waitFor(() => {
75
+ expect(mocks.request).toHaveBeenCalledWith({ url: 'gitManager:branches', params: { repositoryId: 7 } });
76
+ });
77
+ expect(screen.queryByTestId('run-review')).not.toBeInTheDocument();
78
+ });
79
+ });
@@ -0,0 +1,126 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import React from 'react';
11
+ import { cleanup, configure, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
12
+ import { ReviewHistory } from '../components/ReviewHistory';
13
+
14
+ const mocks = vi.hoisted(() => {
15
+ const request = vi.fn();
16
+ return {
17
+ request,
18
+ apiClient: { request },
19
+ success: vi.fn(),
20
+ warning: vi.fn(),
21
+ };
22
+ });
23
+
24
+ vi.mock('@nocobase/client-v2', () => ({
25
+ useApp: () => ({ apiClient: mocks.apiClient }),
26
+ getModernClientPrefix: () => 'v',
27
+ getRouteRuntimeVersion: () => 'legacy',
28
+ getV2EffectiveBasePath: () => '/v/',
29
+ stripModernClientPrefix: (path: string) => path.replace(/\/v\/?$/, '/'),
30
+ }));
31
+ vi.mock('../context/GitManagerContext', () => ({
32
+ useGitManager: () => ({ repos: [{ id: 7, name: 'review-repo', repoUrl: 'https://gitlab.test/group/project' }] }),
33
+ }));
34
+ vi.mock('../locale', () => ({ useT: () => (key: string) => key }));
35
+ vi.mock('../components/MarkdownView', () => ({
36
+ MarkdownView: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
37
+ }));
38
+ vi.mock('antd', async (importOriginal) => {
39
+ const actual = await importOriginal<typeof import('antd')>();
40
+ const ReactModule = await import('react');
41
+ return {
42
+ ...actual,
43
+ Drawer: (props: { open: boolean; title: React.ReactNode; extra?: React.ReactNode; children: React.ReactNode }) =>
44
+ props.open
45
+ ? ReactModule.default.createElement(
46
+ 'div',
47
+ { 'data-testid': 'review-drawer' },
48
+ props.title,
49
+ props.extra,
50
+ props.children,
51
+ )
52
+ : null,
53
+ Table: (props: {
54
+ dataSource?: Array<{ id: number; mrIid: number }>;
55
+ onRow?: (record: { id: number; mrIid: number }) => { onClick?: React.MouseEventHandler<HTMLElement> };
56
+ }) =>
57
+ ReactModule.default.createElement(
58
+ 'div',
59
+ null,
60
+ ...(props.dataSource || []).map((record) => {
61
+ const rowClick = props.onRow?.(record).onClick;
62
+ return ReactModule.default.createElement(
63
+ 'button',
64
+ { key: String(record.id), type: 'button', onClick: rowClick },
65
+ `Open review ${record.mrIid}`,
66
+ );
67
+ }),
68
+ ),
69
+ Popconfirm: (props: { children: React.ReactElement; onConfirm?: () => void }) => {
70
+ const child = props.children as React.ReactElement<{ onClick?: React.MouseEventHandler<HTMLElement> }>;
71
+ return ReactModule.default.cloneElement(child, {
72
+ onClick: (event) => {
73
+ child.props.onClick?.(event);
74
+ props.onConfirm?.();
75
+ },
76
+ });
77
+ },
78
+ message: { ...actual.message, success: mocks.success, warning: mocks.warning },
79
+ };
80
+ });
81
+
82
+ describe('ReviewHistory legacy approval outcome', () => {
83
+ const review = {
84
+ id: 301,
85
+ repositoryId: 7,
86
+ targetType: 'mr',
87
+ mrIid: 42,
88
+ status: 'completed',
89
+ postStatus: 'pending_approval',
90
+ reviewMarkdown: '## Existing review',
91
+ createdAt: '2026-11-10T00:00:00.000Z',
92
+ triggeredBy: 'manual',
93
+ };
94
+
95
+ beforeEach(() => {
96
+ vi.clearAllMocks();
97
+ configure({ asyncUtilTimeout: 1500 });
98
+ mocks.request.mockImplementation(async ({ url }: { url: string }) => {
99
+ if (url === 'gitCodeReviews:list' || url === 'gitCodeReviews:get') {
100
+ return { data: { data: url.endsWith(':list') ? [review] : review } };
101
+ }
102
+ if (url === 'gitManager:reviewApprovePost') return { data: { data: { status: 'observed' } } };
103
+ return { data: { data: [] } };
104
+ });
105
+ });
106
+
107
+ afterEach(cleanup);
108
+
109
+ it('reports an observed matching note without claiming the review was posted', async () => {
110
+ render(<ReviewHistory />);
111
+ fireEvent.click(await screen.findByRole('button', { name: 'Open review 42' }));
112
+ const drawer = await screen.findByTestId('review-drawer');
113
+ const approveLabel = within(drawer).getByText('Approve & Post', { exact: true });
114
+ fireEvent.click(approveLabel);
115
+
116
+ await waitFor(() => {
117
+ expect(mocks.warning).toHaveBeenCalledWith('A matching comment was found, but its attempt cannot be confirmed');
118
+ });
119
+ expect(mocks.success).not.toHaveBeenCalledWith('Review posted to merge request');
120
+ expect(mocks.request).toHaveBeenCalledWith({
121
+ url: 'gitManager:reviewApprovePost',
122
+ method: 'post',
123
+ data: { reviewId: 301, editedMarkdown: '## Existing review', baseConfirmation: 'LEGACY_BASE_UNVERIFIED' },
124
+ });
125
+ });
126
+ });
@@ -11,63 +11,74 @@ import React from 'react';
11
11
  import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
12
12
  import { RunReviewButton } from '../components/RunReviewButton';
13
13
 
14
- const mocks = vi.hoisted(() => ({ request: vi.fn(), getPlugin: vi.fn(), triggerTask: vi.fn() }));
14
+ const mocks = vi.hoisted(() => {
15
+ const request = vi.fn();
16
+ return { request, apiClient: { request }, getPlugin: vi.fn(), triggerTask: vi.fn() };
17
+ });
15
18
  vi.mock('@nocobase/client-v2', () => ({
16
- useApp: () => ({ apiClient: { request: mocks.request }, pm: { get: mocks.getPlugin } }),
19
+ useApp: () => ({ apiClient: mocks.apiClient, pm: { get: mocks.getPlugin } }),
17
20
  }));
18
21
  vi.mock('../locale', () => ({ useT: () => (key: string) => key }));
19
- // Any accidental runtime import of the optional AI package must fail this suite.
22
+ // Any accidental runtime import of the AI package must fail this suite.
20
23
  vi.mock('@nocobase/plugin-ai', () => {
21
24
  throw new Error('Unexpected legacy AI import');
22
25
  });
23
26
  vi.mock('@nocobase/plugin-ai/client-v2', () => {
24
- throw new Error('Unexpected mandatory AI import');
27
+ throw new Error('Unexpected direct AI client import');
25
28
  });
26
29
 
27
- describe('RunReviewButton optional AI integration', () => {
30
+ describe('RunReviewButton managed review queue', () => {
28
31
  beforeEach(() => {
29
32
  vi.clearAllMocks();
30
- mocks.getPlugin.mockReturnValue(undefined);
31
- mocks.request.mockImplementation(async ({ url }: { url: string }) => ({
32
- data: {
33
- data: url === 'gitReviewFlows:list' ? [{ id: 1, name: 'Security', aiEmployeeUsername: 'reviewer' }] : [],
34
- },
35
- }));
33
+ mocks.request.mockImplementation(async ({ url }: { url: string }) => {
34
+ if (url === 'gitReviewFlows:list') {
35
+ return { data: { data: [{ id: 1, name: 'Security', aiEmployeeUsername: 'reviewer', repositoryId: 7 }] } };
36
+ }
37
+ if (url === 'gitManager:triggerReview') return { data: { data: { reviewId: 123 } } };
38
+ return { data: { data: [] } };
39
+ });
36
40
  });
37
41
  afterEach(cleanup);
38
42
 
39
- it('renders Git review controls without the AI plugin and disables only chat', async () => {
43
+ it('exposes managed review actions without a direct AI chat action', async () => {
40
44
  render(<RunReviewButton target={{ type: 'branch', repositoryId: 7, branch: 'main' }} />);
41
45
  fireEvent.click(screen.getByRole('button', { name: /Code Review/ }));
42
- const chat = await screen.findByRole('menuitem', { name: /Ask AI Employee/ });
43
- expect(chat.getAttribute('aria-disabled')).toBe('true');
44
- expect(screen.getByRole('menuitem', { name: /Run automated review/ }).getAttribute('aria-disabled')).not.toBe(
45
- 'true',
46
- );
46
+
47
+ expect(await screen.findByRole('menuitem', { name: /Run automated review/ })).toBeInTheDocument();
48
+ expect(screen.queryByRole('menuitem', { name: /Ask AI Employee/ })).not.toBeInTheDocument();
49
+ expect(mocks.getPlugin).not.toHaveBeenCalled();
50
+ expect(mocks.triggerTask).not.toHaveBeenCalled();
47
51
  });
48
52
 
49
- it('opens a contextual task through the installed AI manager', async () => {
50
- mocks.getPlugin.mockReturnValue({ aiManager: { triggerTask: mocks.triggerTask } });
51
- render(<RunReviewButton target={{ type: 'mr', repositoryId: 7, mrIid: 42, title: 'Fix permissions' }} />);
53
+ it('queues a review and reports the returned review id without direct AI invocation', async () => {
54
+ const onTriggered = vi.fn();
55
+ render(
56
+ <RunReviewButton
57
+ target={{ type: 'mr', repositoryId: 7, mrIid: 42, title: 'Fix permissions' }}
58
+ onTriggered={onTriggered}
59
+ />,
60
+ );
52
61
  fireEvent.click(screen.getByRole('button', { name: /Code Review/ }));
53
- fireEvent.click(await screen.findByRole('menuitem', { name: /Ask AI Employee/ }));
54
- await waitFor(() => expect(mocks.triggerTask).toHaveBeenCalledTimes(1));
55
- expect(mocks.triggerTask).toHaveBeenCalledWith({
56
- aiEmployee: 'reviewer',
57
- tasks: [
62
+ fireEvent.click(await screen.findByRole('menuitem', { name: /Run automated review/ }));
63
+ await screen.findByText('Security — @reviewer');
64
+ fireEvent.click(await screen.findByRole('button', { name: 'Start Review' }));
65
+
66
+ await waitFor(() => {
67
+ expect(mocks.request).toHaveBeenCalledWith(
58
68
  expect.objectContaining({
59
- autoSend: false,
60
- message: expect.objectContaining({
61
- workContext: [
62
- expect.objectContaining({
63
- type: 'git-merge-request',
64
- content: { repositoryId: 7, mrIid: 42, title: 'Fix permissions' },
65
- }),
66
- ],
69
+ url: 'gitManager:triggerReview',
70
+ method: 'post',
71
+ data: expect.objectContaining({
72
+ repositoryId: 7,
73
+ targetType: 'mr',
74
+ flowId: 1,
75
+ mrIid: 42,
67
76
  }),
68
77
  }),
69
- ],
78
+ );
79
+ expect(onTriggered).toHaveBeenCalledWith(123);
70
80
  });
71
- expect(mocks.getPlugin).toHaveBeenCalledWith('ai');
81
+ expect(mocks.getPlugin).not.toHaveBeenCalled();
82
+ expect(mocks.triggerTask).not.toHaveBeenCalled();
72
83
  });
73
84
  });