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,59 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ export type GitContextKind = 'repository' | 'merge-request' | 'commit';
4
+ export type GitContextApp = {
5
+ apiClient: {
6
+ request: (config: {
7
+ url: string;
8
+ params?: Record<string, unknown>;
9
+ skipNotify?: boolean;
10
+ timeout?: number;
11
+ }) => Promise<unknown>;
12
+ auth?: { token?: string | null };
13
+ };
14
+ eventBus: EventTarget;
15
+ };
16
+
17
+ const currentRepositories = new WeakMap<object, number>();
18
+
19
+ export function setCurrentGitRepository(app: object, repositoryId?: number) {
20
+ if (repositoryId == null) currentRepositories.delete(app);
21
+ else currentRepositories.set(app, repositoryId);
22
+ }
23
+
24
+ export function getCurrentGitRepository(app: object): number | undefined {
25
+ return currentRepositories.get(app);
26
+ }
27
+
28
+ export function actionBody(response: unknown): unknown {
29
+ return (response as { data?: { data?: unknown } } | null)?.data?.data;
30
+ }
31
+
32
+ export function actionData(response: unknown): unknown {
33
+ const body = actionBody(response);
34
+ if (body && typeof body === 'object' && 'success' in body && 'data' in body) {
35
+ return (body as { data: unknown }).data;
36
+ }
37
+ return body;
38
+ }
39
+
40
+ function contextParams(kind: GitContextKind, uid: string): Record<string, unknown> {
41
+ if (kind === 'repository') return { kind, repositoryId: uid };
42
+ const separator = uid.indexOf(':');
43
+ const repositoryId = uid.slice(0, separator);
44
+ const target = uid.slice(separator + 1);
45
+ if (separator <= 0 || !target) throw new Error('Invalid Git context');
46
+ if (kind === 'merge-request') return { kind, repositoryId, mrIid: target };
47
+ return { kind, repositoryId, commitHash: target };
48
+ }
49
+
50
+ export async function fetchGitContext(app: GitContextApp, kind: GitContextKind, uid: string): Promise<unknown> {
51
+ const response = await app.apiClient.request({
52
+ url: 'gitManager:chatContextContent',
53
+ params: contextParams(kind, uid),
54
+ skipNotify: true,
55
+ });
56
+ const data = actionData(response);
57
+ if (!data || typeof data !== 'object') throw new Error('Git context is unavailable');
58
+ return data;
59
+ }
@@ -5,14 +5,12 @@ import type PluginAIClientV2 from '@nocobase/plugin-ai/client-v2';
5
5
  import type PluginAclClientV2 from '@nocobase/plugin-acl/client-v2';
6
6
  import type { PermissionTabProps } from '@nocobase/plugin-acl/client-v2';
7
7
  import React from 'react';
8
- import { GitRepositoryWorkContext, GitMergeRequestWorkContext, GitCommitWorkContext } from './ai-context';
8
+ import { registerGitWorkContexts } from './ai-context';
9
9
 
10
10
  export class PluginGitManagerClient extends Plugin<Record<string, never>, Application> {
11
11
  async load() {
12
12
  const aiManager = this.app.pm.get<PluginAIClientV2>('ai')?.aiManager;
13
- aiManager?.registerWorkContext('git-repository', GitRepositoryWorkContext);
14
- aiManager?.registerWorkContext('git-merge-request', GitMergeRequestWorkContext);
15
- aiManager?.registerWorkContext('git-commit', GitCommitWorkContext);
13
+ if (aiManager) await registerGitWorkContexts(this.app, aiManager);
16
14
  this.app.pm.get<PluginAclClientV2>('acl')?.settingsUI.addPermissionsTab({
17
15
  key: 'git-manager',
18
16
  label: this.t('Git Manager'),
@@ -392,5 +392,31 @@
392
392
  "Refresh publication status before recovery": "Refresh publication status before recovery",
393
393
  "Matching comment found; another publication attempt still owns the review": "Matching comment found; another publication attempt still owns the review",
394
394
  "Review publication claim changed": "Review publication claim changed; refresh and check the current attempt",
395
- "Review project reservation changed": "Review project reservation changed"
395
+ "Review project reservation changed": "Review project reservation changed",
396
+ "Git context is unavailable. Check your access and select it again.": "Git context is unavailable. Check your access and select it again.",
397
+ "Unable to load Git context. Check your access and try again.": "Unable to load Git context. Check your access and try again.",
398
+ "Search repositories": "Search repositories",
399
+ "No repositories available": "No repositories available",
400
+ "Load more repositories": "Load more repositories",
401
+ "Select a branch": "Select a branch",
402
+ "State": "State",
403
+ "opened": "Open",
404
+ "merged": "Merged",
405
+ "closed": "Closed",
406
+ "all": "All",
407
+ "Search loaded results": "Search loaded results",
408
+ "Select a commit": "Select a commit",
409
+ "Select a merge request": "Select a merge request",
410
+ "No results": "No results",
411
+ "Load more results": "Load more results",
412
+ "Cancel": "Cancel",
413
+ "Attach to chat": "Attach to chat",
414
+ "Loading": "Loading",
415
+ "Additional changed files were omitted.": "Additional changed files were omitted.",
416
+ "The diff was truncated to the configured limit.": "The diff was truncated to the configured limit.",
417
+ "Binary file contents are not included in the diff.": "Binary file contents are not included in the diff.",
418
+ "Additional changed files were omitted by the provider.": "Additional changed files were omitted by the provider.",
419
+ "The provider omitted patches for one or more files, including binary or large files.": "The provider omitted patches for one or more files, including binary or large files.",
420
+ "The provider omitted additional changed files or patches.": "The provider omitted additional changed files or patches.",
421
+ "Additional changed files or diff content were omitted.": "Additional changed files or diff content were omitted."
396
422
  }
@@ -380,5 +380,31 @@
380
380
  "Refresh publication status before recovery": "Hãy làm mới trạng thái đăng trước khi khôi phục",
381
381
  "Matching comment found; another publication attempt still owns the review": "Đã tìm thấy bình luận khớp; một lần đăng khác vẫn đang giữ lượt đánh giá",
382
382
  "Review publication claim changed": "Lượt đăng đang giữ đã thay đổi; hãy làm mới và kiểm tra lượt hiện tại",
383
- "Review project reservation changed": "Quyền giữ dự án cho lượt đánh giá đã thay đổi"
383
+ "Review project reservation changed": "Quyền giữ dự án cho lượt đánh giá đã thay đổi",
384
+ "Git context is unavailable. Check your access and select it again.": "Không thể đọc ngữ cảnh Git. Hãy kiểm tra quyền truy cập và chọn lại.",
385
+ "Unable to load Git context. Check your access and try again.": "Không thể tải dữ liệu Git. Hãy kiểm tra quyền truy cập và thử lại.",
386
+ "Search repositories": "Tìm repository",
387
+ "No repositories available": "Không có repository nào khả dụng",
388
+ "Load more repositories": "Tải thêm repository",
389
+ "Select a branch": "Chọn nhánh",
390
+ "State": "Trạng thái",
391
+ "opened": "Đang mở",
392
+ "merged": "Đã hợp nhất",
393
+ "closed": "Đã đóng",
394
+ "all": "Tất cả",
395
+ "Search loaded results": "Tìm trong các kết quả đã tải",
396
+ "Select a commit": "Chọn commit",
397
+ "Select a merge request": "Chọn merge request",
398
+ "No results": "Không có kết quả",
399
+ "Load more results": "Tải thêm kết quả",
400
+ "Cancel": "Hủy",
401
+ "Attach to chat": "Gắn vào chat",
402
+ "Loading": "Đang tải",
403
+ "Additional changed files were omitted.": "Một số tệp thay đổi khác đã được lược bỏ.",
404
+ "The diff was truncated to the configured limit.": "Nội dung diff đã được cắt theo giới hạn cấu hình.",
405
+ "Binary file contents are not included in the diff.": "Nội dung tệp nhị phân không có trong diff.",
406
+ "Additional changed files were omitted by the provider.": "Nhà cung cấp đã lược bỏ một số tệp thay đổi khác.",
407
+ "The provider omitted patches for one or more files, including binary or large files.": "Nhà cung cấp không trả patch cho một hoặc nhiều tệp, bao gồm tệp nhị phân hoặc tệp lớn.",
408
+ "The provider omitted additional changed files or patches.": "Nhà cung cấp đã lược bỏ một số tệp thay đổi hoặc patch khác.",
409
+ "Additional changed files or diff content were omitted.": "Một số tệp thay đổi hoặc nội dung diff khác đã được lược bỏ."
384
410
  }
@@ -146,5 +146,34 @@
146
146
  "Refresh publication status before recovery": "恢复前请刷新发布状态",
147
147
  "Matching comment found; another publication attempt still owns the review": "已找到匹配评论;另一个发布操作仍占用该审查",
148
148
  "Review publication claim changed": "审查发布占用已更改;请刷新并检查当前操作",
149
- "Review project reservation changed": "审查项目占用已更改"
149
+ "Review project reservation changed": "审查项目占用已更改",
150
+ "Git context is unavailable. Check your access and select it again.": "无法读取 Git 上下文。请检查访问权限并重新选择。",
151
+ "Unable to load Git context. Check your access and try again.": "无法加载 Git 数据。请检查访问权限后重试。",
152
+ "Search repositories": "搜索仓库",
153
+ "Select a repository": "选择仓库",
154
+ "Commit": "提交",
155
+ "Merge Request": "合并请求",
156
+ "No repositories available": "没有可用的仓库",
157
+ "Load more repositories": "加载更多仓库",
158
+ "Select a branch": "选择分支",
159
+ "State": "状态",
160
+ "opened": "开放",
161
+ "merged": "已合并",
162
+ "closed": "已关闭",
163
+ "all": "全部",
164
+ "Search loaded results": "搜索已加载的结果",
165
+ "Select a commit": "选择提交",
166
+ "Select a merge request": "选择合并请求",
167
+ "No results": "没有结果",
168
+ "Load more results": "加载更多结果",
169
+ "Cancel": "取消",
170
+ "Attach to chat": "附加到聊天",
171
+ "Loading": "正在加载",
172
+ "Additional changed files were omitted.": "已省略其他更改的文件。",
173
+ "The diff was truncated to the configured limit.": "差异内容已按配置的上限截断。",
174
+ "Binary file contents are not included in the diff.": "差异内容不包含二进制文件内容。",
175
+ "Additional changed files were omitted by the provider.": "提供商省略了其他更改的文件。",
176
+ "The provider omitted patches for one or more files, including binary or large files.": "提供商省略了一个或多个文件的补丁,包括二进制文件或大文件。",
177
+ "The provider omitted additional changed files or patches.": "提供商省略了其他更改的文件或补丁。",
178
+ "Additional changed files or diff content were omitted.": "已省略其他更改的文件或差异内容。"
150
179
  }
@@ -0,0 +1,276 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import type { Context } from '@nocobase/actions';
4
+ import { enforceGitChatAdmission, registerGitChatContextStrategies } from '../chat-context-admission';
5
+
6
+ const mocks = vi.hoisted(() => ({ loadChatContext: vi.fn() }));
7
+
8
+ vi.mock('../actions/chat-context', () => ({ loadChatContext: mocks.loadChatContext }));
9
+
10
+ type GitContext = { type: string; uid: string; title?: string; content?: unknown };
11
+
12
+ function createApp(aiPlugin?: unknown) {
13
+ return {
14
+ pm: {
15
+ get: vi.fn((name: string) => (name === 'ai' ? aiPlugin : undefined)),
16
+ },
17
+ };
18
+ }
19
+
20
+ function createContext(input: {
21
+ app: ReturnType<typeof createApp>;
22
+ actionName: string;
23
+ values: Record<string, unknown>;
24
+ messagesRepository?: { findOne: ReturnType<typeof vi.fn> };
25
+ userId?: number;
26
+ }) {
27
+ const next = vi.fn().mockResolvedValue(undefined);
28
+ const throwError = vi.fn((status: number, message: string): never => {
29
+ throw Object.assign(new Error(message), { status });
30
+ });
31
+ const getRepository = vi.fn(() => input.messagesRepository);
32
+ const context = {
33
+ action: { resourceName: 'aiConversations', actionName: input.actionName, params: { values: input.values } },
34
+ app: input.app,
35
+ auth: { user: { id: input.userId ?? 21 } },
36
+ db: { getRepository },
37
+ state: { currentRoles: ['developer'], currentUser: { id: input.userId ?? 21 } },
38
+ t: (value: string) => value,
39
+ throw: throwError,
40
+ };
41
+ return { context: context as unknown as Context, next, throwError, getRepository };
42
+ }
43
+
44
+ function contextItem(overrides: Partial<GitContext> = {}): GitContext {
45
+ return {
46
+ type: 'git-commit',
47
+ uid: `7:${'a'.repeat(40)}`,
48
+ title: 'Old Repository · aaaaaaa · stale title',
49
+ ...overrides,
50
+ };
51
+ }
52
+
53
+ describe('Git AI chat context admission', () => {
54
+ beforeEach(() => {
55
+ vi.clearAllMocks();
56
+ });
57
+
58
+ it('rehydrates client supplied content and title before a message is sent', async () => {
59
+ const freshContent = {
60
+ type: 'git-commit',
61
+ repositoryId: 7,
62
+ repositoryName: 'permitted-repository',
63
+ commitSha: 'a'.repeat(40),
64
+ subject: 'Fix permission check',
65
+ diff: '+fresh data',
66
+ };
67
+ mocks.loadChatContext.mockResolvedValue(freshContent);
68
+ const aiPlugin = { workContextHandler: { registerStrategy: vi.fn() } };
69
+ const app = createApp(aiPlugin);
70
+ const item = contextItem({ content: { diff: '+forged data' } });
71
+ const values = { messages: [{ role: 'user', workContext: [item] }] };
72
+ const { context, next } = createContext({ app, actionName: 'sendMessages', values });
73
+
74
+ await enforceGitChatAdmission(context, next);
75
+
76
+ expect(mocks.loadChatContext).toHaveBeenCalledWith(context, {
77
+ kind: 'commit',
78
+ repositoryId: '7',
79
+ commitHash: 'a'.repeat(40),
80
+ });
81
+ expect(values.messages[0].workContext[0]).toMatchObject({
82
+ type: 'git-commit',
83
+ uid: `7:${'a'.repeat(40)}`,
84
+ title: 'permitted-repository · aaaaaaa · Fix permission check',
85
+ content: freshContent,
86
+ });
87
+ expect(next).toHaveBeenCalledTimes(1);
88
+ });
89
+
90
+ it('blocks sending when access was revoked after a context tag had been selected', async () => {
91
+ mocks.loadChatContext.mockRejectedValue(Object.assign(new Error('Permission denied'), { status: 403 }));
92
+ const app = createApp({ workContextHandler: { registerStrategy: vi.fn() } });
93
+ const values = { messages: [{ role: 'user', workContext: [contextItem({ content: { diff: '+stale data' } })] }] };
94
+ const { context, next, throwError } = createContext({ app, actionName: 'sendMessages', values });
95
+
96
+ await expect(enforceGitChatAdmission(context, next)).rejects.toMatchObject({ status: 403 });
97
+
98
+ expect(throwError).toHaveBeenCalledWith(403, 'Git context is unavailable. Check your access and select it again.');
99
+ expect(next).not.toHaveBeenCalled();
100
+ });
101
+
102
+ it('checks resend session ownership before reading messages and rehydrates the latest user tag', async () => {
103
+ const workContext = [contextItem({ content: { diff: '+old content' } })];
104
+ const messageId = '9007199254740992';
105
+ const targetMessage = {
106
+ get: (field: string) => (field === 'messageId' ? messageId : field === 'role' ? 'assistant' : null),
107
+ };
108
+ const priorUserMessage = {
109
+ get: (field: string) =>
110
+ field === 'messageId'
111
+ ? '9007199254740991'
112
+ : field === 'role'
113
+ ? 'user'
114
+ : field === 'workContext'
115
+ ? workContext
116
+ : null,
117
+ };
118
+ const messagesRepository = {
119
+ findOne: vi.fn().mockResolvedValueOnce(targetMessage).mockResolvedValueOnce(priorUserMessage),
120
+ };
121
+ const aiPlugin = {
122
+ workContextHandler: { registerStrategy: vi.fn() },
123
+ aiConversationsManager: { getConversation: vi.fn().mockResolvedValue({ sessionId: 'session-1' }) },
124
+ };
125
+ const app = createApp(aiPlugin);
126
+ const values = { sessionId: 'session-1', messageId };
127
+ const { context, next, getRepository } = createContext({
128
+ app,
129
+ actionName: 'resendMessages',
130
+ values,
131
+ messagesRepository,
132
+ });
133
+ mocks.loadChatContext.mockResolvedValue({
134
+ type: 'git-commit',
135
+ repositoryId: 7,
136
+ repositoryName: 'permitted-repository',
137
+ commitSha: 'a'.repeat(40),
138
+ subject: 'Current commit title',
139
+ diff: '+current content',
140
+ });
141
+
142
+ await enforceGitChatAdmission(context, next);
143
+
144
+ const manager = aiPlugin.aiConversationsManager;
145
+ expect(manager.getConversation).toHaveBeenCalledWith({ sessionId: 'session-1', userId: 21 });
146
+ expect(getRepository).toHaveBeenCalledWith('aiConversations.messages', 'session-1');
147
+ expect(messagesRepository.findOne).toHaveBeenNthCalledWith(1, { filter: { messageId } });
148
+ expect(messagesRepository.findOne).toHaveBeenNthCalledWith(2, {
149
+ filter: { sessionId: 'session-1', role: 'user', messageId: { $lt: messageId } },
150
+ sort: ['-messageId'],
151
+ });
152
+ expect(workContext[0]).toMatchObject({
153
+ title: 'permitted-repository · aaaaaaa · Current commit title',
154
+ content: { diff: '+current content' },
155
+ });
156
+ expect(next).toHaveBeenCalledTimes(1);
157
+ });
158
+
159
+ it('accepts a positive safe numeric messageId on resend', async () => {
160
+ const targetMessage = {
161
+ get: (field: string) =>
162
+ field === 'messageId' ? 42 : field === 'role' ? 'user' : field === 'workContext' ? [] : null,
163
+ };
164
+ const messagesRepository = { findOne: vi.fn().mockResolvedValue(targetMessage) };
165
+ const aiPlugin = {
166
+ aiConversationsManager: { getConversation: vi.fn().mockResolvedValue({ sessionId: 'session-1' }) },
167
+ };
168
+ const { context, next } = createContext({
169
+ app: createApp(aiPlugin),
170
+ actionName: 'resendMessages',
171
+ values: { sessionId: 'session-1', messageId: 42 },
172
+ messagesRepository,
173
+ });
174
+
175
+ await enforceGitChatAdmission(context, next);
176
+
177
+ expect(messagesRepository.findOne).toHaveBeenCalledWith({ filter: { messageId: 42 } });
178
+ expect(next).toHaveBeenCalledTimes(1);
179
+ });
180
+
181
+ it('selects the latest session message only when messageId is absent', async () => {
182
+ const targetMessage = {
183
+ get: (field: string) =>
184
+ field === 'messageId' ? '99' : field === 'role' ? 'user' : field === 'workContext' ? [] : null,
185
+ };
186
+ const messagesRepository = { findOne: vi.fn().mockResolvedValue(targetMessage) };
187
+ const aiPlugin = {
188
+ aiConversationsManager: { getConversation: vi.fn().mockResolvedValue({ sessionId: 'session-1' }) },
189
+ };
190
+ const { context, next } = createContext({
191
+ app: createApp(aiPlugin),
192
+ actionName: 'resendMessages',
193
+ values: { sessionId: 'session-1' },
194
+ messagesRepository,
195
+ });
196
+
197
+ await enforceGitChatAdmission(context, next);
198
+
199
+ expect(messagesRepository.findOne).toHaveBeenCalledWith({
200
+ filter: { sessionId: 'session-1' },
201
+ sort: ['-messageId'],
202
+ });
203
+ expect(next).toHaveBeenCalledTimes(1);
204
+ });
205
+
206
+ it('rejects a malformed messageId before reading the session or messages', async () => {
207
+ const messagesRepository = { findOne: vi.fn() };
208
+ const aiPlugin = { aiConversationsManager: { getConversation: vi.fn() } };
209
+ const { context, next, getRepository, throwError } = createContext({
210
+ app: createApp(aiPlugin),
211
+ actionName: 'resendMessages',
212
+ values: { sessionId: 'session-1', messageId: '9007199254740993x' },
213
+ messagesRepository,
214
+ });
215
+
216
+ await expect(enforceGitChatAdmission(context, next)).rejects.toMatchObject({
217
+ status: 400,
218
+ message: 'Invalid messageId',
219
+ });
220
+
221
+ expect(throwError).toHaveBeenCalledWith(400, 'Invalid messageId');
222
+ expect(aiPlugin.aiConversationsManager.getConversation).not.toHaveBeenCalled();
223
+ expect(getRepository).not.toHaveBeenCalled();
224
+ expect(messagesRepository.findOne).not.toHaveBeenCalled();
225
+ expect(next).not.toHaveBeenCalled();
226
+ });
227
+
228
+ it('does not query message storage when the current user does not own the resend session', async () => {
229
+ const messagesRepository = { findOne: vi.fn() };
230
+ const aiPlugin = {
231
+ aiConversationsManager: { getConversation: vi.fn().mockResolvedValue(null) },
232
+ };
233
+ const { context, next, getRepository } = createContext({
234
+ app: createApp(aiPlugin),
235
+ actionName: 'resendMessages',
236
+ values: { sessionId: 'another-users-session', messageId: '2' },
237
+ messagesRepository,
238
+ });
239
+
240
+ await enforceGitChatAdmission(context, next);
241
+
242
+ expect(aiPlugin.aiConversationsManager.getConversation).toHaveBeenCalledWith({
243
+ sessionId: 'another-users-session',
244
+ userId: 21,
245
+ });
246
+ expect(getRepository).not.toHaveBeenCalled();
247
+ expect(messagesRepository.findOne).not.toHaveBeenCalled();
248
+ expect(next).toHaveBeenCalledTimes(1);
249
+ });
250
+
251
+ it('redacts unavailable historical Git context without blocking unrelated messages', async () => {
252
+ const strategies = new Map<string, { resolve: (ctx: Context, item: GitContext) => Promise<string> }>();
253
+ const aiPlugin = {
254
+ workContextHandler: {
255
+ registerStrategy: vi.fn(
256
+ (type: string, strategy: { resolve: (ctx: Context, item: GitContext) => Promise<string> }) => {
257
+ strategies.set(type, strategy);
258
+ },
259
+ ),
260
+ },
261
+ };
262
+ const app = createApp(aiPlugin);
263
+ expect(registerGitChatContextStrategies(app)).toBe(true);
264
+ mocks.loadChatContext.mockRejectedValue(new Error('Permission denied'));
265
+ const { context, next } = createContext({ app, actionName: 'sendMessages', values: { messages: [] } });
266
+
267
+ const strategy = strategies.get('git-commit');
268
+ if (!strategy) throw new Error('Git commit context strategy was not registered');
269
+ const response = await strategy.resolve(context, contextItem());
270
+
271
+ expect(JSON.parse(response)).toEqual({ type: 'git-commit', content: { unavailable: true } });
272
+ await enforceGitChatAdmission(context, next);
273
+ expect(next).toHaveBeenCalledTimes(1);
274
+ expect(registerGitChatContextStrategies(createApp())).toBe(false);
275
+ });
276
+ });
@@ -0,0 +1,144 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import type { Context } from '@nocobase/actions';
4
+ import { chatContextOptions } from '../actions/chat-context';
5
+
6
+ type Permission = {
7
+ params: {
8
+ filter?: unknown;
9
+ fields?: string[];
10
+ whitelist?: string[];
11
+ except?: string[];
12
+ blacklist?: string[];
13
+ };
14
+ } | null;
15
+
16
+ type RepositoryQuery = {
17
+ filter?: unknown;
18
+ fields?: string[];
19
+ sort?: string[];
20
+ limit?: number;
21
+ offset?: number;
22
+ };
23
+
24
+ function scoped(ids: number[], fields?: string[]): Permission {
25
+ return {
26
+ params: {
27
+ filter: { id: { $in: ids } },
28
+ ...(fields ? { fields } : {}),
29
+ },
30
+ };
31
+ }
32
+
33
+ function createContext(input: {
34
+ roles: string[];
35
+ permissions: Record<string, Permission>;
36
+ params: Record<string, unknown>;
37
+ repository?: Record<string, unknown>;
38
+ allowRoles?: string[];
39
+ }) {
40
+ const repository = input.repository || {
41
+ id: 1,
42
+ name: 'Restricted repository',
43
+ defaultBranch: 'main',
44
+ status: 'ready',
45
+ };
46
+ const repositoryAccess = {
47
+ findOne: vi.fn(async (_query: RepositoryQuery) => repository),
48
+ find: vi.fn(async (_query: RepositoryQuery) => [repository]),
49
+ };
50
+ const can = vi.fn(async ({ roles, resource, action }: { roles: string[]; resource: string; action: string }) => {
51
+ if (input.allowRoles && !input.allowRoles.every((role) => roles.includes(role))) return null;
52
+ return input.permissions[`${resource}:${action}`] ?? null;
53
+ });
54
+ const getRepository = vi.fn(() => repositoryAccess);
55
+ const context = {
56
+ state: { currentUser: { id: 21 }, currentRoles: input.roles },
57
+ action: { params: input.params },
58
+ request: { body: {} },
59
+ app: { acl: { can } },
60
+ db: { getRepository },
61
+ throw: vi.fn((status: number, message: string): never => {
62
+ throw Object.assign(new Error(message), { status });
63
+ }),
64
+ body: undefined as unknown,
65
+ };
66
+ return { context: context as unknown as Context, can, repositoryAccess };
67
+ }
68
+
69
+ describe('Git AI chat context options permissions', () => {
70
+ it('disables a kind when its per-action repository scopes have no common repository', async () => {
71
+ const permissions: Record<string, Permission> = {
72
+ 'gitRepositories:list': scoped([1, 2]),
73
+ 'gitRepositories:get': scoped([1, 2]),
74
+ 'gitManager:branches': scoped([1]),
75
+ 'gitManager:log': scoped([2]),
76
+ 'gitManager:commitDetail': scoped([1, 2]),
77
+ 'gitManager:diff': scoped([1, 2]),
78
+ };
79
+ const { context, repositoryAccess } = createContext({
80
+ roles: ['git-reader'],
81
+ permissions,
82
+ params: { kind: 'commit' },
83
+ });
84
+
85
+ await chatContextOptions(context, vi.fn().mockResolvedValue(undefined));
86
+
87
+ expect(context.body).toMatchObject({
88
+ success: true,
89
+ data: {
90
+ capabilities: { repository: true, 'merge-request': false, commit: false },
91
+ items: [],
92
+ },
93
+ });
94
+ expect(repositoryAccess.find).not.toHaveBeenCalled();
95
+ expect(repositoryAccess.findOne).toHaveBeenCalledTimes(1);
96
+ });
97
+
98
+ it('combines joined roles and omits hidden names from results and search', async () => {
99
+ const repositoryPermissions: Permission = scoped([1], ['id', 'defaultBranch', 'status']);
100
+ const permissions: Record<string, Permission> = {
101
+ 'gitRepositories:list': repositoryPermissions,
102
+ 'gitRepositories:get': repositoryPermissions,
103
+ 'gitManager:branches': scoped([1]),
104
+ 'gitManager:log': scoped([1]),
105
+ 'gitManager:commitDetail': scoped([1]),
106
+ 'gitManager:diff': scoped([1]),
107
+ };
108
+ const roles = ['repository-reader', 'commit-reader'];
109
+ const repository = { id: 1, name: 'Restricted repository', defaultBranch: 'main', status: 'ready' };
110
+ const { context, can, repositoryAccess } = createContext({
111
+ roles,
112
+ allowRoles: roles,
113
+ permissions,
114
+ params: { kind: 'repository' },
115
+ repository,
116
+ });
117
+
118
+ await chatContextOptions(context, vi.fn().mockResolvedValue(undefined));
119
+
120
+ expect(can).toHaveBeenCalled();
121
+ expect(can.mock.calls.every(([input]) => input.roles.join(',') === roles.join(','))).toBe(true);
122
+ expect(context.body).toMatchObject({
123
+ success: true,
124
+ data: {
125
+ capabilities: { repository: true, 'merge-request': false, commit: true },
126
+ items: [{ id: 1, defaultBranch: 'main', status: 'ready' }],
127
+ },
128
+ });
129
+ expect(JSON.stringify(context.body)).not.toContain('Restricted repository');
130
+
131
+ const searchContext = createContext({
132
+ roles,
133
+ allowRoles: roles,
134
+ permissions,
135
+ params: { kind: 'repository', search: 'Restricted repository' },
136
+ repository,
137
+ });
138
+ await chatContextOptions(searchContext.context, vi.fn().mockResolvedValue(undefined));
139
+
140
+ expect(searchContext.context.body).toMatchObject({ success: true, data: { items: [] } });
141
+ expect(searchContext.repositoryAccess.find).not.toHaveBeenCalled();
142
+ expect(JSON.stringify(searchContext.context.body)).not.toContain('Restricted repository');
143
+ });
144
+ });