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.
- package/dist/client/{156.c27c2392746e7866.js → 156.8e36af3e2cee173e.js} +1 -1
- package/dist/client/{317.17ed0018e3e7db00.js → 317.2d0d33871e24ee24.js} +1 -1
- package/dist/client/{434.b2eeaaef33aae6e0.js → 434.2401f7257495b66e.js} +1 -1
- package/dist/client/{453.fc3042c9740d8fab.js → 453.58657b9ba0904477.js} +1 -1
- package/dist/client/index.js +1 -1
- package/dist/client-v2/{434.19c7579c06b9077c.js → 434.32b0a07b821b9329.js} +1 -1
- package/dist/client-v2/{453.5e507c94c59277b1.js → 453.f9a0ec6d8e1bd1cc.js} +1 -1
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +10 -9
- package/dist/locale/en-US.json +27 -1
- package/dist/locale/vi-VN.json +27 -1
- package/dist/locale/zh-CN.json +30 -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 +99 -4
- package/dist/server/actions/gitlab-api.js +86 -7
- package/dist/server/chat-context-admission.js +187 -0
- package/dist/server/plugin.js +8 -0
- package/dist/server/request-method-policy.js +2 -0
- package/package.json +2 -2
- package/src/client/__tests__/GitContextPicker.test.tsx +120 -0
- package/src/client/__tests__/ai-context.test.tsx +119 -0
- package/src/client/ai-context.tsx +3 -113
- package/src/client/context/GitManagerContext.tsx +18 -2
- package/src/client/index.tsx +3 -5
- 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 +27 -1
- package/src/locale/vi-VN.json +27 -1
- package/src/locale/zh-CN.json +30 -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-chat-context.test.ts +138 -0
- package/src/server/__tests__/git-security.test.ts +52 -0
- package/src/server/__tests__/smoke.test.ts +200 -0
- package/src/server/actions/chat-context.ts +302 -0
- package/src/server/actions/git-actions.ts +119 -6
- package/src/server/actions/gitlab-api.ts +97 -4
- package/src/server/chat-context-admission.ts +182 -0
- package/src/server/plugin.ts +11 -0
- package/src/server/request-method-policy.ts +2 -0
|
@@ -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
|
+
});
|
package/dist/server/plugin.js
CHANGED
|
@@ -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) => {
|
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.
|
|
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": "
|
|
56
|
+
"gitHead": "36c3d44696c81e16199e8dd5e1b13314a4c62a96",
|
|
57
57
|
"publishConfig": {
|
|
58
58
|
"access": "public",
|
|
59
59
|
"registry": "https://registry.npmjs.org/"
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import React from 'react';
|
|
4
|
+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
|
5
|
+
import type { GitContextApp } from '../../client-v2/git-context-api';
|
|
6
|
+
import { GitContextPicker } from '../../client-v2/components/GitContextPicker';
|
|
7
|
+
import { setCurrentGitRepository } from '../../client-v2/git-context-api';
|
|
8
|
+
|
|
9
|
+
const mocks = vi.hoisted(() => ({ t: (key: string) => key }));
|
|
10
|
+
|
|
11
|
+
vi.mock('react-i18next', () => ({
|
|
12
|
+
useTranslation: () => ({ t: mocks.t }),
|
|
13
|
+
}));
|
|
14
|
+
|
|
15
|
+
const actionResponse = (data: unknown, extra: Record<string, unknown> = {}) => ({
|
|
16
|
+
data: { data: { success: true, data, ...extra } },
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
describe('GitContextPicker', () => {
|
|
20
|
+
afterEach(() => {
|
|
21
|
+
cleanup();
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
it('preselects an authorized repository and rechecks a selected commit before attaching only its uid and title', async () => {
|
|
25
|
+
const commitHash = 'a'.repeat(40);
|
|
26
|
+
const repository = { id: 7, name: 'backend', defaultBranch: 'main', status: 'connected' };
|
|
27
|
+
const request = vi.fn(async ({ url, params }: { url: string; params?: Record<string, unknown> }) => {
|
|
28
|
+
if (url === 'gitManager:chatContextOptions') {
|
|
29
|
+
return actionResponse({ items: [repository], hasMore: false });
|
|
30
|
+
}
|
|
31
|
+
if (url === 'gitManager:branches') {
|
|
32
|
+
return actionResponse({ all: ['main', 'release'], current: 'release', detached: false });
|
|
33
|
+
}
|
|
34
|
+
if (url === 'gitManager:log') {
|
|
35
|
+
return actionResponse({
|
|
36
|
+
all: [{ hash: commitHash, subject: 'Fix access checks', author_name: 'Maya', date: '2026-10-20T10:00:00Z' }],
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
if (url === 'gitManager:chatContextContent') {
|
|
40
|
+
return actionResponse({ type: 'git-commit', repositoryId: 7, commitSha: commitHash, diff: '+secure' });
|
|
41
|
+
}
|
|
42
|
+
throw new Error(`Unexpected API request ${url} ${JSON.stringify(params)}`);
|
|
43
|
+
});
|
|
44
|
+
const app = { apiClient: { request }, eventBus: new EventTarget() } as GitContextApp;
|
|
45
|
+
const onAdd = vi.fn();
|
|
46
|
+
const onClose = vi.fn();
|
|
47
|
+
setCurrentGitRepository(app, repository.id);
|
|
48
|
+
|
|
49
|
+
render(<GitContextPicker app={app} kind="commit" onAdd={onAdd} onClose={onClose} />);
|
|
50
|
+
|
|
51
|
+
await waitFor(() =>
|
|
52
|
+
expect(request).toHaveBeenCalledWith(
|
|
53
|
+
expect.objectContaining({
|
|
54
|
+
url: 'gitManager:chatContextOptions',
|
|
55
|
+
params: { kind: 'commit', repositoryId: 7, page: 1, pageSize: 1 },
|
|
56
|
+
}),
|
|
57
|
+
),
|
|
58
|
+
);
|
|
59
|
+
await waitFor(() =>
|
|
60
|
+
expect(request).toHaveBeenCalledWith(
|
|
61
|
+
expect.objectContaining({
|
|
62
|
+
url: 'gitManager:log',
|
|
63
|
+
params: { repositoryId: 7, branch: 'release', skip: 0, maxCount: 30 },
|
|
64
|
+
}),
|
|
65
|
+
),
|
|
66
|
+
);
|
|
67
|
+
|
|
68
|
+
fireEvent.mouseDown(await screen.findByRole('combobox', { name: 'Commit' }));
|
|
69
|
+
fireEvent.click(await screen.findByText(/aaaaaaa · Fix access checks · Maya/));
|
|
70
|
+
fireEvent.click(screen.getByRole('button', { name: 'Attach to chat' }));
|
|
71
|
+
|
|
72
|
+
await waitFor(() =>
|
|
73
|
+
expect(onAdd).toHaveBeenCalledWith({
|
|
74
|
+
uid: `7:${commitHash}`,
|
|
75
|
+
title: 'backend · aaaaaaa · Fix access checks',
|
|
76
|
+
}),
|
|
77
|
+
);
|
|
78
|
+
expect(request).toHaveBeenCalledWith(
|
|
79
|
+
expect.objectContaining({
|
|
80
|
+
url: 'gitManager:chatContextContent',
|
|
81
|
+
params: { kind: 'commit', repositoryId: '7', commitHash },
|
|
82
|
+
}),
|
|
83
|
+
);
|
|
84
|
+
const contentRequestIndex = request.mock.calls.findIndex(
|
|
85
|
+
([config]) => config.url === 'gitManager:chatContextContent',
|
|
86
|
+
);
|
|
87
|
+
expect(request.mock.invocationCallOrder[contentRequestIndex]).toBeLessThan(onAdd.mock.invocationCallOrder[0]);
|
|
88
|
+
expect(onClose).toHaveBeenCalledTimes(1);
|
|
89
|
+
expect(JSON.stringify(onAdd.mock.calls[0][0])).not.toContain('diff');
|
|
90
|
+
setCurrentGitRepository(app);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('keeps an empty GitHub merged page loadable when the server reports a next page', async () => {
|
|
94
|
+
const repository = { id: 9, name: 'frontend', defaultBranch: 'main', status: 'connected' };
|
|
95
|
+
const request = vi.fn(async ({ url }: { url: string }) => {
|
|
96
|
+
if (url === 'gitManager:chatContextOptions') return actionResponse({ items: [repository], hasMore: false });
|
|
97
|
+
if (url === 'gitManager:mergeRequests') {
|
|
98
|
+
return actionResponse([], { pagination: { totalPages: null, hasMore: true } });
|
|
99
|
+
}
|
|
100
|
+
throw new Error(`Unexpected API request ${url}`);
|
|
101
|
+
});
|
|
102
|
+
const app = { apiClient: { request }, eventBus: new EventTarget() } as GitContextApp;
|
|
103
|
+
setCurrentGitRepository(app, repository.id);
|
|
104
|
+
|
|
105
|
+
render(<GitContextPicker app={app} kind="merge-request" onAdd={vi.fn()} onClose={vi.fn()} />);
|
|
106
|
+
|
|
107
|
+
const loadMore = await screen.findByRole('button', { name: 'Load more results' });
|
|
108
|
+
fireEvent.click(loadMore);
|
|
109
|
+
|
|
110
|
+
await waitFor(() => {
|
|
111
|
+
expect(request).toHaveBeenCalledWith(
|
|
112
|
+
expect.objectContaining({
|
|
113
|
+
url: 'gitManager:mergeRequests',
|
|
114
|
+
params: { repositoryId: 9, state: 'opened', page: 2, perPage: 30 },
|
|
115
|
+
}),
|
|
116
|
+
);
|
|
117
|
+
});
|
|
118
|
+
setCurrentGitRepository(app);
|
|
119
|
+
});
|
|
120
|
+
});
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import { Registry } from '@nocobase/utils/client';
|
|
4
|
+
import { waitFor } from '@testing-library/react';
|
|
5
|
+
import type { AIManager } from '@nocobase/plugin-ai/client-v2';
|
|
6
|
+
import { actionData, fetchGitContext, type GitContextApp } from '../../client-v2/git-context-api';
|
|
7
|
+
import { registerGitWorkContexts } from '../../client-v2/ai-context';
|
|
8
|
+
|
|
9
|
+
type WorkContextRecord = {
|
|
10
|
+
name?: string;
|
|
11
|
+
menu?: { onClick?: unknown };
|
|
12
|
+
getContent?: (app: unknown, item: { uid: string }) => Promise<unknown>;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
function createManager() {
|
|
16
|
+
const manager = {
|
|
17
|
+
workContext: new Registry<WorkContextRecord>(),
|
|
18
|
+
getWorkContext(name: string) {
|
|
19
|
+
return this.workContext.get(name);
|
|
20
|
+
},
|
|
21
|
+
registerWorkContext(name: string, options: WorkContextRecord) {
|
|
22
|
+
this.workContext.register(name, { ...options, name });
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
return manager as unknown as AIManager & { workContext: Registry<WorkContextRecord> };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function actionResponse(data: unknown) {
|
|
29
|
+
return { data: { data: { success: true, data } } };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
describe('Git chat work contexts', () => {
|
|
33
|
+
it('keeps menus hidden until capabilities load and updates them after authentication and role changes', async () => {
|
|
34
|
+
const eventBus = new EventTarget();
|
|
35
|
+
const responseHandlers: Array<(response: { config?: { url?: string } }) => unknown> = [];
|
|
36
|
+
const pendingRequest = vi.fn();
|
|
37
|
+
const app = {
|
|
38
|
+
eventBus,
|
|
39
|
+
apiClient: {
|
|
40
|
+
auth: { token: 'test-token' },
|
|
41
|
+
axios: {
|
|
42
|
+
interceptors: {
|
|
43
|
+
response: {
|
|
44
|
+
use: (handler: (response: { config?: { url?: string } }) => unknown) => {
|
|
45
|
+
responseHandlers.push(handler);
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
request: pendingRequest,
|
|
51
|
+
},
|
|
52
|
+
} as unknown as GitContextApp;
|
|
53
|
+
const manager = createManager();
|
|
54
|
+
let resolveInitial: ((value: unknown) => void) | undefined;
|
|
55
|
+
pendingRequest.mockImplementationOnce(
|
|
56
|
+
() =>
|
|
57
|
+
new Promise((resolve) => {
|
|
58
|
+
resolveInitial = resolve;
|
|
59
|
+
}),
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
const registration = registerGitWorkContexts(app, manager);
|
|
63
|
+
expect([...manager.workContext.getValues()].every((context) => !context.menu)).toBe(true);
|
|
64
|
+
expect(registerGitWorkContexts(app, manager)).toBe(registration);
|
|
65
|
+
expect(pendingRequest).toHaveBeenCalledWith({
|
|
66
|
+
url: 'gitManager:chatContextOptions',
|
|
67
|
+
skipNotify: true,
|
|
68
|
+
timeout: 5000,
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
resolveInitial?.(actionResponse({ capabilities: { repository: true, 'merge-request': false, commit: false } }));
|
|
72
|
+
await registration;
|
|
73
|
+
expect(manager.workContext.get('git-repository')?.menu).toBeDefined();
|
|
74
|
+
expect(manager.workContext.get('git-merge-request')?.menu).toBeUndefined();
|
|
75
|
+
expect(manager.workContext.get('git-commit')?.menu).toBeUndefined();
|
|
76
|
+
|
|
77
|
+
pendingRequest.mockResolvedValueOnce(
|
|
78
|
+
actionResponse({ capabilities: { repository: false, 'merge-request': false, commit: true } }),
|
|
79
|
+
);
|
|
80
|
+
const roleCheck = responseHandlers[0]({ config: { url: '/api/roles:check' } });
|
|
81
|
+
expect(roleCheck).toEqual({ config: { url: '/api/roles:check' } });
|
|
82
|
+
await waitFor(() => {
|
|
83
|
+
expect(manager.workContext.get('git-repository')?.menu).toBeUndefined();
|
|
84
|
+
expect(manager.workContext.get('git-commit')?.menu).toBeDefined();
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
if (!app.apiClient.auth) throw new Error('Expected the authenticated API client');
|
|
88
|
+
app.apiClient.auth.token = null;
|
|
89
|
+
eventBus.dispatchEvent(new Event('auth:tokenChanged'));
|
|
90
|
+
expect(manager.workContext.get('git-commit')?.menu).toBeUndefined();
|
|
91
|
+
expect(pendingRequest).toHaveBeenCalledTimes(2);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it('unwraps an action response and refetches attached context by its stable uid', async () => {
|
|
95
|
+
const contextData = { type: 'git-commit', repositoryId: 7, commitSha: 'a'.repeat(40), diff: '+value' };
|
|
96
|
+
const request = vi
|
|
97
|
+
.fn()
|
|
98
|
+
.mockResolvedValueOnce(
|
|
99
|
+
actionResponse({ capabilities: { repository: false, 'merge-request': false, commit: true } }),
|
|
100
|
+
)
|
|
101
|
+
.mockResolvedValue(actionResponse(contextData));
|
|
102
|
+
const app = { apiClient: { request }, eventBus: new EventTarget() } as GitContextApp;
|
|
103
|
+
const manager = createManager();
|
|
104
|
+
await registerGitWorkContexts(app, manager);
|
|
105
|
+
|
|
106
|
+
expect(actionData(actionResponse(contextData))).toEqual(contextData);
|
|
107
|
+
const reader = manager.workContext.get('git-commit')?.getContent;
|
|
108
|
+
await expect(
|
|
109
|
+
reader?.(app, { uid: `7:${'a'.repeat(40)}`, content: { type: 'git-commit', diff: 'stale content' } }),
|
|
110
|
+
).resolves.toEqual(contextData);
|
|
111
|
+
await expect(fetchGitContext(app, 'commit', `7:${'a'.repeat(40)}`)).resolves.toEqual(contextData);
|
|
112
|
+
expect(request).toHaveBeenCalledWith({
|
|
113
|
+
url: 'gitManager:chatContextContent',
|
|
114
|
+
params: { kind: 'commit', repositoryId: '7', commitHash: 'a'.repeat(40) },
|
|
115
|
+
skipNotify: true,
|
|
116
|
+
});
|
|
117
|
+
expect(request).toHaveBeenCalledTimes(3);
|
|
118
|
+
});
|
|
119
|
+
});
|
|
@@ -1,114 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
import { Space } from 'antd';
|
|
3
|
-
import { BranchesOutlined, MergeOutlined, NodeIndexOutlined } from '@ant-design/icons';
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
4
2
|
|
|
5
|
-
|
|
6
|
-
*
|
|
7
|
-
* regardless of whether plugin-ai is installed at compile time. The plugin
|
|
8
|
-
* checks `app.aiManager` at runtime before registering.
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
export const GitRepositoryWorkContext: any = {
|
|
12
|
-
name: 'git-repository',
|
|
13
|
-
menu: {
|
|
14
|
-
icon: <BranchesOutlined />,
|
|
15
|
-
Component: () => <span>Git Repository</span>,
|
|
16
|
-
},
|
|
17
|
-
tag: {
|
|
18
|
-
Component: ({ item }: any) => (
|
|
19
|
-
<Space size={4}>
|
|
20
|
-
<BranchesOutlined />
|
|
21
|
-
<span>{item?.title || `Repo #${item?.uid}`}</span>
|
|
22
|
-
</Space>
|
|
23
|
-
),
|
|
24
|
-
},
|
|
25
|
-
getContent: async (app: any, { uid }: any) => {
|
|
26
|
-
const response = await app.apiClient.request({
|
|
27
|
-
url: 'gitRepositories:get',
|
|
28
|
-
params: { filterByTk: uid },
|
|
29
|
-
});
|
|
30
|
-
const repo = response?.data?.data;
|
|
31
|
-
if (!repo) return null;
|
|
32
|
-
return {
|
|
33
|
-
type: 'git-repository',
|
|
34
|
-
repositoryId: repo.id,
|
|
35
|
-
name: repo.name,
|
|
36
|
-
repoUrl: repo.repoUrl,
|
|
37
|
-
defaultBranch: repo.defaultBranch,
|
|
38
|
-
status: repo.status,
|
|
39
|
-
};
|
|
40
|
-
},
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
export const GitMergeRequestWorkContext: any = {
|
|
44
|
-
name: 'git-merge-request',
|
|
45
|
-
menu: {
|
|
46
|
-
icon: <MergeOutlined />,
|
|
47
|
-
Component: () => <span>Git Merge Request</span>,
|
|
48
|
-
},
|
|
49
|
-
tag: {
|
|
50
|
-
Component: ({ item }: any) => (
|
|
51
|
-
<Space size={4}>
|
|
52
|
-
<MergeOutlined />
|
|
53
|
-
<span>{item?.title || `MR ${item?.uid}`}</span>
|
|
54
|
-
</Space>
|
|
55
|
-
),
|
|
56
|
-
},
|
|
57
|
-
getContent: async (app: any, { uid }: any) => {
|
|
58
|
-
// uid format: "<repositoryId>:<mrIid>"
|
|
59
|
-
const [repoIdStr, mrIidStr] = String(uid || '').split(':');
|
|
60
|
-
const repositoryId = Number(repoIdStr);
|
|
61
|
-
const mrIid = Number(mrIidStr);
|
|
62
|
-
if (!repositoryId || !mrIid) return null;
|
|
63
|
-
const response = await app.apiClient.request({
|
|
64
|
-
url: 'gitManager:mergeRequestDetail',
|
|
65
|
-
params: { repositoryId, mrIid },
|
|
66
|
-
});
|
|
67
|
-
const data = response?.data?.data;
|
|
68
|
-
return {
|
|
69
|
-
type: 'git-merge-request',
|
|
70
|
-
repositoryId,
|
|
71
|
-
mrIid,
|
|
72
|
-
title: data?.title,
|
|
73
|
-
sourceBranch: data?.sourceBranch,
|
|
74
|
-
targetBranch: data?.targetBranch,
|
|
75
|
-
author: data?.author,
|
|
76
|
-
changes: data?.changes,
|
|
77
|
-
description: data?.description,
|
|
78
|
-
webUrl: data?.webUrl,
|
|
79
|
-
};
|
|
80
|
-
},
|
|
81
|
-
};
|
|
82
|
-
|
|
83
|
-
export const GitCommitWorkContext: any = {
|
|
84
|
-
name: 'git-commit',
|
|
85
|
-
menu: {
|
|
86
|
-
icon: <NodeIndexOutlined />,
|
|
87
|
-
Component: () => <span>Git Commit</span>,
|
|
88
|
-
},
|
|
89
|
-
tag: {
|
|
90
|
-
Component: ({ item }: any) => (
|
|
91
|
-
<Space size={4}>
|
|
92
|
-
<NodeIndexOutlined />
|
|
93
|
-
<span>{item?.title || `Commit ${item?.uid}`}</span>
|
|
94
|
-
</Space>
|
|
95
|
-
),
|
|
96
|
-
},
|
|
97
|
-
getContent: async (app: any, { uid }: any) => {
|
|
98
|
-
// uid format: "<repositoryId>:<commitSha>"
|
|
99
|
-
const [repoIdStr, commitSha] = String(uid || '').split(':');
|
|
100
|
-
const repositoryId = Number(repoIdStr);
|
|
101
|
-
if (!repositoryId || !commitSha) return null;
|
|
102
|
-
const response = await app.apiClient.request({
|
|
103
|
-
url: 'gitManager:commitDetail',
|
|
104
|
-
params: { repositoryId, commitHash: commitSha },
|
|
105
|
-
});
|
|
106
|
-
const data = response?.data?.data;
|
|
107
|
-
return {
|
|
108
|
-
type: 'git-commit',
|
|
109
|
-
repositoryId,
|
|
110
|
-
commitSha,
|
|
111
|
-
...data,
|
|
112
|
-
};
|
|
113
|
-
},
|
|
114
|
-
};
|
|
3
|
+
// The legacy client can use the v2 AI chat and its work-context contract.
|
|
4
|
+
export * from '../client-v2/ai-context';
|
|
@@ -1,5 +1,15 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* This file is part of the NocoBase (R) project.
|
|
3
|
+
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
|
|
4
|
+
* Authors: NocoBase Team.
|
|
5
|
+
*
|
|
6
|
+
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
|
|
7
|
+
* For more information, please refer to: https://www.nocobase.com/agreement.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import React, { createContext, useContext, useState, useCallback, useRef, useEffect } from 'react';
|
|
2
11
|
import { useApp } from '@nocobase/client-v2';
|
|
12
|
+
import { setCurrentGitRepository } from '../../client-v2/git-context-api';
|
|
3
13
|
|
|
4
14
|
interface Repository {
|
|
5
15
|
id: number;
|
|
@@ -34,7 +44,8 @@ export function useGitManager() {
|
|
|
34
44
|
}
|
|
35
45
|
|
|
36
46
|
export const GitManagerProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
|
37
|
-
const
|
|
47
|
+
const app = useApp();
|
|
48
|
+
const api = app.apiClient;
|
|
38
49
|
const [repos, setRepos] = useState<Repository[]>([]);
|
|
39
50
|
const [selectedRepo, setSelectedRepo] = useState<Repository | null>(null);
|
|
40
51
|
const [loading, setLoading] = useState(false);
|
|
@@ -43,6 +54,11 @@ export const GitManagerProvider: React.FC<{ children: React.ReactNode }> = ({ ch
|
|
|
43
54
|
const selectedRepoRef = useRef(selectedRepo);
|
|
44
55
|
selectedRepoRef.current = selectedRepo;
|
|
45
56
|
|
|
57
|
+
useEffect(() => {
|
|
58
|
+
setCurrentGitRepository(app, selectedRepo?.id);
|
|
59
|
+
return () => setCurrentGitRepository(app);
|
|
60
|
+
}, [app, selectedRepo?.id]);
|
|
61
|
+
|
|
46
62
|
const refreshBranches = useCallback(async () => {
|
|
47
63
|
const repo = selectedRepoRef.current;
|
|
48
64
|
if (!repo || repo.status !== 'connected') {
|