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
@@ -0,0 +1,302 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import type { Context } from '@nocobase/actions';
4
+ import type { Filter } from '@nocobase/database';
5
+ import { getEffectiveActionParams, resolveRepositoryScope, scopeIncludesRepository } from '../repository-access';
6
+ import { readChatCommit } from './git-actions';
7
+ import { readChatMergeRequest } from './gitlab-api';
8
+
9
+ const MAX_FILES = 50;
10
+ const MAX_DIFF_BYTES = 24 * 1024;
11
+ const REPOSITORY_FIELDS = ['id', 'name', 'defaultBranch', 'status'] as const;
12
+ const KINDS = ['repository', 'merge-request', 'commit'] as const;
13
+ type Kind = (typeof KINDS)[number];
14
+ type RepositoryField = (typeof REPOSITORY_FIELDS)[number];
15
+ type RepositoryId = number | string;
16
+ type Permission = {
17
+ params?: {
18
+ filter?: unknown;
19
+ fields?: unknown;
20
+ whitelist?: unknown;
21
+ except?: unknown;
22
+ blacklist?: unknown;
23
+ };
24
+ } | null;
25
+ type Scope = { unrestricted: boolean; ids: RepositoryId[] };
26
+ type Access = { scope: Scope; fields: RepositoryField[] } | null;
27
+ type GitContextChange = {
28
+ oldPath?: string;
29
+ newPath?: string;
30
+ status?: string;
31
+ newFile: boolean;
32
+ deletedFile: boolean;
33
+ renamedFile: boolean;
34
+ diff?: string;
35
+ };
36
+
37
+ const ACTIONS: Record<Kind, string[]> = {
38
+ repository: [],
39
+ 'merge-request': ['mergeRequests', 'mergeRequestDetail'],
40
+ commit: ['branches', 'log', 'commitDetail', 'diff'],
41
+ };
42
+
43
+ function rolesFor(ctx: Context): string[] {
44
+ const roles: unknown = ctx.state?.currentRoles;
45
+ if (!ctx.state?.currentUser?.id || !Array.isArray(roles) || roles.some((role) => typeof role !== 'string')) {
46
+ return ctx.throw(403, 'Permission denied');
47
+ }
48
+ return roles;
49
+ }
50
+
51
+ function allowedField(permission: Permission, field: string): boolean {
52
+ if (!permission) return false;
53
+ const params = permission.params || {};
54
+ for (const key of ['fields', 'whitelist'] as const) {
55
+ const value = params[key];
56
+ if (value !== undefined && !Array.isArray(value)) return false;
57
+ if (Array.isArray(value) && value.length && !value.includes(field) && !value.includes('*')) return false;
58
+ }
59
+ for (const key of ['except', 'blacklist'] as const) {
60
+ const value = params[key];
61
+ if (value !== undefined && !Array.isArray(value)) return false;
62
+ if (Array.isArray(value) && (value.includes(field) || value.includes('*'))) return false;
63
+ }
64
+ return true;
65
+ }
66
+
67
+ function intersectScopes(scopes: Scope[]): Scope {
68
+ const restricted = scopes.filter((scope) => !scope.unrestricted);
69
+ if (!restricted.length) return { unrestricted: true, ids: [] };
70
+ const [first, ...rest] = restricted;
71
+ return {
72
+ unrestricted: false,
73
+ ids: first.ids.filter((id) => rest.every((scope) => scope.ids.some((other) => String(other) === String(id)))),
74
+ };
75
+ }
76
+
77
+ async function permissionsFor(ctx: Context, roles: string[]) {
78
+ if (roles.includes('root')) {
79
+ return new Map<string, Permission>(
80
+ [
81
+ 'gitRepositories:list',
82
+ 'gitRepositories:get',
83
+ ...Object.values(ACTIONS)
84
+ .flat()
85
+ .map((name) => `gitManager:${name}`),
86
+ ].map((action) => [action, { params: {} }]),
87
+ );
88
+ }
89
+ const pairs: Array<[string, string]> = [
90
+ ['gitRepositories', 'list'],
91
+ ['gitRepositories', 'get'],
92
+ ...Array.from(new Set(Object.values(ACTIONS).flat())).map((name): [string, string] => ['gitManager', name]),
93
+ ];
94
+ const values = await Promise.all(
95
+ pairs.map(
96
+ async ([resource, action]) =>
97
+ [`${resource}:${action}`, (await ctx.app.acl.can({ roles, resource, action })) as Permission] as const,
98
+ ),
99
+ );
100
+ return new Map<string, Permission>(values);
101
+ }
102
+
103
+ function accessFor(permissions: Map<string, Permission>, kind: Kind): Access {
104
+ const list = permissions.get('gitRepositories:list') || null;
105
+ const get = permissions.get('gitRepositories:get') || null;
106
+ const required = [list, get, ...ACTIONS[kind].map((action) => permissions.get(`gitManager:${action}`) || null)];
107
+ if (required.some((permission) => !permission)) return null;
108
+ const scopes = required.map((permission) => resolveRepositoryScope(permission?.params?.filter));
109
+ if (scopes.some((scope) => !scope.supported)) return null;
110
+ const scope = intersectScopes(scopes);
111
+ if (!scope.unrestricted && !scope.ids.length) return null;
112
+ const fields = REPOSITORY_FIELDS.filter((field) => allowedField(list, field) && allowedField(get, field));
113
+ if (!fields.includes('id')) return null;
114
+ return { scope, fields };
115
+ }
116
+
117
+ function scopeFilter(scope: Scope): Filter {
118
+ return scope.unrestricted ? {} : { id: { $in: scope.ids } };
119
+ }
120
+
121
+ function readRepositoryValue(record: unknown, field: string): unknown {
122
+ if (!record || typeof record !== 'object') return undefined;
123
+ const value = record as { get?: (key: string) => unknown } & Record<string, unknown>;
124
+ return typeof value.get === 'function' ? value.get(field) : value[field];
125
+ }
126
+
127
+ function repositorySummary(record: unknown, fields: RepositoryField[]) {
128
+ return Object.fromEntries(fields.map((field) => [field, readRepositoryValue(record, field)]));
129
+ }
130
+
131
+ function kindFrom(value: unknown): Kind | undefined {
132
+ return typeof value === 'string' && KINDS.includes(value as Kind) ? (value as Kind) : undefined;
133
+ }
134
+
135
+ function positiveInteger(value: unknown, fallback: number, max: number): number {
136
+ const parsed = Number(value);
137
+ return Number.isSafeInteger(parsed) && parsed > 0 ? Math.min(parsed, max) : fallback;
138
+ }
139
+
140
+ export async function chatContextOptions(ctx: Context, next: () => Promise<void>) {
141
+ const roles = rolesFor(ctx);
142
+ const params = getEffectiveActionParams(ctx);
143
+ const kind = kindFrom(params.kind);
144
+ if (params.kind !== undefined && !kind) ctx.throw(400, 'Invalid chat context type');
145
+ const permissions = await permissionsFor(ctx, roles);
146
+ const accesses = Object.fromEntries(KINDS.map((name) => [name, accessFor(permissions, name)])) as Record<
147
+ Kind,
148
+ Access
149
+ >;
150
+ const repo = ctx.db.getRepository('gitRepositories');
151
+ const capabilityValues = await Promise.all(
152
+ KINDS.map(async (name) => {
153
+ const access = accesses[name];
154
+ return Boolean(access && (await repo.findOne({ filter: scopeFilter(access.scope), fields: ['id'] })));
155
+ }),
156
+ );
157
+ const capabilities = Object.fromEntries(KINDS.map((name, index) => [name, capabilityValues[index]])) as Record<
158
+ Kind,
159
+ boolean
160
+ >;
161
+ const page = positiveInteger(params.page, 1, 100000);
162
+ const pageSize = positiveInteger(params.pageSize, 20, 100);
163
+ const access = kind ? accesses[kind] : null;
164
+ const search = typeof params.search === 'string' ? params.search.trim().slice(0, 200) : '';
165
+ const repositoryId = params.repositoryId;
166
+ if (
167
+ repositoryId !== undefined &&
168
+ ((typeof repositoryId !== 'string' && typeof repositoryId !== 'number') || !String(repositoryId).trim())
169
+ ) {
170
+ ctx.throw(400, 'Invalid repository');
171
+ }
172
+ let records: unknown[] = [];
173
+ if (access && (!search || access.fields.includes('name'))) {
174
+ const conditions: Filter[] = [scopeFilter(access.scope)];
175
+ if (search) conditions.push({ name: { $includes: search } });
176
+ if (typeof repositoryId === 'string' || typeof repositoryId === 'number') conditions.push({ id: repositoryId });
177
+ const filter = conditions.length === 1 ? conditions[0] : { $and: conditions };
178
+ records = await repo.find({
179
+ filter,
180
+ fields: access.fields,
181
+ sort: ['id'],
182
+ limit: pageSize + 1,
183
+ offset: (page - 1) * pageSize,
184
+ });
185
+ }
186
+ ctx.body = {
187
+ success: true,
188
+ data: {
189
+ capabilities,
190
+ items: records.slice(0, pageSize).map((record) => repositorySummary(record, access?.fields || [])),
191
+ page,
192
+ pageSize,
193
+ hasMore: records.length > pageSize,
194
+ },
195
+ };
196
+ await next();
197
+ }
198
+
199
+ function boundedDiff(value: string, limit: number): { value: string; truncated: boolean; bytes: number } {
200
+ const bytes = Buffer.from(value, 'utf8');
201
+ if (bytes.length <= limit) return { value, truncated: false, bytes: bytes.length };
202
+ const text = bytes
203
+ .subarray(0, limit)
204
+ .toString('utf8')
205
+ .replace(/\uFFFD$/, '');
206
+ return { value: text, truncated: true, bytes: Buffer.byteLength(text, 'utf8') };
207
+ }
208
+
209
+ export async function loadChatContext(ctx: Context, params: Record<string, unknown>): Promise<Record<string, unknown>> {
210
+ const roles = rolesFor(ctx);
211
+ const kind = kindFrom(params.kind);
212
+ const repositoryId = params.repositoryId;
213
+ if (!kind || (typeof repositoryId !== 'number' && typeof repositoryId !== 'string') || !String(repositoryId).trim()) {
214
+ return ctx.throw(400, 'Invalid chat context');
215
+ }
216
+ const access = accessFor(await permissionsFor(ctx, roles), kind);
217
+ if (
218
+ !access ||
219
+ (!access.scope.unrestricted && !scopeIncludesRepository({ id: { $in: access.scope.ids } }, repositoryId))
220
+ ) {
221
+ return ctx.throw(403, 'Permission denied');
222
+ }
223
+ const repository = await ctx.db.getRepository('gitRepositories').findOne({
224
+ filter: { $and: [scopeFilter(access.scope), { id: repositoryId }] },
225
+ fields: access.fields,
226
+ });
227
+ if (!repository) return ctx.throw(404, 'Repository not found');
228
+ const summary = repositorySummary(repository, access.fields);
229
+ const repositoryName = summary.name;
230
+ let content: Record<string, unknown>;
231
+ if (kind === 'repository') {
232
+ content = {
233
+ type: 'git-repository',
234
+ repositoryId,
235
+ name: summary.name,
236
+ defaultBranch: summary.defaultBranch,
237
+ status: summary.status,
238
+ };
239
+ } else if (kind === 'commit') {
240
+ const commitHash = typeof params.commitHash === 'string' ? params.commitHash : '';
241
+ const commit = await readChatCommit(ctx, commitHash, MAX_FILES, MAX_DIFF_BYTES, repositoryId);
242
+ content = {
243
+ type: 'git-commit',
244
+ repositoryId,
245
+ repositoryName,
246
+ ...commit,
247
+ hash: commit.commitSha,
248
+ files: commit.files.map((file) => ({ ...file, file: file.newPath })),
249
+ limitations: commit.limitations.map((limitation) => ctx.t(limitation, { ns: 'plugin-git-manager' })),
250
+ };
251
+ } else {
252
+ const mrIid = Number(params.mrIid);
253
+ if (!Number.isSafeInteger(mrIid) || mrIid <= 0) return ctx.throw(400, 'Invalid merge request');
254
+ const result = await readChatMergeRequest(ctx, mrIid, repositoryId);
255
+ let remaining = MAX_DIFF_BYTES;
256
+ let truncated = result.files.length > MAX_FILES;
257
+ const changes: GitContextChange[] = result.files
258
+ .slice(0, MAX_FILES)
259
+ .map((file: { oldPath?: string; newPath?: string; status?: string; diff?: string; unavailable?: boolean }) => {
260
+ const diff = typeof file.diff === 'string' && !file.unavailable ? boundedDiff(file.diff, remaining) : undefined;
261
+ if (diff) {
262
+ remaining -= diff.bytes;
263
+ truncated ||= diff.truncated;
264
+ }
265
+ return {
266
+ oldPath: file.oldPath,
267
+ newPath: file.newPath,
268
+ status: file.status,
269
+ newFile: file.status === 'added',
270
+ deletedFile: file.status === 'removed',
271
+ renamedFile: file.status === 'renamed',
272
+ diff: diff?.value,
273
+ };
274
+ });
275
+ const limitations = [...result.limitations];
276
+ if (truncated) limitations.push('Additional changed files or diff content were omitted.');
277
+ if (limitations.length) truncated = true;
278
+ content = {
279
+ type: 'git-merge-request',
280
+ repositoryId,
281
+ repositoryName,
282
+ mrIid,
283
+ title: result.title,
284
+ description: result.description,
285
+ state: result.state,
286
+ sourceBranch: result.sourceBranch,
287
+ targetBranch: result.targetBranch,
288
+ author: result.author,
289
+ files: changes.map(({ diff: _diff, ...file }) => file),
290
+ changes,
291
+ truncated,
292
+ limitations: limitations.map((limitation) => ctx.t(limitation, { ns: 'plugin-git-manager' })),
293
+ };
294
+ }
295
+ return content;
296
+ }
297
+
298
+ export async function chatContextContent(ctx: Context, next: () => Promise<void>) {
299
+ const content = await loadChatContext(ctx, getEffectiveActionParams(ctx));
300
+ ctx.body = { success: true, data: content };
301
+ await next();
302
+ }
@@ -1,17 +1,10 @@
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 simpleGit, { SimpleGit } from 'simple-git';
11
4
  import { Context } from '@nocobase/actions';
12
5
  import * as path from 'path';
13
6
  import * as fs from 'fs';
14
- import { spawnSync } from 'child_process';
7
+ import { spawn, spawnSync } from 'child_process';
15
8
  import { getEffectiveActionParams } from '../repository-access';
16
9
  import { redactError } from '../utils/redact';
17
10
  import { getRepoAccount } from '../utils/get-repo-account';
@@ -32,6 +25,7 @@ interface GitActionParams {
32
25
  commitHash?: string;
33
26
  compareHash?: string;
34
27
  maxCount?: number | string;
28
+ skip?: number | string;
35
29
  branch?: string;
36
30
  ref?: string;
37
31
  treePath?: string;
@@ -212,8 +206,8 @@ function getGit(ctx: Context, localPath: string): SimpleGit {
212
206
  return createGit(localPath);
213
207
  }
214
208
 
215
- export async function getRepo(ctx: Context) {
216
- const { repositoryId } = getGitActionParams(ctx);
209
+ export async function getRepo(ctx: Context, requestedRepositoryId?: number | string) {
210
+ const repositoryId = requestedRepositoryId ?? getGitActionParams(ctx).repositoryId;
217
211
  const repo = await ctx.db.getRepository('gitRepositories').findOne({
218
212
  filterByTk: repositoryId,
219
213
  });
@@ -386,16 +380,31 @@ export async function status(ctx: Context, next: () => Promise<void>) {
386
380
  export async function log(ctx: Context, next: () => Promise<void>) {
387
381
  const repo = await getRepo(ctx);
388
382
  const localPath = validateLocalPath(repo.get('localPath'));
389
- const { maxCount = 50, file } = getGitActionParams(ctx);
383
+ const { maxCount = 50, file, branch, skip } = getGitActionParams(ctx);
390
384
 
391
385
  const parsed = Number.parseInt(String(maxCount), 10);
392
- const options: Record<string, any> = { maxCount: Math.min(Math.max(parsed || 50, 1), 500) };
386
+ const options: { maxCount: number; file?: string } = { maxCount: Math.min(Math.max(parsed || 50, 1), 500) };
393
387
  if (file) {
394
388
  if (file.includes('..')) ctx.throw(400, 'Invalid file path');
395
389
  options.file = file;
396
390
  }
397
391
 
398
- const result = await getGit(ctx, localPath).log(options);
392
+ const args: string[] = [];
393
+ if (branch) args.push(validateBranch(branch));
394
+ if (skip !== undefined) {
395
+ const parsedSkip = Number(skip);
396
+ if (!Number.isSafeInteger(parsedSkip) || parsedSkip < 0 || parsedSkip > 1000000) {
397
+ ctx.throw(400, 'Invalid history offset');
398
+ }
399
+ args.push(`--skip=${parsedSkip}`);
400
+ }
401
+ const result = args.length
402
+ ? await getGit(ctx, localPath).log([
403
+ ...args,
404
+ `--max-count=${options.maxCount}`,
405
+ ...(file ? ['--follow', '--', file] : []),
406
+ ])
407
+ : await getGit(ctx, localPath).log(options);
399
408
  ctx.body = { success: true, data: result };
400
409
  await next();
401
410
  }
@@ -538,3 +547,100 @@ export async function commitDetail(ctx: Context, next: () => Promise<void>) {
538
547
  };
539
548
  await next();
540
549
  }
550
+
551
+ async function readLimitedGitOutput(localPath: string, args: string[], maxBytes: number) {
552
+ return new Promise<{ text: string; truncated: boolean }>((resolve, reject) => {
553
+ const process = spawn(GIT_BINARY, args, {
554
+ cwd: localPath,
555
+ env: gitProcessEnvironment(),
556
+ windowsHide: true,
557
+ stdio: ['ignore', 'pipe', 'ignore'],
558
+ });
559
+ const chunks: Buffer[] = [];
560
+ let size = 0;
561
+ let truncated = false;
562
+ process.stdout.on('data', (chunk: Buffer) => {
563
+ const remaining = maxBytes - size;
564
+ if (remaining > 0) {
565
+ const data = chunk.subarray(0, remaining);
566
+ chunks.push(data);
567
+ size += data.length;
568
+ }
569
+ if (chunk.length > remaining) {
570
+ truncated = true;
571
+ process.kill();
572
+ }
573
+ });
574
+ process.on('error', reject);
575
+ process.on('close', (code) => {
576
+ if (code !== 0 && !truncated) {
577
+ reject(new Error('Unable to read commit diff'));
578
+ return;
579
+ }
580
+ const text = Buffer.concat(chunks)
581
+ .toString('utf8')
582
+ .replace(/\uFFFD$/, '');
583
+ resolve({ text, truncated });
584
+ });
585
+ });
586
+ }
587
+
588
+ /** Build a bounded commit context, comparing merge commits with their first parent. */
589
+ export async function readChatCommit(
590
+ ctx: Context,
591
+ commitHash: string,
592
+ maxFiles: number,
593
+ maxBytes: number,
594
+ repositoryId?: number | string,
595
+ ) {
596
+ if (!/^[a-f\d]{4,64}$/i.test(commitHash)) ctx.throw(400, 'Invalid commit hash');
597
+ const repo = await getRepo(ctx, repositoryId);
598
+ const localPath = validateLocalPath(repo.get('localPath'));
599
+ const git = getGit(ctx, localPath);
600
+ const hash = (await git.raw(['rev-parse', '--verify', `${commitHash}^{commit}`])).trim();
601
+ const [metadata, parentLine] = await Promise.all([
602
+ git.raw(['show', '-s', '--format=%H%x00%an%x00%aI%x00%s%x00%b', hash]),
603
+ git.raw(['rev-list', '--parents', '-n', '1', hash]),
604
+ ]);
605
+ const [, author, date, subject, body] = metadata.split('\0');
606
+ const parent = parentLine.trim().split(/\s+/)[1];
607
+ const namesArgs = parent
608
+ ? ['diff', '--name-status', '-z', '-M', parent, hash, '--']
609
+ : ['diff-tree', '--root', '--no-commit-id', '-r', '--name-status', '-z', '-M', hash, '--'];
610
+ const tokens = (await git.raw(namesArgs)).split('\0');
611
+ const files: Array<{ oldPath: string; newPath: string; status: string }> = [];
612
+ for (let index = 0; index < tokens.length && tokens[index]; ) {
613
+ const status = tokens[index++];
614
+ const oldPath = tokens[index++];
615
+ const newPath = /^[RC]/.test(status) ? tokens[index++] : oldPath;
616
+ if (!oldPath || !newPath) break;
617
+ files.push({ oldPath, newPath, status });
618
+ }
619
+ const selectedFiles = files.slice(0, maxFiles);
620
+ const paths = Array.from(new Set(selectedFiles.flatMap((file) => [file.oldPath, file.newPath]))).map(
621
+ (file) => `:(literal)${file}`,
622
+ );
623
+ const patchArgs = parent
624
+ ? ['diff', '--no-ext-diff', '--no-textconv', '--no-color', parent, hash, '--', ...paths]
625
+ : ['show', '--format=', '--no-ext-diff', '--no-textconv', '--no-color', hash, '--', ...paths];
626
+ const patch = paths.length
627
+ ? await readLimitedGitOutput(localPath, patchArgs, maxBytes)
628
+ : { text: '', truncated: false };
629
+ const limitations: string[] = [];
630
+ if (files.length > maxFiles) limitations.push('Additional changed files were omitted.');
631
+ if (patch.truncated) limitations.push('The diff was truncated to the configured limit.');
632
+ if (/^Binary files .* differ$|^GIT binary patch$/m.test(patch.text)) {
633
+ limitations.push('Binary file contents are not included in the diff.');
634
+ }
635
+ return {
636
+ commitSha: hash,
637
+ author,
638
+ date,
639
+ subject,
640
+ body: body?.trim(),
641
+ files: selectedFiles,
642
+ diff: patch.text,
643
+ truncated: patch.truncated || files.length > maxFiles,
644
+ limitations,
645
+ };
646
+ }
@@ -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 { Context } from '@nocobase/actions';
11
4
  import { getEffectiveActionParams } from '../repository-access';
@@ -38,15 +31,21 @@ async function gitlabFetch(apiBase: string, endpoint: string, pat: string, param
38
31
  // Extract pagination info from response headers
39
32
  const totalPages = response.headers.get('x-total-pages');
40
33
  const total = response.headers.get('x-total');
34
+ const nextPage = response.headers.get('x-next-page');
41
35
 
42
36
  const data = await response.json();
43
- return { data, totalPages: totalPages ? parseInt(totalPages, 10) : null, total: total ? parseInt(total, 10) : null };
37
+ return {
38
+ data,
39
+ totalPages: totalPages ? parseInt(totalPages, 10) : null,
40
+ total: total ? parseInt(total, 10) : null,
41
+ hasMore: nextPage !== null ? Boolean(nextPage) : null,
42
+ };
44
43
  }
45
44
 
46
- async function getRepoApiContext(ctx: Context) {
45
+ async function getRepoApiContext(ctx: Context, requestedRepositoryId?: number | string) {
47
46
  // Fix for POST requests where data might be in ctx.request.body
48
47
  const params = getEffectiveActionParams(ctx);
49
- const { repositoryId } = params;
48
+ const repositoryId = requestedRepositoryId ?? params.repositoryId;
50
49
  if (typeof repositoryId !== 'string' && typeof repositoryId !== 'number') ctx.throw(400, 'repositoryId is required');
51
50
 
52
51
  const repo = await ctx.db.getRepository('gitRepositories').findOne({
@@ -99,7 +98,8 @@ async function githubFetch(endpoint: string, pat: string, params?: Record<string
99
98
  }
100
99
 
101
100
  const data = await response.json();
102
- return { data, totalPages, total: null };
101
+ const hasMore = linkHeader ? linkHeader.split(',').some((link) => link.includes('rel="next"')) : false;
102
+ return { data, totalPages, total: null, hasMore };
103
103
  }
104
104
 
105
105
  export async function mergeRequests(ctx: Context, next: () => Promise<void>) {
@@ -222,6 +222,11 @@ export async function mergeRequests(ctx: Context, next: () => Promise<void>) {
222
222
  perPage: parseInt(String(perPage), 10),
223
223
  total: result.total,
224
224
  totalPages: result.totalPages,
225
+ hasMore:
226
+ result.hasMore ??
227
+ (result.totalPages !== null
228
+ ? Number(page) < result.totalPages
229
+ : result.data.length >= Math.min(parseInt(String(perPage), 10) || 20, 100)),
225
230
  },
226
231
  };
227
232
  await next();
@@ -357,6 +362,87 @@ export async function mergeRequestDetail(ctx: Context, next: () => Promise<void>
357
362
  await next();
358
363
  }
359
364
 
365
+ /** Read enough provider data to detect omitted files without hiding provider errors. */
366
+ export async function readChatMergeRequest(ctx: Context, mrIid: number, repositoryId?: number | string) {
367
+ const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx, repositoryId);
368
+ if (isGitHub) {
369
+ const [request, fileResult] = await Promise.all([
370
+ githubFetch(`/repos/${projectPath}/pulls/${mrIid}`, pat),
371
+ githubFetch(`/repos/${projectPath}/pulls/${mrIid}/files`, pat, { page: 1, per_page: 51 }),
372
+ ]);
373
+ const item = request.data;
374
+ if (!Array.isArray(fileResult.data)) throw new Error('Unable to read merge request changes');
375
+ const files = fileResult.data.map(
376
+ (file: { filename: string; previous_filename?: string; status?: string; patch?: string }) => ({
377
+ oldPath: file.previous_filename || file.filename,
378
+ newPath: file.filename,
379
+ status: file.status,
380
+ diff: file.patch,
381
+ }),
382
+ );
383
+ const limitations: string[] = [];
384
+ if (typeof item.changed_files === 'number' && item.changed_files > files.length) {
385
+ limitations.push('Additional changed files were omitted by the provider.');
386
+ }
387
+ if (files.some((file: { diff?: string }) => !file.diff)) {
388
+ limitations.push('The provider omitted patches for one or more files, including binary or large files.');
389
+ }
390
+ return {
391
+ title: item.title,
392
+ description: item.body,
393
+ state: item.state === 'open' ? 'opened' : item.merged_at ? 'merged' : 'closed',
394
+ sourceBranch: item.head?.ref,
395
+ targetBranch: item.base?.ref,
396
+ author: item.user?.login,
397
+ files,
398
+ limitations,
399
+ };
400
+ }
401
+
402
+ if (!pat) ctx.throw(400, 'Personal Access Token is required for GitLab API access');
403
+ const [request, changeResult] = await Promise.all([
404
+ gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${mrIid}`, pat),
405
+ gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${mrIid}/changes`, pat),
406
+ ]);
407
+ const item = request.data;
408
+ const changeData = changeResult.data || {};
409
+ if (!Array.isArray(changeData.changes)) throw new Error('Unable to read merge request changes');
410
+ const files = changeData.changes.map(
411
+ (file: {
412
+ old_path?: string;
413
+ new_path?: string;
414
+ new_file?: boolean;
415
+ deleted_file?: boolean;
416
+ renamed_file?: boolean;
417
+ diff?: string;
418
+ collapsed?: boolean;
419
+ too_large?: boolean;
420
+ binary?: boolean;
421
+ }) => ({
422
+ oldPath: file.old_path,
423
+ newPath: file.new_path,
424
+ status: file.new_file ? 'added' : file.deleted_file ? 'removed' : file.renamed_file ? 'renamed' : 'modified',
425
+ diff: file.diff,
426
+ unavailable: file.collapsed || file.too_large || file.binary || !file.diff,
427
+ }),
428
+ );
429
+ const limitations: string[] = [];
430
+ if (changeData.overflow) limitations.push('The provider omitted additional changed files or patches.');
431
+ if (files.some((file: { unavailable?: boolean }) => file.unavailable)) {
432
+ limitations.push('The provider omitted patches for one or more files, including binary or large files.');
433
+ }
434
+ return {
435
+ title: item.title,
436
+ description: item.description,
437
+ state: item.state,
438
+ sourceBranch: item.source_branch,
439
+ targetBranch: item.target_branch,
440
+ author: item.author?.username || item.author?.name,
441
+ files,
442
+ limitations,
443
+ };
444
+ }
445
+
360
446
  export async function mergeRequestNotes(ctx: Context, next: () => Promise<void>) {
361
447
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
362
448
  const params = getEffectiveActionParams(ctx);
@@ -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 { Context } from '@nocobase/actions';
11
4
  import { pollAllRepos, pollOneRepo, getPollerStatus } from '../poller';
@@ -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 type { Context } from '@nocobase/actions';
11
4
  import type { GitReviewService } from '../services/review-service';
@@ -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 { Context } from '@nocobase/actions';
11
4
  import type { Application } from '@nocobase/server';
@@ -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 type { Database, Model } from '@nocobase/database';
11
4