plugin-git-manager 1.3.3 → 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 (44) hide show
  1. package/dist/client/{156.c27c2392746e7866.js → 156.8e36af3e2cee173e.js} +1 -1
  2. package/dist/client/{317.17ed0018e3e7db00.js → 317.2d0d33871e24ee24.js} +1 -1
  3. package/dist/client/{434.b2eeaaef33aae6e0.js → 434.2401f7257495b66e.js} +1 -1
  4. package/dist/client/{453.fc3042c9740d8fab.js → 453.58657b9ba0904477.js} +1 -1
  5. package/dist/client/index.js +1 -1
  6. package/dist/client-v2/{434.19c7579c06b9077c.js → 434.32b0a07b821b9329.js} +1 -1
  7. package/dist/client-v2/{453.5e507c94c59277b1.js → 453.f9a0ec6d8e1bd1cc.js} +1 -1
  8. package/dist/client-v2/index.js +1 -1
  9. package/dist/externalVersion.js +10 -9
  10. package/dist/locale/en-US.json +27 -1
  11. package/dist/locale/vi-VN.json +27 -1
  12. package/dist/locale/zh-CN.json +30 -1
  13. package/dist/node_modules/simple-git/package.json +1 -1
  14. package/dist/node_modules/zod/package.json +1 -1
  15. package/dist/server/actions/chat-context.js +282 -0
  16. package/dist/server/actions/git-actions.js +99 -4
  17. package/dist/server/actions/gitlab-api.js +86 -7
  18. package/dist/server/chat-context-admission.js +187 -0
  19. package/dist/server/plugin.js +8 -0
  20. package/dist/server/request-method-policy.js +2 -0
  21. package/package.json +2 -2
  22. package/src/client/__tests__/GitContextPicker.test.tsx +120 -0
  23. package/src/client/__tests__/ai-context.test.tsx +119 -0
  24. package/src/client/ai-context.tsx +3 -113
  25. package/src/client/context/GitManagerContext.tsx +18 -2
  26. package/src/client/index.tsx +3 -5
  27. package/src/client-v2/ai-context.tsx +135 -72
  28. package/src/client-v2/components/GitContextPicker.tsx +418 -0
  29. package/src/client-v2/git-context-api.ts +59 -0
  30. package/src/client-v2/plugin.tsx +2 -4
  31. package/src/locale/en-US.json +27 -1
  32. package/src/locale/vi-VN.json +27 -1
  33. package/src/locale/zh-CN.json +30 -1
  34. package/src/server/__tests__/chat-context-admission.test.ts +276 -0
  35. package/src/server/__tests__/chat-context-options.test.ts +144 -0
  36. package/src/server/__tests__/git-chat-context.test.ts +138 -0
  37. package/src/server/__tests__/git-security.test.ts +52 -0
  38. package/src/server/__tests__/smoke.test.ts +200 -0
  39. package/src/server/actions/chat-context.ts +302 -0
  40. package/src/server/actions/git-actions.ts +119 -6
  41. package/src/server/actions/gitlab-api.ts +97 -4
  42. package/src/server/chat-context-admission.ts +182 -0
  43. package/src/server/plugin.ts +11 -0
  44. package/src/server/request-method-policy.ts +2 -0
@@ -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
+ }
@@ -4,7 +4,7 @@ import simpleGit, { SimpleGit } from 'simple-git';
4
4
  import { Context } from '@nocobase/actions';
5
5
  import * as path from 'path';
6
6
  import * as fs from 'fs';
7
- import { spawnSync } from 'child_process';
7
+ import { spawn, spawnSync } from 'child_process';
8
8
  import { getEffectiveActionParams } from '../repository-access';
9
9
  import { redactError } from '../utils/redact';
10
10
  import { getRepoAccount } from '../utils/get-repo-account';
@@ -25,6 +25,7 @@ interface GitActionParams {
25
25
  commitHash?: string;
26
26
  compareHash?: string;
27
27
  maxCount?: number | string;
28
+ skip?: number | string;
28
29
  branch?: string;
29
30
  ref?: string;
30
31
  treePath?: string;
@@ -205,8 +206,8 @@ function getGit(ctx: Context, localPath: string): SimpleGit {
205
206
  return createGit(localPath);
206
207
  }
207
208
 
208
- export async function getRepo(ctx: Context) {
209
- const { repositoryId } = getGitActionParams(ctx);
209
+ export async function getRepo(ctx: Context, requestedRepositoryId?: number | string) {
210
+ const repositoryId = requestedRepositoryId ?? getGitActionParams(ctx).repositoryId;
210
211
  const repo = await ctx.db.getRepository('gitRepositories').findOne({
211
212
  filterByTk: repositoryId,
212
213
  });
@@ -379,16 +380,31 @@ export async function status(ctx: Context, next: () => Promise<void>) {
379
380
  export async function log(ctx: Context, next: () => Promise<void>) {
380
381
  const repo = await getRepo(ctx);
381
382
  const localPath = validateLocalPath(repo.get('localPath'));
382
- const { maxCount = 50, file } = getGitActionParams(ctx);
383
+ const { maxCount = 50, file, branch, skip } = getGitActionParams(ctx);
383
384
 
384
385
  const parsed = Number.parseInt(String(maxCount), 10);
385
- 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) };
386
387
  if (file) {
387
388
  if (file.includes('..')) ctx.throw(400, 'Invalid file path');
388
389
  options.file = file;
389
390
  }
390
391
 
391
- 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);
392
408
  ctx.body = { success: true, data: result };
393
409
  await next();
394
410
  }
@@ -531,3 +547,100 @@ export async function commitDetail(ctx: Context, next: () => Promise<void>) {
531
547
  };
532
548
  await next();
533
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
+ }
@@ -31,15 +31,21 @@ async function gitlabFetch(apiBase: string, endpoint: string, pat: string, param
31
31
  // Extract pagination info from response headers
32
32
  const totalPages = response.headers.get('x-total-pages');
33
33
  const total = response.headers.get('x-total');
34
+ const nextPage = response.headers.get('x-next-page');
34
35
 
35
36
  const data = await response.json();
36
- 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
+ };
37
43
  }
38
44
 
39
- async function getRepoApiContext(ctx: Context) {
45
+ async function getRepoApiContext(ctx: Context, requestedRepositoryId?: number | string) {
40
46
  // Fix for POST requests where data might be in ctx.request.body
41
47
  const params = getEffectiveActionParams(ctx);
42
- const { repositoryId } = params;
48
+ const repositoryId = requestedRepositoryId ?? params.repositoryId;
43
49
  if (typeof repositoryId !== 'string' && typeof repositoryId !== 'number') ctx.throw(400, 'repositoryId is required');
44
50
 
45
51
  const repo = await ctx.db.getRepository('gitRepositories').findOne({
@@ -92,7 +98,8 @@ async function githubFetch(endpoint: string, pat: string, params?: Record<string
92
98
  }
93
99
 
94
100
  const data = await response.json();
95
- 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 };
96
103
  }
97
104
 
98
105
  export async function mergeRequests(ctx: Context, next: () => Promise<void>) {
@@ -215,6 +222,11 @@ export async function mergeRequests(ctx: Context, next: () => Promise<void>) {
215
222
  perPage: parseInt(String(perPage), 10),
216
223
  total: result.total,
217
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)),
218
230
  },
219
231
  };
220
232
  await next();
@@ -350,6 +362,87 @@ export async function mergeRequestDetail(ctx: Context, next: () => Promise<void>
350
362
  await next();
351
363
  }
352
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
+
353
446
  export async function mergeRequestNotes(ctx: Context, next: () => Promise<void>) {
354
447
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
355
448
  const params = getEffectiveActionParams(ctx);