plugin-git-manager 1.3.3 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/{156.c27c2392746e7866.js → 156.8e36af3e2cee173e.js} +1 -1
- package/dist/client/317.e7b1d59371812c30.js +10 -0
- package/dist/client/434.05d0ba2b821105dc.js +10 -0
- package/dist/client/453.cdcba6d2d0c9522b.js +10 -0
- package/dist/client/454.625da741a7e1161f.js +10 -0
- package/dist/client/index.js +1 -1
- package/dist/client-v2/317.4e116f84ed9081b6.js +10 -0
- package/dist/client-v2/434.764113d20743a45b.js +10 -0
- package/dist/client-v2/453.5ab80c06d8e61a7e.js +10 -0
- package/dist/client-v2/454.b885b1d35ef7ff72.js +10 -0
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +10 -9
- package/dist/locale/en-US.json +38 -1
- package/dist/locale/vi-VN.json +38 -1
- package/dist/locale/zh-CN.json +41 -1
- package/dist/node_modules/simple-git/package.json +1 -1
- package/dist/node_modules/zod/package.json +1 -1
- package/dist/server/actions/chat-context.js +282 -0
- package/dist/server/actions/git-actions.js +387 -80
- package/dist/server/actions/gitlab-api.js +101 -15
- package/dist/server/actions/subtree.js +20 -10
- package/dist/server/chat-context-admission.js +187 -0
- package/dist/server/plugin.js +142 -10
- package/dist/server/repository-access.js +2 -2
- package/dist/server/request-method-policy.js +4 -1
- package/dist/server/services/review-source.js +2 -1
- package/dist/server/utils/cluster-git.js +181 -0
- package/package.json +2 -2
- package/src/client/__tests__/FileExplorerAndManage.test.tsx +236 -0
- package/src/client/__tests__/GitContextPicker.test.tsx +120 -0
- package/src/client/__tests__/ai-context.test.tsx +119 -0
- package/src/client/__tests__/workflowRoutes.test.ts +3 -1
- package/src/client/ai-context.tsx +3 -113
- package/src/client/components/CommitHistory.tsx +19 -7
- package/src/client/components/FileExplorer.tsx +80 -34
- package/src/client/components/GitManagerSettings.tsx +21 -5
- package/src/client/components/GitOperations.tsx +25 -4
- package/src/client/components/GitRuntimeBanner.tsx +97 -0
- package/src/client/components/RepositoryConfig.tsx +28 -6
- package/src/client/context/GitManagerContext.tsx +174 -15
- package/src/client/index.tsx +3 -5
- package/src/client/workflowRoutes.ts +11 -0
- package/src/client-v2/ai-context.tsx +135 -72
- package/src/client-v2/components/GitContextPicker.tsx +418 -0
- package/src/client-v2/git-context-api.ts +59 -0
- package/src/client-v2/plugin.tsx +2 -4
- package/src/locale/en-US.json +38 -1
- package/src/locale/vi-VN.json +38 -1
- package/src/locale/zh-CN.json +41 -1
- package/src/server/__tests__/chat-context-admission.test.ts +276 -0
- package/src/server/__tests__/chat-context-options.test.ts +144 -0
- package/src/server/__tests__/git-actions.test.ts +329 -4
- package/src/server/__tests__/git-chat-context.test.ts +138 -0
- package/src/server/__tests__/git-security.test.ts +52 -0
- package/src/server/__tests__/smoke.test.ts +232 -1
- package/src/server/actions/chat-context.ts +302 -0
- package/src/server/actions/git-actions.ts +428 -89
- package/src/server/actions/gitlab-api.ts +113 -14
- package/src/server/actions/subtree.ts +23 -6
- package/src/server/chat-context-admission.ts +182 -0
- package/src/server/plugin.ts +163 -3
- package/src/server/repository-access.ts +2 -2
- package/src/server/request-method-policy.ts +3 -0
- package/src/server/services/review-source.ts +3 -2
- package/src/server/utils/cluster-git.ts +209 -0
- package/dist/client/317.17ed0018e3e7db00.js +0 -10
- package/dist/client/434.b2eeaaef33aae6e0.js +0 -10
- package/dist/client/453.fc3042c9740d8fab.js +0 -10
- package/dist/client-v2/317.d2466574d00f94d0.js +0 -10
- package/dist/client-v2/434.19c7579c06b9077c.js +0 -10
- package/dist/client-v2/453.5e507c94c59277b1.js +0 -10
|
@@ -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 {
|
|
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
|
|
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
|
-
|
|
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,19 +222,32 @@ 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();
|
|
221
233
|
}
|
|
222
234
|
|
|
235
|
+
function parseMrIid(value: unknown, ctx: Context): number {
|
|
236
|
+
if (value === undefined || value === null || value === '') {
|
|
237
|
+
ctx.throw(400, 'mrIid is required');
|
|
238
|
+
}
|
|
239
|
+
const text = String(value).trim();
|
|
240
|
+
const parsed = typeof value === 'number' ? value : Number(text);
|
|
241
|
+
if (!/^\d+$/.test(text) || !Number.isSafeInteger(parsed) || parsed < 1) {
|
|
242
|
+
ctx.throw(400, 'Invalid merge request ID');
|
|
243
|
+
}
|
|
244
|
+
return parsed;
|
|
245
|
+
}
|
|
246
|
+
|
|
223
247
|
export async function mergeRequestDetail(ctx: Context, next: () => Promise<void>) {
|
|
224
248
|
const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
|
|
225
249
|
const params = getEffectiveActionParams(ctx);
|
|
226
|
-
const
|
|
227
|
-
|
|
228
|
-
if (!mrIid) {
|
|
229
|
-
ctx.throw(400, 'mrIid is required');
|
|
230
|
-
}
|
|
250
|
+
const mrIid = parseMrIid(params.mrIid, ctx);
|
|
231
251
|
|
|
232
252
|
let data;
|
|
233
253
|
if (isGitHub) {
|
|
@@ -350,14 +370,93 @@ export async function mergeRequestDetail(ctx: Context, next: () => Promise<void>
|
|
|
350
370
|
await next();
|
|
351
371
|
}
|
|
352
372
|
|
|
373
|
+
/** Read enough provider data to detect omitted files without hiding provider errors. */
|
|
374
|
+
export async function readChatMergeRequest(ctx: Context, mrIid: number, repositoryId?: number | string) {
|
|
375
|
+
const validMrIid = parseMrIid(mrIid, ctx);
|
|
376
|
+
const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx, repositoryId);
|
|
377
|
+
if (isGitHub) {
|
|
378
|
+
const [request, fileResult] = await Promise.all([
|
|
379
|
+
githubFetch(`/repos/${projectPath}/pulls/${validMrIid}`, pat),
|
|
380
|
+
githubFetch(`/repos/${projectPath}/pulls/${validMrIid}/files`, pat, { page: 1, per_page: 51 }),
|
|
381
|
+
]);
|
|
382
|
+
const item = request.data;
|
|
383
|
+
if (!Array.isArray(fileResult.data)) throw new Error('Unable to read merge request changes');
|
|
384
|
+
const files = fileResult.data.map(
|
|
385
|
+
(file: { filename: string; previous_filename?: string; status?: string; patch?: string }) => ({
|
|
386
|
+
oldPath: file.previous_filename || file.filename,
|
|
387
|
+
newPath: file.filename,
|
|
388
|
+
status: file.status,
|
|
389
|
+
diff: file.patch,
|
|
390
|
+
}),
|
|
391
|
+
);
|
|
392
|
+
const limitations: string[] = [];
|
|
393
|
+
if (typeof item.changed_files === 'number' && item.changed_files > files.length) {
|
|
394
|
+
limitations.push('Additional changed files were omitted by the provider.');
|
|
395
|
+
}
|
|
396
|
+
if (files.some((file: { diff?: string }) => !file.diff)) {
|
|
397
|
+
limitations.push('The provider omitted patches for one or more files, including binary or large files.');
|
|
398
|
+
}
|
|
399
|
+
return {
|
|
400
|
+
title: item.title,
|
|
401
|
+
description: item.body,
|
|
402
|
+
state: item.state === 'open' ? 'opened' : item.merged_at ? 'merged' : 'closed',
|
|
403
|
+
sourceBranch: item.head?.ref,
|
|
404
|
+
targetBranch: item.base?.ref,
|
|
405
|
+
author: item.user?.login,
|
|
406
|
+
files,
|
|
407
|
+
limitations,
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
if (!pat) ctx.throw(400, 'Personal Access Token is required for GitLab API access');
|
|
412
|
+
const [request, changeResult] = await Promise.all([
|
|
413
|
+
gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${validMrIid}`, pat),
|
|
414
|
+
gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${validMrIid}/changes`, pat),
|
|
415
|
+
]);
|
|
416
|
+
const item = request.data;
|
|
417
|
+
const changeData = changeResult.data || {};
|
|
418
|
+
if (!Array.isArray(changeData.changes)) throw new Error('Unable to read merge request changes');
|
|
419
|
+
const files = changeData.changes.map(
|
|
420
|
+
(file: {
|
|
421
|
+
old_path?: string;
|
|
422
|
+
new_path?: string;
|
|
423
|
+
new_file?: boolean;
|
|
424
|
+
deleted_file?: boolean;
|
|
425
|
+
renamed_file?: boolean;
|
|
426
|
+
diff?: string;
|
|
427
|
+
collapsed?: boolean;
|
|
428
|
+
too_large?: boolean;
|
|
429
|
+
binary?: boolean;
|
|
430
|
+
}) => ({
|
|
431
|
+
oldPath: file.old_path,
|
|
432
|
+
newPath: file.new_path,
|
|
433
|
+
status: file.new_file ? 'added' : file.deleted_file ? 'removed' : file.renamed_file ? 'renamed' : 'modified',
|
|
434
|
+
diff: file.diff,
|
|
435
|
+
unavailable: file.collapsed || file.too_large || file.binary || !file.diff,
|
|
436
|
+
}),
|
|
437
|
+
);
|
|
438
|
+
const limitations: string[] = [];
|
|
439
|
+
if (changeData.overflow) limitations.push('The provider omitted additional changed files or patches.');
|
|
440
|
+
if (files.some((file: { unavailable?: boolean }) => file.unavailable)) {
|
|
441
|
+
limitations.push('The provider omitted patches for one or more files, including binary or large files.');
|
|
442
|
+
}
|
|
443
|
+
return {
|
|
444
|
+
title: item.title,
|
|
445
|
+
description: item.description,
|
|
446
|
+
state: item.state,
|
|
447
|
+
sourceBranch: item.source_branch,
|
|
448
|
+
targetBranch: item.target_branch,
|
|
449
|
+
author: item.author?.username || item.author?.name,
|
|
450
|
+
files,
|
|
451
|
+
limitations,
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
|
|
353
455
|
export async function mergeRequestNotes(ctx: Context, next: () => Promise<void>) {
|
|
354
456
|
const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
|
|
355
457
|
const params = getEffectiveActionParams(ctx);
|
|
356
|
-
const {
|
|
357
|
-
|
|
358
|
-
if (!mrIid) {
|
|
359
|
-
ctx.throw(400, 'mrIid is required');
|
|
360
|
-
}
|
|
458
|
+
const { page = 1, perPage = 50 } = params;
|
|
459
|
+
const mrIid = parseMrIid(params.mrIid, ctx);
|
|
361
460
|
|
|
362
461
|
let notes = [];
|
|
363
462
|
const pagination = {
|
|
@@ -1,9 +1,18 @@
|
|
|
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
|
+
|
|
1
10
|
import { Context } from '@nocobase/actions';
|
|
2
11
|
import * as fs from 'fs';
|
|
3
12
|
import * as os from 'os';
|
|
4
13
|
import * as path from 'path';
|
|
5
14
|
import type { SimpleGit } from 'simple-git';
|
|
6
|
-
import { createGit, validateBranch, validateLocalPath, withAuth } from './git-actions';
|
|
15
|
+
import { createGit, getGit, validateBranch, validateLocalPath, withAuth, type RepoLockManager } from './git-actions';
|
|
7
16
|
import { getEffectiveActionParams } from '../repository-access';
|
|
8
17
|
import { getRepoAccount } from '../utils/get-repo-account';
|
|
9
18
|
import { redactError, redactPat } from '../utils/redact';
|
|
@@ -329,7 +338,8 @@ export async function subtreeOptions(ctx: Context, next: () => Promise<void>) {
|
|
|
329
338
|
if (!account) ctx.throw(400, 'Repository has no Git account configured');
|
|
330
339
|
const localPath = validateLocalPath(stringValue(repo.get('localPath')));
|
|
331
340
|
const repoUrl = stringValue(repo.get('repoUrl'));
|
|
332
|
-
const git =
|
|
341
|
+
const git = await getGit(ctx, localPath);
|
|
342
|
+
const lockManager = (ctx as Context & { app?: { lockManager?: RepoLockManager } }).app?.lockManager;
|
|
333
343
|
|
|
334
344
|
try {
|
|
335
345
|
const data = await withAuth(
|
|
@@ -365,11 +375,13 @@ export async function subtreeOptions(ctx: Context, next: () => Promise<void>) {
|
|
|
365
375
|
},
|
|
366
376
|
account.username,
|
|
367
377
|
remoteName,
|
|
378
|
+
lockManager,
|
|
368
379
|
);
|
|
369
380
|
ctx.body = { success: true, data };
|
|
370
381
|
} catch (error) {
|
|
382
|
+
const status = (error as { status?: number })?.status === 503 ? 503 : 400;
|
|
371
383
|
const safeError = redactError(error);
|
|
372
|
-
ctx.throw(
|
|
384
|
+
ctx.throw(status, ctx.t(safeError.message, { ns: 'plugin-git-manager' }));
|
|
373
385
|
}
|
|
374
386
|
await next();
|
|
375
387
|
}
|
|
@@ -381,7 +393,8 @@ export async function subtreePreview(ctx: Context, next: () => Promise<void>) {
|
|
|
381
393
|
const { config, repo, account } = await loadConfigAndRepository(ctx, configId);
|
|
382
394
|
const localPath = validateLocalPath(stringValue(repo.get('localPath')));
|
|
383
395
|
const repoUrl = stringValue(repo.get('repoUrl'));
|
|
384
|
-
const git =
|
|
396
|
+
const git = await getGit(ctx, localPath);
|
|
397
|
+
const lockManager = (ctx as Context & { app?: { lockManager?: RepoLockManager } }).app?.lockManager;
|
|
385
398
|
|
|
386
399
|
try {
|
|
387
400
|
const preview = await withAuth(
|
|
@@ -392,11 +405,13 @@ export async function subtreePreview(ctx: Context, next: () => Promise<void>) {
|
|
|
392
405
|
() => createPreview(git, config),
|
|
393
406
|
account.username,
|
|
394
407
|
config.remoteName,
|
|
408
|
+
lockManager,
|
|
395
409
|
);
|
|
396
410
|
ctx.body = { success: true, data: preview };
|
|
397
411
|
} catch (error) {
|
|
412
|
+
const status = (error as { status?: number })?.status === 503 ? 503 : 400;
|
|
398
413
|
const safeError = redactError(error);
|
|
399
|
-
ctx.throw(
|
|
414
|
+
ctx.throw(status, ctx.t(safeError.message, { ns: 'plugin-git-manager' }));
|
|
400
415
|
}
|
|
401
416
|
await next();
|
|
402
417
|
}
|
|
@@ -421,7 +436,8 @@ export async function subtreeRunOnAppProcess(ctx: Context, next: () => Promise<v
|
|
|
421
436
|
const { config, repo, account } = await loadConfigAndRepository(ctx, runParams.configId);
|
|
422
437
|
const localPath = validateLocalPath(stringValue(repo.get('localPath')));
|
|
423
438
|
const repoUrl = stringValue(repo.get('repoUrl'));
|
|
424
|
-
const git =
|
|
439
|
+
const git = await getGit(ctx, localPath);
|
|
440
|
+
const lockManager = (ctx as Context & { app?: { lockManager?: RepoLockManager } }).app?.lockManager;
|
|
425
441
|
const runsRepository = ctx.db.getRepository('gitSubtreeRuns');
|
|
426
442
|
const startedAt = new Date();
|
|
427
443
|
const run = await runsRepository.create({
|
|
@@ -462,6 +478,7 @@ export async function subtreeRunOnAppProcess(ctx: Context, next: () => Promise<v
|
|
|
462
478
|
},
|
|
463
479
|
account.username,
|
|
464
480
|
config.remoteName,
|
|
481
|
+
lockManager,
|
|
465
482
|
);
|
|
466
483
|
|
|
467
484
|
const finishedAt = new Date();
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import type { Context } from '@nocobase/actions';
|
|
4
|
+
import { loadChatContext } from './actions/chat-context';
|
|
5
|
+
|
|
6
|
+
type GitContextType = 'git-repository' | 'git-merge-request' | 'git-commit';
|
|
7
|
+
type GitContextItem = { type: GitContextType; uid: string; title?: string };
|
|
8
|
+
type WorkContextHandler = {
|
|
9
|
+
registerStrategy: (
|
|
10
|
+
type: string,
|
|
11
|
+
strategy: { resolve: (ctx: Context, item: GitContextItem) => Promise<string> },
|
|
12
|
+
) => void;
|
|
13
|
+
};
|
|
14
|
+
type AIPlugin = {
|
|
15
|
+
workContextHandler?: WorkContextHandler;
|
|
16
|
+
aiConversationsManager?: {
|
|
17
|
+
getConversation: (options: { sessionId: string; userId: number | string }) => Promise<unknown>;
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
type App = { pm: { get: (name: string) => unknown } };
|
|
21
|
+
|
|
22
|
+
const TYPES: GitContextType[] = ['git-repository', 'git-merge-request', 'git-commit'];
|
|
23
|
+
const registered = new WeakMap<WorkContextHandler, Set<GitContextType>>();
|
|
24
|
+
const admitted = new WeakMap<object, Map<string, Record<string, unknown>>>();
|
|
25
|
+
|
|
26
|
+
function gitContext(value: unknown): GitContextItem | null {
|
|
27
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
28
|
+
const item = value as Record<string, unknown>;
|
|
29
|
+
if (typeof item.type !== 'string' || !TYPES.includes(item.type as GitContextType)) return null;
|
|
30
|
+
return {
|
|
31
|
+
type: item.type as GitContextType,
|
|
32
|
+
uid: typeof item.uid === 'string' ? item.uid : '',
|
|
33
|
+
...(typeof item.title === 'string' ? { title: item.title } : {}),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function contextParams(ctx: Context, item: GitContextItem): Record<string, unknown> {
|
|
38
|
+
const kind = item.type.slice(4);
|
|
39
|
+
if (!item.uid || !item.uid.trim()) return ctx.throw(400, 'Invalid Git context');
|
|
40
|
+
if (kind === 'repository') return { kind, repositoryId: item.uid };
|
|
41
|
+
const separator = item.uid.indexOf(':');
|
|
42
|
+
if (separator <= 0 || separator === item.uid.length - 1) return ctx.throw(400, 'Invalid Git context');
|
|
43
|
+
const repositoryId = item.uid.slice(0, separator);
|
|
44
|
+
const target = item.uid.slice(separator + 1);
|
|
45
|
+
return kind === 'merge-request' ? { kind, repositoryId, mrIid: target } : { kind, repositoryId, commitHash: target };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function contextKey(item: GitContextItem): string {
|
|
49
|
+
return JSON.stringify([item.type, item.uid]);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function resolvedItem(item: GitContextItem, content: Record<string, unknown>) {
|
|
53
|
+
const name = typeof content.repositoryName === 'string' ? content.repositoryName : String(content.repositoryId || '');
|
|
54
|
+
let title: string;
|
|
55
|
+
if (item.type === 'git-repository') {
|
|
56
|
+
title = typeof content.name === 'string' ? content.name : String(content.repositoryId || '');
|
|
57
|
+
} else if (item.type === 'git-merge-request') {
|
|
58
|
+
title = [name, `!${content.mrIid}`, content.title].filter(Boolean).join(' · ');
|
|
59
|
+
} else {
|
|
60
|
+
title = [name, String(content.commitSha || '').slice(0, 7), content.subject].filter(Boolean).join(' · ');
|
|
61
|
+
}
|
|
62
|
+
return { type: item.type, uid: item.uid, title, content };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function aiPluginFor(app: App): AIPlugin | undefined {
|
|
66
|
+
try {
|
|
67
|
+
return (app.pm.get('ai') || app.pm.get('@nocobase/plugin-ai')) as AIPlugin | undefined;
|
|
68
|
+
} catch {
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function registerGitChatContextStrategies(app: App): boolean {
|
|
74
|
+
const handler = aiPluginFor(app)?.workContextHandler;
|
|
75
|
+
if (!handler || typeof handler.registerStrategy !== 'function') return false;
|
|
76
|
+
const names = registered.get(handler) || new Set<GitContextType>();
|
|
77
|
+
registered.set(handler, names);
|
|
78
|
+
for (const type of TYPES) {
|
|
79
|
+
if (names.has(type)) continue;
|
|
80
|
+
handler.registerStrategy(type, {
|
|
81
|
+
resolve: async (ctx, source) => {
|
|
82
|
+
const item = gitContext(source);
|
|
83
|
+
if (!item) return '';
|
|
84
|
+
try {
|
|
85
|
+
const content =
|
|
86
|
+
admitted.get(ctx)?.get(contextKey(item)) || (await loadChatContext(ctx, contextParams(ctx, item)));
|
|
87
|
+
return JSON.stringify(resolvedItem(item, content));
|
|
88
|
+
} catch {
|
|
89
|
+
return JSON.stringify({ type, content: { unavailable: true } });
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
names.add(type);
|
|
94
|
+
}
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function admitContextItems(ctx: Context, values: unknown): Promise<void> {
|
|
99
|
+
if (!Array.isArray(values)) return;
|
|
100
|
+
for (let index = 0; index < values.length; index += 1) {
|
|
101
|
+
const item = gitContext(values[index]);
|
|
102
|
+
if (!item) continue;
|
|
103
|
+
try {
|
|
104
|
+
if (!registerGitChatContextStrategies(ctx.app)) throw new Error('Git context strategy is unavailable');
|
|
105
|
+
const content = await loadChatContext(ctx, contextParams(ctx, item));
|
|
106
|
+
let cache = admitted.get(ctx);
|
|
107
|
+
if (!cache) {
|
|
108
|
+
cache = new Map();
|
|
109
|
+
admitted.set(ctx, cache);
|
|
110
|
+
}
|
|
111
|
+
cache.set(contextKey(item), content);
|
|
112
|
+
values[index] = resolvedItem(item, content);
|
|
113
|
+
} catch {
|
|
114
|
+
ctx.throw(
|
|
115
|
+
403,
|
|
116
|
+
ctx.t('Git context is unavailable. Check your access and select it again.', { ns: 'plugin-git-manager' }),
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function recordValue(record: unknown, key: string): unknown {
|
|
123
|
+
if (!record || typeof record !== 'object') return undefined;
|
|
124
|
+
const object = record as { get?: (field: string) => unknown } & Record<string, unknown>;
|
|
125
|
+
return typeof object.get === 'function' ? object.get(key) : object[key];
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function admitResentMessage(ctx: Context, values: Record<string, unknown>) {
|
|
129
|
+
const sessionId = typeof values.sessionId === 'string' ? values.sessionId : '';
|
|
130
|
+
const hasMessageId = Object.prototype.hasOwnProperty.call(values, 'messageId');
|
|
131
|
+
let messageId: string | number | undefined;
|
|
132
|
+
if (hasMessageId) {
|
|
133
|
+
const supplied = values.messageId;
|
|
134
|
+
if (typeof supplied === 'number' && Number.isSafeInteger(supplied) && supplied > 0) {
|
|
135
|
+
messageId = supplied;
|
|
136
|
+
} else if (typeof supplied === 'string' && /^\d+$/.test(supplied) && /[1-9]/.test(supplied)) {
|
|
137
|
+
messageId = supplied;
|
|
138
|
+
} else {
|
|
139
|
+
return ctx.throw(400, 'Invalid messageId');
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const userId = ctx.auth?.user?.id;
|
|
143
|
+
const plugin = aiPluginFor(ctx.app);
|
|
144
|
+
if (!sessionId || !userId || !plugin?.aiConversationsManager) return;
|
|
145
|
+
const conversation = await plugin.aiConversationsManager.getConversation({ sessionId, userId });
|
|
146
|
+
if (!conversation) return;
|
|
147
|
+
const repository = ctx.db.getRepository('aiConversations.messages', sessionId);
|
|
148
|
+
const target = hasMessageId
|
|
149
|
+
? await repository.findOne({ filter: { messageId } })
|
|
150
|
+
: await repository.findOne({ filter: { sessionId }, sort: ['-messageId'] });
|
|
151
|
+
if (!target) return;
|
|
152
|
+
const targetId = recordValue(target, 'messageId');
|
|
153
|
+
if ((typeof targetId !== 'string' && typeof targetId !== 'number') || !targetId) {
|
|
154
|
+
return ctx.throw(400, 'Invalid messageId');
|
|
155
|
+
}
|
|
156
|
+
const message =
|
|
157
|
+
recordValue(target, 'role') === 'user'
|
|
158
|
+
? target
|
|
159
|
+
: await repository.findOne({
|
|
160
|
+
filter: { sessionId, role: 'user', messageId: { $lt: targetId } },
|
|
161
|
+
sort: ['-messageId'],
|
|
162
|
+
});
|
|
163
|
+
await admitContextItems(ctx, recordValue(message, 'workContext'));
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export async function enforceGitChatAdmission(ctx: Context, next: () => Promise<void>) {
|
|
167
|
+
if (ctx.action?.resourceName !== 'aiConversations') return next();
|
|
168
|
+
const action = ctx.action.actionName;
|
|
169
|
+
if (action !== 'sendMessages' && action !== 'resendMessages') return next();
|
|
170
|
+
const values = ctx.action.params?.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
|
+
}
|