plugin-git-manager 1.3.2 → 1.4.0

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 (82) hide show
  1. package/LICENSE +201 -0
  2. package/dist/client/{156.c27c2392746e7866.js → 156.8e36af3e2cee173e.js} +1 -1
  3. package/dist/client/{317.17ed0018e3e7db00.js → 317.2d0d33871e24ee24.js} +1 -1
  4. package/dist/client/{434.b2eeaaef33aae6e0.js → 434.2401f7257495b66e.js} +1 -1
  5. package/dist/client/{453.d49fac0e20ea08d9.js → 453.58657b9ba0904477.js} +1 -1
  6. package/dist/client/index.js +1 -1
  7. package/dist/client-v2/{434.19c7579c06b9077c.js → 434.32b0a07b821b9329.js} +1 -1
  8. package/dist/client-v2/{453.84c4387ba605dc27.js → 453.f9a0ec6d8e1bd1cc.js} +1 -1
  9. package/dist/client-v2/index.js +1 -1
  10. package/dist/externalVersion.js +10 -9
  11. package/dist/locale/en-US.json +27 -1
  12. package/dist/locale/vi-VN.json +27 -1
  13. package/dist/locale/zh-CN.json +30 -1
  14. package/dist/node_modules/simple-git/package.json +1 -1
  15. package/dist/node_modules/zod/package.json +1 -1
  16. package/dist/server/actions/chat-context.js +282 -0
  17. package/dist/server/actions/git-actions.js +99 -4
  18. package/dist/server/actions/gitlab-api.js +86 -7
  19. package/dist/server/chat-context-admission.js +187 -0
  20. package/dist/server/plugin.js +8 -0
  21. package/dist/server/request-method-policy.js +2 -0
  22. package/dist/server/services/review-source.js +7 -4
  23. package/package.json +2 -2
  24. package/src/client/__tests__/CommitHistory.test.tsx +1 -8
  25. package/src/client/__tests__/GitContextPicker.test.tsx +120 -0
  26. package/src/client/__tests__/ReviewHistory.test.tsx +1 -8
  27. package/src/client/__tests__/RunReviewButton.test.tsx +1 -8
  28. package/src/client/__tests__/ai-context.test.tsx +119 -0
  29. package/src/client/__tests__/workflowRoutes.test.ts +3 -10
  30. package/src/client/ai-context.tsx +3 -113
  31. package/src/client/components/CommitHistory.tsx +1 -8
  32. package/src/client/components/ReviewFlows.tsx +1 -8
  33. package/src/client/components/ReviewHistory.tsx +1 -8
  34. package/src/client/components/RunReviewButton.tsx +1 -8
  35. package/src/client/context/GitManagerContext.tsx +18 -2
  36. package/src/client/index.tsx +4 -13
  37. package/src/client/workflowRoutes.ts +3 -18
  38. package/src/client-v2/ai-context.tsx +135 -72
  39. package/src/client-v2/components/GitContextPicker.tsx +418 -0
  40. package/src/client-v2/git-context-api.ts +59 -0
  41. package/src/client-v2/plugin.tsx +2 -4
  42. package/src/locale/en-US.json +27 -1
  43. package/src/locale/vi-VN.json +27 -1
  44. package/src/locale/zh-CN.json +30 -1
  45. package/src/server/__tests__/chat-context-admission.test.ts +276 -0
  46. package/src/server/__tests__/chat-context-options.test.ts +144 -0
  47. package/src/server/__tests__/git-chat-context.test.ts +138 -0
  48. package/src/server/__tests__/git-security.test.ts +53 -8
  49. package/src/server/__tests__/poller-lifecycle.test.ts +1 -8
  50. package/src/server/__tests__/repository-access.test.ts +1 -8
  51. package/src/server/__tests__/review-service.integration.test.ts +1 -8
  52. package/src/server/__tests__/review.test.ts +1 -8
  53. package/src/server/__tests__/smoke.test.ts +201 -8
  54. package/src/server/actions/chat-context.ts +302 -0
  55. package/src/server/actions/git-actions.ts +120 -14
  56. package/src/server/actions/gitlab-api.ts +98 -12
  57. package/src/server/actions/poller.ts +1 -8
  58. package/src/server/actions/review-cutover.ts +1 -8
  59. package/src/server/actions/review.ts +1 -8
  60. package/src/server/actions/role-permissions.ts +1 -8
  61. package/src/server/ai-tools.ts +1 -8
  62. package/src/server/chat-context-admission.ts +182 -0
  63. package/src/server/collections/gitCodeReviews.ts +1 -8
  64. package/src/server/collections/gitReviewCutover.ts +1 -8
  65. package/src/server/collections/gitReviewFlows.ts +1 -8
  66. package/src/server/collections/gitReviewInbox.ts +1 -8
  67. package/src/server/collections/gitReviewProjects.ts +1 -8
  68. package/src/server/collections/gitReviewRequests.ts +1 -8
  69. package/src/server/index.ts +1 -8
  70. package/src/server/plugin.ts +12 -8
  71. package/src/server/poller.ts +1 -8
  72. package/src/server/repository-access.ts +1 -8
  73. package/src/server/request-method-policy.ts +3 -8
  74. package/src/server/review-control-access.ts +1 -8
  75. package/src/server/services/__tests__/registry-content-service.test.ts +1 -8
  76. package/src/server/services/__tests__/review-source.test.ts +33 -8
  77. package/src/server/services/legacy-post-service.ts +1 -8
  78. package/src/server/services/registry-content-service.ts +1 -8
  79. package/src/server/services/review-service.ts +1 -8
  80. package/src/server/services/review-source.ts +8 -12
  81. package/src/server/utils/get-repo-account.ts +1 -8
  82. package/src/server/utils/url-security.ts +1 -8
@@ -52,6 +52,7 @@ __export(git_actions_exports, {
52
52
  log: () => log,
53
53
  pull: () => pull,
54
54
  push: () => push,
55
+ readChatCommit: () => readChatCommit,
55
56
  status: () => status,
56
57
  validateBranch: () => validateBranch,
57
58
  validateLocalPath: () => validateLocalPath,
@@ -206,8 +207,8 @@ function getGit(ctx, localPath) {
206
207
  assertGitAvailable(ctx);
207
208
  return createGit(localPath);
208
209
  }
209
- async function getRepo(ctx) {
210
- const { repositoryId } = getGitActionParams(ctx);
210
+ async function getRepo(ctx, requestedRepositoryId) {
211
+ const repositoryId = requestedRepositoryId ?? getGitActionParams(ctx).repositoryId;
211
212
  const repo = await ctx.db.getRepository("gitRepositories").findOne({
212
213
  filterByTk: repositoryId
213
214
  });
@@ -348,14 +349,27 @@ async function status(ctx, next) {
348
349
  async function log(ctx, next) {
349
350
  const repo = await getRepo(ctx);
350
351
  const localPath = validateLocalPath(repo.get("localPath"));
351
- const { maxCount = 50, file } = getGitActionParams(ctx);
352
+ const { maxCount = 50, file, branch, skip } = getGitActionParams(ctx);
352
353
  const parsed = Number.parseInt(String(maxCount), 10);
353
354
  const options = { maxCount: Math.min(Math.max(parsed || 50, 1), 500) };
354
355
  if (file) {
355
356
  if (file.includes("..")) ctx.throw(400, "Invalid file path");
356
357
  options.file = file;
357
358
  }
358
- const result = await getGit(ctx, localPath).log(options);
359
+ const args = [];
360
+ if (branch) args.push(validateBranch(branch));
361
+ if (skip !== void 0) {
362
+ const parsedSkip = Number(skip);
363
+ if (!Number.isSafeInteger(parsedSkip) || parsedSkip < 0 || parsedSkip > 1e6) {
364
+ ctx.throw(400, "Invalid history offset");
365
+ }
366
+ args.push(`--skip=${parsedSkip}`);
367
+ }
368
+ const result = args.length ? await getGit(ctx, localPath).log([
369
+ ...args,
370
+ `--max-count=${options.maxCount}`,
371
+ ...file ? ["--follow", "--", file] : []
372
+ ]) : await getGit(ctx, localPath).log(options);
359
373
  ctx.body = { success: true, data: result };
360
374
  await next();
361
375
  }
@@ -470,6 +484,86 @@ async function commitDetail(ctx, next) {
470
484
  };
471
485
  await next();
472
486
  }
487
+ async function readLimitedGitOutput(localPath, args, maxBytes) {
488
+ return new Promise((resolve, reject) => {
489
+ const process2 = (0, import_child_process.spawn)(GIT_BINARY, args, {
490
+ cwd: localPath,
491
+ env: gitProcessEnvironment(),
492
+ windowsHide: true,
493
+ stdio: ["ignore", "pipe", "ignore"]
494
+ });
495
+ const chunks = [];
496
+ let size = 0;
497
+ let truncated = false;
498
+ process2.stdout.on("data", (chunk) => {
499
+ const remaining = maxBytes - size;
500
+ if (remaining > 0) {
501
+ const data = chunk.subarray(0, remaining);
502
+ chunks.push(data);
503
+ size += data.length;
504
+ }
505
+ if (chunk.length > remaining) {
506
+ truncated = true;
507
+ process2.kill();
508
+ }
509
+ });
510
+ process2.on("error", reject);
511
+ process2.on("close", (code) => {
512
+ if (code !== 0 && !truncated) {
513
+ reject(new Error("Unable to read commit diff"));
514
+ return;
515
+ }
516
+ const text = Buffer.concat(chunks).toString("utf8").replace(/\uFFFD$/, "");
517
+ resolve({ text, truncated });
518
+ });
519
+ });
520
+ }
521
+ async function readChatCommit(ctx, commitHash, maxFiles, maxBytes, repositoryId) {
522
+ if (!/^[a-f\d]{4,64}$/i.test(commitHash)) ctx.throw(400, "Invalid commit hash");
523
+ const repo = await getRepo(ctx, repositoryId);
524
+ const localPath = validateLocalPath(repo.get("localPath"));
525
+ const git = getGit(ctx, localPath);
526
+ const hash = (await git.raw(["rev-parse", "--verify", `${commitHash}^{commit}`])).trim();
527
+ const [metadata, parentLine] = await Promise.all([
528
+ git.raw(["show", "-s", "--format=%H%x00%an%x00%aI%x00%s%x00%b", hash]),
529
+ git.raw(["rev-list", "--parents", "-n", "1", hash])
530
+ ]);
531
+ const [, author, date, subject, body] = metadata.split("\0");
532
+ const parent = parentLine.trim().split(/\s+/)[1];
533
+ const namesArgs = parent ? ["diff", "--name-status", "-z", "-M", parent, hash, "--"] : ["diff-tree", "--root", "--no-commit-id", "-r", "--name-status", "-z", "-M", hash, "--"];
534
+ const tokens = (await git.raw(namesArgs)).split("\0");
535
+ const files = [];
536
+ for (let index = 0; index < tokens.length && tokens[index]; ) {
537
+ const status2 = tokens[index++];
538
+ const oldPath = tokens[index++];
539
+ const newPath = /^[RC]/.test(status2) ? tokens[index++] : oldPath;
540
+ if (!oldPath || !newPath) break;
541
+ files.push({ oldPath, newPath, status: status2 });
542
+ }
543
+ const selectedFiles = files.slice(0, maxFiles);
544
+ const paths = Array.from(new Set(selectedFiles.flatMap((file) => [file.oldPath, file.newPath]))).map(
545
+ (file) => `:(literal)${file}`
546
+ );
547
+ const patchArgs = parent ? ["diff", "--no-ext-diff", "--no-textconv", "--no-color", parent, hash, "--", ...paths] : ["show", "--format=", "--no-ext-diff", "--no-textconv", "--no-color", hash, "--", ...paths];
548
+ const patch = paths.length ? await readLimitedGitOutput(localPath, patchArgs, maxBytes) : { text: "", truncated: false };
549
+ const limitations = [];
550
+ if (files.length > maxFiles) limitations.push("Additional changed files were omitted.");
551
+ if (patch.truncated) limitations.push("The diff was truncated to the configured limit.");
552
+ if (/^Binary files .* differ$|^GIT binary patch$/m.test(patch.text)) {
553
+ limitations.push("Binary file contents are not included in the diff.");
554
+ }
555
+ return {
556
+ commitSha: hash,
557
+ author,
558
+ date,
559
+ subject,
560
+ body: body == null ? void 0 : body.trim(),
561
+ files: selectedFiles,
562
+ diff: patch.text,
563
+ truncated: patch.truncated || files.length > maxFiles,
564
+ limitations
565
+ };
566
+ }
473
567
  // Annotate the CommonJS export names for ESM import in node:
474
568
  0 && (module.exports = {
475
569
  acquireLock,
@@ -488,6 +582,7 @@ async function commitDetail(ctx, next) {
488
582
  log,
489
583
  pull,
490
584
  push,
585
+ readChatCommit,
491
586
  status,
492
587
  validateBranch,
493
588
  validateLocalPath,
@@ -28,7 +28,8 @@ var gitlab_api_exports = {};
28
28
  __export(gitlab_api_exports, {
29
29
  mergeRequestDetail: () => mergeRequestDetail,
30
30
  mergeRequestNotes: () => mergeRequestNotes,
31
- mergeRequests: () => mergeRequests
31
+ mergeRequests: () => mergeRequests,
32
+ readChatMergeRequest: () => readChatMergeRequest
32
33
  });
33
34
  module.exports = __toCommonJS(gitlab_api_exports);
34
35
  var import_repository_access = require("../repository-access");
@@ -56,12 +57,18 @@ async function gitlabFetch(apiBase, endpoint, pat, params) {
56
57
  }
57
58
  const totalPages = response.headers.get("x-total-pages");
58
59
  const total = response.headers.get("x-total");
60
+ const nextPage = response.headers.get("x-next-page");
59
61
  const data = await response.json();
60
- return { data, totalPages: totalPages ? parseInt(totalPages, 10) : null, total: total ? parseInt(total, 10) : null };
62
+ return {
63
+ data,
64
+ totalPages: totalPages ? parseInt(totalPages, 10) : null,
65
+ total: total ? parseInt(total, 10) : null,
66
+ hasMore: nextPage !== null ? Boolean(nextPage) : null
67
+ };
61
68
  }
62
- async function getRepoApiContext(ctx) {
69
+ async function getRepoApiContext(ctx, requestedRepositoryId) {
63
70
  const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
64
- const { repositoryId } = params;
71
+ const repositoryId = requestedRepositoryId ?? params.repositoryId;
65
72
  if (typeof repositoryId !== "string" && typeof repositoryId !== "number") ctx.throw(400, "repositoryId is required");
66
73
  const repo = await ctx.db.getRepository("gitRepositories").findOne({
67
74
  filterByTk: repositoryId
@@ -106,7 +113,8 @@ async function githubFetch(endpoint, pat, params) {
106
113
  }
107
114
  }
108
115
  const data = await response.json();
109
- return { data, totalPages, total: null };
116
+ const hasMore = linkHeader ? linkHeader.split(",").some((link) => link.includes('rel="next"')) : false;
117
+ return { data, totalPages, total: null, hasMore };
110
118
  }
111
119
  async function mergeRequests(ctx, next) {
112
120
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
@@ -217,7 +225,8 @@ async function mergeRequests(ctx, next) {
217
225
  page: parseInt(String(page), 10),
218
226
  perPage: parseInt(String(perPage), 10),
219
227
  total: result.total,
220
- totalPages: result.totalPages
228
+ totalPages: result.totalPages,
229
+ hasMore: result.hasMore ?? (result.totalPages !== null ? Number(page) < result.totalPages : result.data.length >= Math.min(parseInt(String(perPage), 10) || 20, 100))
221
230
  }
222
231
  };
223
232
  await next();
@@ -339,6 +348,75 @@ async function mergeRequestDetail(ctx, next) {
339
348
  };
340
349
  await next();
341
350
  }
351
+ async function readChatMergeRequest(ctx, mrIid, repositoryId) {
352
+ var _a, _b, _c, _d, _e;
353
+ const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx, repositoryId);
354
+ if (isGitHub) {
355
+ const [request2, fileResult] = await Promise.all([
356
+ githubFetch(`/repos/${projectPath}/pulls/${mrIid}`, pat),
357
+ githubFetch(`/repos/${projectPath}/pulls/${mrIid}/files`, pat, { page: 1, per_page: 51 })
358
+ ]);
359
+ const item2 = request2.data;
360
+ if (!Array.isArray(fileResult.data)) throw new Error("Unable to read merge request changes");
361
+ const files2 = fileResult.data.map(
362
+ (file) => ({
363
+ oldPath: file.previous_filename || file.filename,
364
+ newPath: file.filename,
365
+ status: file.status,
366
+ diff: file.patch
367
+ })
368
+ );
369
+ const limitations2 = [];
370
+ if (typeof item2.changed_files === "number" && item2.changed_files > files2.length) {
371
+ limitations2.push("Additional changed files were omitted by the provider.");
372
+ }
373
+ if (files2.some((file) => !file.diff)) {
374
+ limitations2.push("The provider omitted patches for one or more files, including binary or large files.");
375
+ }
376
+ return {
377
+ title: item2.title,
378
+ description: item2.body,
379
+ state: item2.state === "open" ? "opened" : item2.merged_at ? "merged" : "closed",
380
+ sourceBranch: (_a = item2.head) == null ? void 0 : _a.ref,
381
+ targetBranch: (_b = item2.base) == null ? void 0 : _b.ref,
382
+ author: (_c = item2.user) == null ? void 0 : _c.login,
383
+ files: files2,
384
+ limitations: limitations2
385
+ };
386
+ }
387
+ if (!pat) ctx.throw(400, "Personal Access Token is required for GitLab API access");
388
+ const [request, changeResult] = await Promise.all([
389
+ gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${mrIid}`, pat),
390
+ gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${mrIid}/changes`, pat)
391
+ ]);
392
+ const item = request.data;
393
+ const changeData = changeResult.data || {};
394
+ if (!Array.isArray(changeData.changes)) throw new Error("Unable to read merge request changes");
395
+ const files = changeData.changes.map(
396
+ (file) => ({
397
+ oldPath: file.old_path,
398
+ newPath: file.new_path,
399
+ status: file.new_file ? "added" : file.deleted_file ? "removed" : file.renamed_file ? "renamed" : "modified",
400
+ diff: file.diff,
401
+ unavailable: file.collapsed || file.too_large || file.binary || !file.diff
402
+ })
403
+ );
404
+ const limitations = [];
405
+ if (changeData.overflow) limitations.push("The provider omitted additional changed files or patches.");
406
+ if (files.some((file) => file.unavailable)) {
407
+ limitations.push("The provider omitted patches for one or more files, including binary or large files.");
408
+ }
409
+ return {
410
+ title: item.title,
411
+ description: item.description,
412
+ state: item.state,
413
+ sourceBranch: item.source_branch,
414
+ targetBranch: item.target_branch,
415
+ author: ((_d = item.author) == null ? void 0 : _d.username) || ((_e = item.author) == null ? void 0 : _e.name),
416
+ files,
417
+ limitations
418
+ };
419
+ }
342
420
  async function mergeRequestNotes(ctx, next) {
343
421
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
344
422
  const params = (0, import_repository_access.getEffectiveActionParams)(ctx);
@@ -398,5 +476,6 @@ async function mergeRequestNotes(ctx, next) {
398
476
  0 && (module.exports = {
399
477
  mergeRequestDetail,
400
478
  mergeRequestNotes,
401
- mergeRequests
479
+ mergeRequests,
480
+ readChatMergeRequest
402
481
  });
@@ -0,0 +1,187 @@
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 chat_context_admission_exports = {};
28
+ __export(chat_context_admission_exports, {
29
+ enforceGitChatAdmission: () => enforceGitChatAdmission,
30
+ registerGitChatContextStrategies: () => registerGitChatContextStrategies
31
+ });
32
+ module.exports = __toCommonJS(chat_context_admission_exports);
33
+ var import_chat_context = require("./actions/chat-context");
34
+ const TYPES = ["git-repository", "git-merge-request", "git-commit"];
35
+ const registered = /* @__PURE__ */ new WeakMap();
36
+ const admitted = /* @__PURE__ */ new WeakMap();
37
+ function gitContext(value) {
38
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
39
+ const item = value;
40
+ if (typeof item.type !== "string" || !TYPES.includes(item.type)) return null;
41
+ return {
42
+ type: item.type,
43
+ uid: typeof item.uid === "string" ? item.uid : "",
44
+ ...typeof item.title === "string" ? { title: item.title } : {}
45
+ };
46
+ }
47
+ function contextParams(ctx, item) {
48
+ const kind = item.type.slice(4);
49
+ if (!item.uid || !item.uid.trim()) return ctx.throw(400, "Invalid Git context");
50
+ if (kind === "repository") return { kind, repositoryId: item.uid };
51
+ const separator = item.uid.indexOf(":");
52
+ if (separator <= 0 || separator === item.uid.length - 1) return ctx.throw(400, "Invalid Git context");
53
+ const repositoryId = item.uid.slice(0, separator);
54
+ const target = item.uid.slice(separator + 1);
55
+ return kind === "merge-request" ? { kind, repositoryId, mrIid: target } : { kind, repositoryId, commitHash: target };
56
+ }
57
+ function contextKey(item) {
58
+ return JSON.stringify([item.type, item.uid]);
59
+ }
60
+ function resolvedItem(item, content) {
61
+ const name = typeof content.repositoryName === "string" ? content.repositoryName : String(content.repositoryId || "");
62
+ let title;
63
+ if (item.type === "git-repository") {
64
+ title = typeof content.name === "string" ? content.name : String(content.repositoryId || "");
65
+ } else if (item.type === "git-merge-request") {
66
+ title = [name, `!${content.mrIid}`, content.title].filter(Boolean).join(" \xB7 ");
67
+ } else {
68
+ title = [name, String(content.commitSha || "").slice(0, 7), content.subject].filter(Boolean).join(" \xB7 ");
69
+ }
70
+ return { type: item.type, uid: item.uid, title, content };
71
+ }
72
+ function aiPluginFor(app) {
73
+ try {
74
+ return app.pm.get("ai") || app.pm.get("@nocobase/plugin-ai");
75
+ } catch {
76
+ return void 0;
77
+ }
78
+ }
79
+ function registerGitChatContextStrategies(app) {
80
+ var _a;
81
+ const handler = (_a = aiPluginFor(app)) == null ? void 0 : _a.workContextHandler;
82
+ if (!handler || typeof handler.registerStrategy !== "function") return false;
83
+ const names = registered.get(handler) || /* @__PURE__ */ new Set();
84
+ registered.set(handler, names);
85
+ for (const type of TYPES) {
86
+ if (names.has(type)) continue;
87
+ handler.registerStrategy(type, {
88
+ resolve: async (ctx, source) => {
89
+ var _a2;
90
+ const item = gitContext(source);
91
+ if (!item) return "";
92
+ try {
93
+ const content = ((_a2 = admitted.get(ctx)) == null ? void 0 : _a2.get(contextKey(item))) || await (0, import_chat_context.loadChatContext)(ctx, contextParams(ctx, item));
94
+ return JSON.stringify(resolvedItem(item, content));
95
+ } catch {
96
+ return JSON.stringify({ type, content: { unavailable: true } });
97
+ }
98
+ }
99
+ });
100
+ names.add(type);
101
+ }
102
+ return true;
103
+ }
104
+ async function admitContextItems(ctx, values) {
105
+ if (!Array.isArray(values)) return;
106
+ for (let index = 0; index < values.length; index += 1) {
107
+ const item = gitContext(values[index]);
108
+ if (!item) continue;
109
+ try {
110
+ if (!registerGitChatContextStrategies(ctx.app)) throw new Error("Git context strategy is unavailable");
111
+ const content = await (0, import_chat_context.loadChatContext)(ctx, contextParams(ctx, item));
112
+ let cache = admitted.get(ctx);
113
+ if (!cache) {
114
+ cache = /* @__PURE__ */ new Map();
115
+ admitted.set(ctx, cache);
116
+ }
117
+ cache.set(contextKey(item), content);
118
+ values[index] = resolvedItem(item, content);
119
+ } catch {
120
+ ctx.throw(
121
+ 403,
122
+ ctx.t("Git context is unavailable. Check your access and select it again.", { ns: "plugin-git-manager" })
123
+ );
124
+ }
125
+ }
126
+ }
127
+ function recordValue(record, key) {
128
+ if (!record || typeof record !== "object") return void 0;
129
+ const object = record;
130
+ return typeof object.get === "function" ? object.get(key) : object[key];
131
+ }
132
+ async function admitResentMessage(ctx, values) {
133
+ var _a, _b;
134
+ const sessionId = typeof values.sessionId === "string" ? values.sessionId : "";
135
+ const hasMessageId = Object.prototype.hasOwnProperty.call(values, "messageId");
136
+ let messageId;
137
+ if (hasMessageId) {
138
+ const supplied = values.messageId;
139
+ if (typeof supplied === "number" && Number.isSafeInteger(supplied) && supplied > 0) {
140
+ messageId = supplied;
141
+ } else if (typeof supplied === "string" && /^\d+$/.test(supplied) && /[1-9]/.test(supplied)) {
142
+ messageId = supplied;
143
+ } else {
144
+ return ctx.throw(400, "Invalid messageId");
145
+ }
146
+ }
147
+ const userId = (_b = (_a = ctx.auth) == null ? void 0 : _a.user) == null ? void 0 : _b.id;
148
+ const plugin = aiPluginFor(ctx.app);
149
+ if (!sessionId || !userId || !(plugin == null ? void 0 : plugin.aiConversationsManager)) return;
150
+ const conversation = await plugin.aiConversationsManager.getConversation({ sessionId, userId });
151
+ if (!conversation) return;
152
+ const repository = ctx.db.getRepository("aiConversations.messages", sessionId);
153
+ const target = hasMessageId ? await repository.findOne({ filter: { messageId } }) : await repository.findOne({ filter: { sessionId }, sort: ["-messageId"] });
154
+ if (!target) return;
155
+ const targetId = recordValue(target, "messageId");
156
+ if (typeof targetId !== "string" && typeof targetId !== "number" || !targetId) {
157
+ return ctx.throw(400, "Invalid messageId");
158
+ }
159
+ const message = recordValue(target, "role") === "user" ? target : await repository.findOne({
160
+ filter: { sessionId, role: "user", messageId: { $lt: targetId } },
161
+ sort: ["-messageId"]
162
+ });
163
+ await admitContextItems(ctx, recordValue(message, "workContext"));
164
+ }
165
+ async function enforceGitChatAdmission(ctx, next) {
166
+ var _a, _b;
167
+ if (((_a = ctx.action) == null ? void 0 : _a.resourceName) !== "aiConversations") return next();
168
+ const action = ctx.action.actionName;
169
+ if (action !== "sendMessages" && action !== "resendMessages") return next();
170
+ const values = (_b = ctx.action.params) == null ? void 0 : _b.values;
171
+ if (!values || typeof values !== "object" || Array.isArray(values)) return next();
172
+ if (action === "sendMessages" && Array.isArray(values.messages)) {
173
+ for (const message of values.messages) {
174
+ if (message && typeof message === "object" && message.role === "user") {
175
+ await admitContextItems(ctx, message.workContext);
176
+ }
177
+ }
178
+ } else if (action === "resendMessages") {
179
+ await admitResentMessage(ctx, values);
180
+ }
181
+ await next();
182
+ }
183
+ // Annotate the CommonJS export names for ESM import in node:
184
+ 0 && (module.exports = {
185
+ enforceGitChatAdmission,
186
+ registerGitChatContextStrategies
187
+ });
@@ -52,6 +52,7 @@ var reviewCutoverActions = __toESM(require("./actions/review-cutover"));
52
52
  var pollerActions = __toESM(require("./actions/poller"));
53
53
  var rolePermissionsActions = __toESM(require("./actions/role-permissions"));
54
54
  var subtreeActions = __toESM(require("./actions/subtree"));
55
+ var chatContextActions = __toESM(require("./actions/chat-context"));
55
56
  var import_review = require("./actions/review");
56
57
  var import_ai_tools = require("./ai-tools");
57
58
  var import_request_method_policy = require("./request-method-policy");
@@ -61,6 +62,7 @@ var import_review_service = require("./services/review-service");
61
62
  var import_legacy_post_service = require("./services/legacy-post-service");
62
63
  var import_review_control_access = require("./review-control-access");
63
64
  var import_repository_access = require("./repository-access");
65
+ var import_chat_context_admission = require("./chat-context-admission");
64
66
  var import_redact = require("./utils/redact");
65
67
  var import_url_security = require("./utils/url-security");
66
68
  const GIT_CONFIGURATION_URL_FIELDS = /* @__PURE__ */ new Set(["repoUrl", "baseUrl"]);
@@ -130,6 +132,8 @@ class PluginGitManagerServer extends import_server.Plugin {
130
132
  mergeRequests: gitlabApi.mergeRequests,
131
133
  mergeRequestDetail: gitlabApi.mergeRequestDetail,
132
134
  mergeRequestNotes: gitlabApi.mergeRequestNotes,
135
+ chatContextOptions: chatContextActions.chatContextOptions,
136
+ chatContextContent: chatContextActions.chatContextContent,
133
137
  triggerReview: reviewActions.triggerReview,
134
138
  reviewApprovePost: reviewActions.reviewApprovePost,
135
139
  reviewLegacyPostStatus: reviewActions.reviewLegacyPostStatus,
@@ -153,6 +157,8 @@ class PluginGitManagerServer extends import_server.Plugin {
153
157
  subtreeReplace: subtreeActions.subtreeRunOnAppProcess
154
158
  }
155
159
  });
160
+ this.app.acl.allow("gitManager", "chatContextOptions", "loggedIn");
161
+ this.app.acl.allow("gitManager", "chatContextContent", "loggedIn");
156
162
  const legacyApprovalAction = this.app.acl.getAvailableAction("reviewApprovePost");
157
163
  const priorAliases = (_a = legacyApprovalAction == null ? void 0 : legacyApprovalAction.options) == null ? void 0 : _a.aliases;
158
164
  this.app.acl.setAvailableAction("reviewApprovePost", {
@@ -201,6 +207,7 @@ class PluginGitManagerServer extends import_server.Plugin {
201
207
  });
202
208
  }
203
209
  this.app.resourceManager.use(import_request_method_policy.enforceGitRequestMethod);
210
+ this.app.resourceManager.use(import_chat_context_admission.enforceGitChatAdmission);
204
211
  this.app.resourceManager.use(import_review_control_access.enforceReviewControlAccess);
205
212
  this.app.resourceManager.use(import_repository_access.enforceRepositoryAccess);
206
213
  this.app.resourceManager.use(import_repository_access.enforceRepositoryCollectionAccess);
@@ -217,6 +224,7 @@ class PluginGitManagerServer extends import_server.Plugin {
217
224
  return next();
218
225
  });
219
226
  (0, import_ai_tools.registerGitReviewAiTools)(this.app);
227
+ this.app.on("afterLoad", () => (0, import_chat_context_admission.registerGitChatContextStrategies)(this.app));
220
228
  this.app.on("afterStart", async () => {
221
229
  await ensureAutoReviewFlowSchema(this.app).catch(
222
230
  (err) => {
@@ -40,6 +40,8 @@ const READ_ACTIONS = /* @__PURE__ */ new Set([
40
40
  "mergeRequests",
41
41
  "mergeRequestDetail",
42
42
  "mergeRequestNotes",
43
+ "chatContextOptions",
44
+ "chatContextContent",
43
45
  "pollerStatus",
44
46
  "rolePermissions",
45
47
  "reviewCutoverStatus"
@@ -176,9 +176,11 @@ async function readPinnedReviewSource(db, repo, source) {
176
176
  if (!Array.isArray(files) || files.length >= 300) throw new Error("GitHub comparison is incomplete");
177
177
  content = files.map((item) => {
178
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");
179
+ if (typeof file.filename !== "string") throw new Error("GitHub comparison contains an unavailable patch");
181
180
  if (/[\r\n]/.test(file.filename)) throw new Error("GitHub comparison has an unsupported filename");
181
+ if (typeof file.patch !== "string") {
182
+ return `Binary files a/${file.filename} and b/${file.filename} differ (patch omitted by provider)`;
183
+ }
182
184
  return `--- a/${file.filename}
183
185
  +++ b/${file.filename}
184
186
  ${file.patch}`;
@@ -193,11 +195,12 @@ ${file.patch}`;
193
195
  }
194
196
  content = comparison.diffs.map((item) => {
195
197
  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
198
  const oldPath = String(file.old_path || "");
199
199
  const newPath = String(file.new_path || "");
200
200
  if (/[\r\n]/.test(oldPath + newPath)) throw new Error("GitLab comparison has an unsupported filename");
201
+ if (file.too_large || file.collapsed || typeof file.diff !== "string") {
202
+ return `Binary files a/${oldPath} and b/${newPath} differ (patch omitted by provider)`;
203
+ }
201
204
  return `--- a/${oldPath}
202
205
  +++ b/${newPath}
203
206
  ${file.diff}`;
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.3.2",
6
+ "version": "1.4.0",
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": "871d69010d8039d528f9df534f9242f4dafb498e",
56
+ "gitHead": "36c3d44696c81e16199e8dd5e1b13314a4c62a96",
57
57
  "publishConfig": {
58
58
  "access": "public",
59
59
  "registry": "https://registry.npmjs.org/"
@@ -1,11 +1,4 @@
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
- */
1
+ // SPDX-License-Identifier: Apache-2.0
9
2
 
10
3
  import React from 'react';
11
4
  import { cleanup, render, screen, waitFor } from '@testing-library/react';