plugin-git-manager 1.2.23 → 1.2.26

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 (53) hide show
  1. package/dist/client/900.acf7d1fa22f95e71.js +10 -0
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/900.f32b9dc85249fc0a.js +10 -0
  4. package/dist/client-v2/index.js +1 -1
  5. package/dist/externalVersion.js +8 -8
  6. package/dist/locale/en-US.json +4 -3
  7. package/dist/locale/vi-VN.json +4 -3
  8. package/dist/locale/zh-CN.json +4 -3
  9. package/dist/server/actions/git-actions.js +21 -8
  10. package/dist/server/actions/gitlab-api.js +5 -8
  11. package/dist/server/actions/poller.js +2 -1
  12. package/dist/server/actions/review.js +50 -13
  13. package/dist/server/actions/role-permissions.js +109 -16
  14. package/dist/server/actions/subtree.js +4 -8
  15. package/dist/server/migrations/20260730000000-migrate-legacy-repository-permissions.js +23 -7
  16. package/dist/server/plugin.js +42 -19
  17. package/dist/server/repository-access.js +505 -27
  18. package/dist/server/services/registry-content-service.js +149 -32
  19. package/dist/server/utils/get-repo-account.js +5 -2
  20. package/dist/server/utils/gitlab-url.js +2 -0
  21. package/dist/server/utils/redact.js +51 -5
  22. package/dist/server/utils/url-security.js +109 -0
  23. package/package.json +4 -2
  24. package/src/client/components/RunReviewButton.tsx +437 -436
  25. package/src/client/index.tsx +2 -1
  26. package/src/locale/en-US.json +4 -3
  27. package/src/locale/vi-VN.json +4 -3
  28. package/src/locale/zh-CN.json +4 -3
  29. package/src/server/__tests__/git-actions.test.ts +24 -0
  30. package/src/server/__tests__/plugin-url-security.test.ts +17 -0
  31. package/src/server/__tests__/poller.test.ts +37 -0
  32. package/src/server/__tests__/repository-access.test.ts +695 -1
  33. package/src/server/__tests__/review.test.ts +137 -0
  34. package/src/server/__tests__/role-permissions.test.ts +123 -2
  35. package/src/server/actions/git-actions.ts +33 -10
  36. package/src/server/actions/gitlab-api.ts +5 -8
  37. package/src/server/actions/poller.ts +2 -1
  38. package/src/server/actions/review.ts +74 -15
  39. package/src/server/actions/role-permissions.ts +136 -14
  40. package/src/server/actions/subtree.ts +4 -8
  41. package/src/server/migrations/20260730000000-migrate-legacy-repository-permissions.ts +23 -8
  42. package/src/server/plugin.ts +46 -25
  43. package/src/server/repository-access.ts +737 -28
  44. package/src/server/services/__tests__/registry-content-service.test.ts +209 -13
  45. package/src/server/services/registry-content-service.ts +473 -315
  46. package/src/server/utils/__tests__/redact.test.ts +56 -0
  47. package/src/server/utils/__tests__/url-security.test.ts +85 -0
  48. package/src/server/utils/get-repo-account.ts +22 -4
  49. package/src/server/utils/gitlab-url.ts +3 -0
  50. package/src/server/utils/redact.ts +68 -5
  51. package/src/server/utils/url-security.ts +95 -0
  52. package/dist/client/900.ee2fa037aff389e2.js +0 -10
  53. package/dist/client-v2/900.bef1c41d267e50c5.js +0 -10
@@ -1,436 +1,437 @@
1
- import React, { useCallback, useEffect, useMemo, useState } from 'react';
2
- import { Button, Dropdown, Modal, Form, Select, Input, message, Space, Tooltip, Tag, Alert } from 'antd';
3
- import { RobotOutlined, MessageOutlined, ThunderboltOutlined, ReloadOutlined } from '@ant-design/icons';
4
- import { useApp } from '@nocobase/client-v2';
5
- import * as aiClient from '@nocobase/plugin-ai/client';
6
- import { REVIEW_PROMPT_TEMPLATES } from '../promptTemplates';
7
- import { useT } from '../locale';
8
-
9
- interface ReviewFlow {
10
- id: number;
11
- name: string;
12
- enabled: boolean;
13
- triggerMode: string;
14
- aiEmployeeUsername?: string;
15
- postMode: string;
16
- repositoryId?: number;
17
- llmService?: string;
18
- model?: string;
19
- instructions?: string;
20
- }
21
-
22
- type Target =
23
- | { type: 'mr'; repositoryId: number; mrIid: number; title?: string }
24
- | { type: 'commit'; repositoryId: number; commitSha: string; title?: string }
25
- | { type: 'branch'; repositoryId: number; branch: string; title?: string }
26
- | { type: 'folder'; repositoryId: number; folderPath: string; ref?: string; title?: string };
27
-
28
- /**
29
- * Button that lets the user kick off a code review for a given target.
30
- * Two paths:
31
- * - "Run review" → POST gitManager:triggerReview (server-side, async)
32
- * - "Open chat" → call (aiClient as any).useChatBoxActions?.() || {}.triggerTask if plugin-ai is loaded,
33
- * so the user can chat with the AI employee using the same context.
34
- */
35
- export const RunReviewButton: React.FC<{
36
- target: Target;
37
- size?: 'small' | 'middle' | 'large';
38
- type?: 'default' | 'primary' | 'link';
39
- onTriggered?: (reviewId: number) => void;
40
- }> = ({ target, size = 'small', type = 'default', onTriggered }) => {
41
- const t = useT();
42
- const api = useApp().apiClient;
43
- const aiConfigRepository = (aiClient as any).useAIConfigRepository?.() || {};
44
- const { triggerTask } = (aiClient as any).useChatBoxActions?.() || {};
45
- const [open, setOpen] = useState(false);
46
- const [flows, setFlows] = useState<ReviewFlow[]>([]);
47
- const [submitting, setSubmitting] = useState(false);
48
- const [asking, setAsking] = useState(false);
49
- const [existingReview, setExistingReview] = useState<any | null>(null);
50
- const [templateKey, setTemplateKey] = useState<string | undefined>();
51
- const [form] = Form.useForm();
52
-
53
- const loadExistingReview = useCallback(() => {
54
- let cancelled = false;
55
- const filter: any = {
56
- repositoryId: target.repositoryId,
57
- targetType: target.type,
58
- };
59
- if (target.type === 'mr') filter.mrIid = target.mrIid;
60
- if (target.type === 'commit') filter.commitSha = target.commitSha;
61
- if (target.type === 'branch') filter.branch = target.branch;
62
- if (target.type === 'folder') {
63
- filter.folderPath = target.folderPath;
64
- filter.branch = target.ref || null;
65
- }
66
-
67
- api
68
- .request({
69
- url: 'gitCodeReviews:list',
70
- params: {
71
- pageSize: 1,
72
- sort: ['-id'],
73
- filter,
74
- },
75
- })
76
- .then((res) => {
77
- if (cancelled) return;
78
- const list = res?.data?.data || [];
79
- setExistingReview(list[0] || null);
80
- })
81
- .catch(() => undefined);
82
- return () => {
83
- cancelled = true;
84
- };
85
- }, [api, target]);
86
-
87
- useEffect(() => {
88
- return loadExistingReview();
89
- }, [loadExistingReview]);
90
-
91
- const loadFlows = useCallback(async () => {
92
- const { data } = await api.request({
93
- url: 'gitReviewFlows:list',
94
- params: {
95
- pageSize: 100,
96
- filter: {
97
- enabled: true,
98
- $or: [{ repositoryId: target.repositoryId }, { repositoryId: null }],
99
- },
100
- },
101
- });
102
- const list: ReviewFlow[] = data?.data || [];
103
- setFlows(list);
104
- return list;
105
- }, [api, target.repositoryId]);
106
-
107
- const pickFlow = useCallback(
108
- (list: ReviewFlow[]) => {
109
- const repoFlow = list.find((f) => f.repositoryId === target.repositoryId);
110
- return repoFlow ?? list[0] ?? null;
111
- },
112
- [target.repositoryId],
113
- );
114
-
115
- useEffect(() => {
116
- if (!open) return;
117
- setTemplateKey(undefined);
118
- let cancelled = false;
119
- loadFlows()
120
- .then((list) => {
121
- if (cancelled) return;
122
- const flow = pickFlow(list);
123
- if (flow?.id) form.setFieldValue('flowId', flow.id);
124
- })
125
- .catch(() => undefined);
126
- return () => {
127
- cancelled = true;
128
- };
129
- }, [open, loadFlows, pickFlow, form]);
130
-
131
- const handleRun = async () => {
132
- try {
133
- const values = await form.validateFields();
134
- setSubmitting(true);
135
- const params: any = {
136
- repositoryId: target.repositoryId,
137
- targetType: target.type,
138
- flowId: values.flowId,
139
- extraInstructions: values.extraInstructions || undefined,
140
- };
141
- if (target.type === 'mr') params.mrIid = target.mrIid;
142
- if (target.type === 'commit') params.commitSha = target.commitSha;
143
- if (target.type === 'branch') params.branch = target.branch;
144
- if (target.type === 'folder') {
145
- params.folderPath = target.folderPath;
146
- params.branch = target.ref;
147
- }
148
- const res = await api.request({
149
- url: 'gitManager:triggerReview',
150
- method: 'post',
151
- data: params,
152
- });
153
- const reviewId = res?.data?.data?.reviewId;
154
- message.success(t('Review started'));
155
- setOpen(false);
156
- form.resetFields();
157
- loadExistingReview();
158
- onTriggered?.(reviewId);
159
- } catch (err: any) {
160
- if (err?.errorFields) return; // validation error
161
- message.error(err?.response?.data?.errors?.[0]?.message || err?.message || t('Failed to trigger review'));
162
- } finally {
163
- setSubmitting(false);
164
- }
165
- };
166
-
167
- const buildWorkContext = () => {
168
- const title = target.title || buildContextHint();
169
- if (target.type === 'mr') {
170
- return {
171
- type: 'git-merge-request',
172
- uid: `${target.repositoryId}:${target.mrIid}`,
173
- title,
174
- content: {
175
- repositoryId: target.repositoryId,
176
- mrIid: target.mrIid,
177
- title,
178
- },
179
- };
180
- }
181
- if (target.type === 'commit') {
182
- return {
183
- type: 'git-commit',
184
- uid: `${target.repositoryId}:${target.commitSha}`,
185
- title,
186
- content: {
187
- repositoryId: target.repositoryId,
188
- commitSha: target.commitSha,
189
- title,
190
- },
191
- };
192
- }
193
- if (target.type === 'folder') {
194
- return {
195
- type: 'git-repository',
196
- uid: `${target.repositoryId}:folder:${target.folderPath}`,
197
- title,
198
- content: {
199
- repositoryId: target.repositoryId,
200
- folderPath: target.folderPath,
201
- ref: target.ref,
202
- title,
203
- },
204
- };
205
- }
206
- return {
207
- type: 'git-repository',
208
- uid: String(target.repositoryId),
209
- title,
210
- content: {
211
- repositoryId: target.repositoryId,
212
- branch: target.branch,
213
- title,
214
- },
215
- };
216
- };
217
-
218
- const buildChatPrompt = () => {
219
- if (target.type === 'mr') {
220
- return `Please review merge request !${target.mrIid} (${
221
- target.title || 'untitled'
222
- }). Use the attached Git merge request context and the available git tools when you need more detail.`;
223
- }
224
- if (target.type === 'commit') {
225
- return `Please review commit ${target.commitSha} (${
226
- target.title || 'untitled'
227
- }). Use the attached Git commit context and the available git tools when you need more detail.`;
228
- }
229
- if (target.type === 'folder') {
230
- return `Please review the full code inside folder "${target.folderPath || '/'}" at ref ${
231
- target.ref || 'HEAD'
232
- }. Use git_list_files (recursive=true) to enumerate the files, then git_get_file_content to read them.`;
233
- }
234
- return `Please help me inspect branch ${target.branch}. Use the attached Git repository context and the available git tools when you need more detail.`;
235
- };
236
-
237
- const handleOpenChat = async () => {
238
- if (!triggerTask || !aiConfigRepository?.getAIEmployees) {
239
- message.warning(t('AI plugin is not available'));
240
- return;
241
- }
242
- setAsking(true);
243
- try {
244
- const list = flows.length ? flows : await loadFlows();
245
- const flow = pickFlow(list);
246
- if (!flow?.aiEmployeeUsername) {
247
- message.warning(t('No matching flow available'));
248
- return;
249
- }
250
- const employees: any[] = aiConfigRepository.aiEmployees?.length
251
- ? aiConfigRepository.aiEmployees
252
- : await aiConfigRepository.getAIEmployees();
253
- const aiEmployee = employees.find((item) => item.username === flow.aiEmployeeUsername);
254
- if (!aiEmployee) {
255
- message.warning(t('AI employee not found'));
256
- return;
257
- }
258
- await triggerTask({
259
- aiEmployee,
260
- tasks: [
261
- {
262
- title: `${flow.name}: ${buildContextHint()}`,
263
- message: {
264
- user: buildChatPrompt(),
265
- system: flow.instructions || undefined,
266
- workContext: [buildWorkContext()],
267
- },
268
- model: flow.llmService && flow.model ? { llmService: flow.llmService, model: flow.model } : null,
269
- autoSend: false,
270
- },
271
- ],
272
- });
273
- } catch (err: any) {
274
- message.error(err?.message || t('Failed to open AI chat'));
275
- } finally {
276
- setAsking(false);
277
- }
278
- };
279
-
280
- const buildContextHint = () => {
281
- if (target.type === 'mr') return `MR !${target.mrIid}`;
282
- if (target.type === 'commit') return `Commit ${String(target.commitSha).slice(0, 7)}`;
283
- if (target.type === 'folder') return `${t('Folder')} ${target.folderPath || '/'}`;
284
- return `Branch ${target.branch}`;
285
- };
286
-
287
- // Derive re-run state for MR targets
288
- const hasNewCommits =
289
- existingReview &&
290
- existingReview.headSha &&
291
- existingReview.latestSha &&
292
- existingReview.headSha !== existingReview.latestSha;
293
- const isReReview = !!existingReview && existingReview.status !== 'pending';
294
- const buttonLabel = isReReview
295
- ? hasNewCommits
296
- ? t('Re-review (new commits)')
297
- : t('Re-run review')
298
- : t('Code Review');
299
- const ButtonIcon = isReReview ? ReloadOutlined : RobotOutlined;
300
-
301
- const items = useMemo(
302
- () => [
303
- {
304
- key: 'run',
305
- icon: <ThunderboltOutlined />,
306
- label: isReReview ? t('Re-run automated review') : t('Run automated review'),
307
- onClick: () => setOpen(true),
308
- },
309
- ...(existingReview
310
- ? [
311
- {
312
- key: 'view',
313
- icon: <RobotOutlined />,
314
- label: t(`Status: ${existingReview.status}`) + ' - ' + t('View in Review History tab'),
315
- onClick: () => {
316
- message.info(t('Please switch to the "Review History" tab to see the details.'));
317
- },
318
- },
319
- ]
320
- : []),
321
- {
322
- key: 'chat',
323
- icon: <MessageOutlined />,
324
- label: t('Ask AI Employee'),
325
- onClick: handleOpenChat,
326
- disabled: asking,
327
- },
328
- ],
329
- [isReReview, existingReview, asking, handleOpenChat, t],
330
- );
331
-
332
- return (
333
- <>
334
- <Dropdown menu={{ items }} placement="bottomRight" trigger={['click']}>
335
- <Button
336
- size={size}
337
- type={hasNewCommits ? 'primary' : type}
338
- icon={<ButtonIcon />}
339
- danger={!!hasNewCommits}
340
- loading={asking}
341
- >
342
- {buttonLabel}
343
- </Button>
344
- </Dropdown>
345
- <Modal
346
- title={
347
- <Space>
348
- <RobotOutlined />
349
- <span>{isReReview ? t('Re-run code review') : t('Run code review')}</span>
350
- <span style={{ color: '#999', fontSize: 12, fontWeight: 400 }}>{buildContextHint()}</span>
351
- </Space>
352
- }
353
- open={open}
354
- onCancel={() => setOpen(false)}
355
- onOk={handleRun}
356
- okText={isReReview ? t('Re-run') : t('Start Review')}
357
- confirmLoading={submitting}
358
- destroyOnClose
359
- >
360
- {isReReview && (
361
- <Alert
362
- type={hasNewCommits ? 'warning' : 'info'}
363
- showIcon
364
- style={{ marginBottom: 12 }}
365
- message={
366
- hasNewCommits
367
- ? t('New commits detected since last review. Re-running will overwrite the existing review.')
368
- : t('A review already exists for this target. Re-running will overwrite it.')
369
- }
370
- description={
371
- <Space size={8} wrap style={{ fontSize: 12 }}>
372
- {existingReview?.headSha && (
373
- <span>
374
- {t('Reviewed at')}:&nbsp;
375
- <Tag style={{ fontFamily: 'monospace' }}>{String(existingReview.headSha).slice(0, 7)}</Tag>
376
- </span>
377
- )}
378
- {hasNewCommits && existingReview?.latestSha && (
379
- <span>
380
- {t('Latest')}:&nbsp;
381
- <Tag color="orange" style={{ fontFamily: 'monospace' }}>
382
- {String(existingReview.latestSha).slice(0, 7)}
383
- </Tag>
384
- </span>
385
- )}
386
- </Space>
387
- }
388
- />
389
- )}
390
- <Form form={form} layout="vertical">
391
- <Form.Item
392
- name="flowId"
393
- label={t('Review Flow')}
394
- rules={[{ required: true, message: t('Please select a review flow') }]}
395
- extra={
396
- flows.length === 0 ? (
397
- <Tooltip title={t('Create a review flow in the Review Flows tab first')}>
398
- <span style={{ color: '#faad14' }}>{t('No enabled flow found for this repository')}</span>
399
- </Tooltip>
400
- ) : null
401
- }
402
- >
403
- <Select
404
- options={flows.map((f) => ({
405
- value: f.id,
406
- label: `${f.name}${f.aiEmployeeUsername ? ` — @${f.aiEmployeeUsername}` : ''}${
407
- f.repositoryId == null ? ` (${t('global')})` : ''
408
- }`,
409
- }))}
410
- placeholder={t('Select a review flow')}
411
- />
412
- </Form.Item>
413
- <Form.Item
414
- label={t('Prompt template')}
415
- extra={t('Selecting a template replaces the extra instructions text')}
416
- >
417
- <Select
418
- allowClear
419
- value={templateKey}
420
- placeholder={t('Load a default prompt by code type')}
421
- options={REVIEW_PROMPT_TEMPLATES.map((tpl) => ({ value: tpl.key, label: t(tpl.label) }))}
422
- onChange={(key) => {
423
- setTemplateKey(key);
424
- const tpl = REVIEW_PROMPT_TEMPLATES.find((item) => item.key === key);
425
- if (tpl) form.setFieldValue('extraInstructions', tpl.text);
426
- }}
427
- />
428
- </Form.Item>
429
- <Form.Item name="extraInstructions" label={t('Extra instructions (optional)')}>
430
- <Input.TextArea rows={4} placeholder={t('e.g. Focus on security issues in authentication')} />
431
- </Form.Item>
432
- </Form>
433
- </Modal>
434
- </>
435
- );
436
- };
1
+ import React, { useCallback, useEffect, useMemo, useState } from 'react';
2
+ import { Button, Dropdown, Modal, Form, Select, Input, message, Space, Tooltip, Tag, Alert } from 'antd';
3
+ import { RobotOutlined, MessageOutlined, ThunderboltOutlined, ReloadOutlined } from '@ant-design/icons';
4
+ import { useApp } from '@nocobase/client-v2';
5
+ import * as aiClient from "@nocobase/plugin-ai";
6
+ import { REVIEW_PROMPT_TEMPLATES } from '../promptTemplates';
7
+ import { useT } from '../locale';
8
+
9
+ interface ReviewFlow {
10
+ id: number;
11
+ name: string;
12
+ enabled: boolean;
13
+ triggerMode: string;
14
+ aiEmployeeUsername?: string;
15
+ postMode: string;
16
+ repositoryId?: number;
17
+ llmService?: string;
18
+ model?: string;
19
+ instructions?: string;
20
+ }
21
+
22
+ type Target =
23
+ | { type: 'mr'; repositoryId: number; mrIid: number; title?: string }
24
+ | { type: 'commit'; repositoryId: number; commitSha: string; title?: string }
25
+ | { type: 'branch'; repositoryId: number; branch: string; title?: string }
26
+ | { type: 'folder'; repositoryId: number; folderPath: string; ref?: string; title?: string };
27
+
28
+ /**
29
+ * Button that lets the user kick off a code review for a given target.
30
+ * Two paths:
31
+ * - "Run review" → POST gitManager:triggerReview (server-side, async)
32
+ * - "Open chat" → call (aiClient as any).useChatBoxActions?.() || {}.triggerTask if plugin-ai is loaded,
33
+ * so the user can chat with the AI employee using the same context.
34
+ */
35
+ export const RunReviewButton: React.FC<{
36
+ target: Target;
37
+ size?: 'small' | 'middle' | 'large';
38
+ type?: 'default' | 'primary' | 'link';
39
+ onTriggered?: (reviewId: number) => void;
40
+ }> = ({ target, size = 'small', type = 'default', onTriggered }) => {
41
+ const t = useT();
42
+ const api = useApp().apiClient;
43
+ const aiConfigRepository = (aiClient as any).useAIConfigRepository?.() || {};
44
+ const { triggerTask } = (aiClient as any).useChatBoxActions?.() || {};
45
+ const [open, setOpen] = useState(false);
46
+ const [flows, setFlows] = useState<ReviewFlow[]>([]);
47
+ const [submitting, setSubmitting] = useState(false);
48
+ const [asking, setAsking] = useState(false);
49
+ const [existingReview, setExistingReview] = useState<any | null>(null);
50
+ const [templateKey, setTemplateKey] = useState<string | undefined>();
51
+ const [form] = Form.useForm();
52
+
53
+ const loadExistingReview = useCallback(() => {
54
+ let cancelled = false;
55
+ const filter: any = {
56
+ repositoryId: target.repositoryId,
57
+ targetType: target.type,
58
+ };
59
+ if (target.type === 'mr') filter.mrIid = target.mrIid;
60
+ if (target.type === 'commit') filter.commitSha = target.commitSha;
61
+ if (target.type === 'branch') filter.branch = target.branch;
62
+ if (target.type === 'folder') {
63
+ filter.folderPath = target.folderPath;
64
+ filter.branch = target.ref || null;
65
+ }
66
+
67
+ api
68
+ .request({
69
+ url: 'gitCodeReviews:list',
70
+ params: {
71
+ pageSize: 1,
72
+ sort: ['-id'],
73
+ filter,
74
+ },
75
+ })
76
+ .then((res) => {
77
+ if (cancelled) return;
78
+ const list = res?.data?.data || [];
79
+ setExistingReview(list[0] || null);
80
+ })
81
+ .catch(() => undefined);
82
+ return () => {
83
+ cancelled = true;
84
+ };
85
+ }, [api, target]);
86
+
87
+ useEffect(() => {
88
+ return loadExistingReview();
89
+ }, [loadExistingReview]);
90
+
91
+ const loadFlows = useCallback(async () => {
92
+ const { data } = await api.request({
93
+ url: 'gitReviewFlows:list',
94
+ params: {
95
+ pageSize: 100,
96
+ filter: {
97
+ enabled: true,
98
+ $or: [{ repositoryId: target.repositoryId }, { repositoryId: null }],
99
+ },
100
+ },
101
+ });
102
+ const list: ReviewFlow[] = data?.data || [];
103
+ setFlows(list);
104
+ return list;
105
+ }, [api, target.repositoryId]);
106
+
107
+ const pickFlow = useCallback(
108
+ (list: ReviewFlow[]) => {
109
+ const repoFlow = list.find((f) => f.repositoryId === target.repositoryId);
110
+ return repoFlow ?? list[0] ?? null;
111
+ },
112
+ [target.repositoryId],
113
+ );
114
+
115
+ useEffect(() => {
116
+ if (!open) return;
117
+ setTemplateKey(undefined);
118
+ let cancelled = false;
119
+ loadFlows()
120
+ .then((list) => {
121
+ if (cancelled) return;
122
+ const flow = pickFlow(list);
123
+ if (flow?.id) form.setFieldValue('flowId', flow.id);
124
+ })
125
+ .catch(() => undefined);
126
+ return () => {
127
+ cancelled = true;
128
+ };
129
+ }, [open, loadFlows, pickFlow, form]);
130
+
131
+ const handleRun = async () => {
132
+ try {
133
+ const values = await form.validateFields();
134
+ setSubmitting(true);
135
+ const params: any = {
136
+ repositoryId: target.repositoryId,
137
+ targetType: target.type,
138
+ flowId: values.flowId,
139
+ extraInstructions: values.extraInstructions || undefined,
140
+ };
141
+ if (target.type === 'mr') params.mrIid = target.mrIid;
142
+ if (target.type === 'commit') params.commitSha = target.commitSha;
143
+ if (target.type === 'branch') params.branch = target.branch;
144
+ if (target.type === 'folder') {
145
+ params.folderPath = target.folderPath;
146
+ params.branch = target.ref;
147
+ }
148
+ const res = await api.request({
149
+ url: 'gitManager:triggerReview',
150
+ method: 'post',
151
+ data: params,
152
+ });
153
+ const reviewId = res?.data?.data?.reviewId;
154
+ message.success(t('Review started'));
155
+ setOpen(false);
156
+ form.resetFields();
157
+ loadExistingReview();
158
+ onTriggered?.(reviewId);
159
+ } catch (err: any) {
160
+ if (err?.errorFields) return; // validation error
161
+ message.error(err?.response?.data?.errors?.[0]?.message || err?.message || t('Failed to trigger review'));
162
+ } finally {
163
+ setSubmitting(false);
164
+ }
165
+ };
166
+
167
+ const buildWorkContext = () => {
168
+ const title = target.title || buildContextHint();
169
+ if (target.type === 'mr') {
170
+ return {
171
+ type: 'git-merge-request',
172
+ uid: `${target.repositoryId}:${target.mrIid}`,
173
+ title,
174
+ content: {
175
+ repositoryId: target.repositoryId,
176
+ mrIid: target.mrIid,
177
+ title,
178
+ },
179
+ };
180
+ }
181
+ if (target.type === 'commit') {
182
+ return {
183
+ type: 'git-commit',
184
+ uid: `${target.repositoryId}:${target.commitSha}`,
185
+ title,
186
+ content: {
187
+ repositoryId: target.repositoryId,
188
+ commitSha: target.commitSha,
189
+ title,
190
+ },
191
+ };
192
+ }
193
+ if (target.type === 'folder') {
194
+ return {
195
+ type: 'git-repository',
196
+ uid: `${target.repositoryId}:folder:${target.folderPath}`,
197
+ title,
198
+ content: {
199
+ repositoryId: target.repositoryId,
200
+ folderPath: target.folderPath,
201
+ ref: target.ref,
202
+ title,
203
+ },
204
+ };
205
+ }
206
+ return {
207
+ type: 'git-repository',
208
+ uid: String(target.repositoryId),
209
+ title,
210
+ content: {
211
+ repositoryId: target.repositoryId,
212
+ branch: target.branch,
213
+ title,
214
+ },
215
+ };
216
+ };
217
+
218
+ const buildChatPrompt = () => {
219
+ if (target.type === 'mr') {
220
+ return `Please review merge request !${target.mrIid} (${
221
+ target.title || 'untitled'
222
+ }). Use the attached Git merge request context and the available git tools when you need more detail.`;
223
+ }
224
+ if (target.type === 'commit') {
225
+ return `Please review commit ${target.commitSha} (${
226
+ target.title || 'untitled'
227
+ }). Use the attached Git commit context and the available git tools when you need more detail.`;
228
+ }
229
+ if (target.type === 'folder') {
230
+ return `Please review the full code inside folder "${target.folderPath || '/'}" at ref ${
231
+ target.ref || 'HEAD'
232
+ }. Use git_list_files (recursive=true) to enumerate the files, then git_get_file_content to read them.`;
233
+ }
234
+ return `Please help me inspect branch ${target.branch}. Use the attached Git repository context and the available git tools when you need more detail.`;
235
+ };
236
+
237
+ const handleOpenChat = async () => {
238
+ if (!triggerTask || !aiConfigRepository?.getAIEmployees) {
239
+ message.warning(t('AI plugin is not available'));
240
+ return;
241
+ }
242
+ setAsking(true);
243
+ try {
244
+ const list = flows.length ? flows : await loadFlows();
245
+ const flow = pickFlow(list);
246
+ if (!flow?.aiEmployeeUsername) {
247
+ message.warning(t('No matching flow available'));
248
+ return;
249
+ }
250
+ const employees: any[] = aiConfigRepository.aiEmployees?.length
251
+ ? aiConfigRepository.aiEmployees
252
+ : await aiConfigRepository.getAIEmployees();
253
+ const aiEmployee = employees.find((item) => item.username === flow.aiEmployeeUsername);
254
+ if (!aiEmployee) {
255
+ message.warning(t('AI employee not found'));
256
+ return;
257
+ }
258
+ await triggerTask({
259
+ aiEmployee,
260
+ tasks: [
261
+ {
262
+ title: `${flow.name}: ${buildContextHint()}`,
263
+ message: {
264
+ user: buildChatPrompt(),
265
+ system: flow.instructions || undefined,
266
+ workContext: [buildWorkContext()],
267
+ },
268
+ model: flow.llmService && flow.model ? { llmService: flow.llmService, model: flow.model } : null,
269
+ autoSend: false,
270
+ },
271
+ ],
272
+ });
273
+ } catch (err: any) {
274
+ message.error(err?.message || t('Failed to open AI chat'));
275
+ } finally {
276
+ setAsking(false);
277
+ }
278
+ };
279
+
280
+ const buildContextHint = () => {
281
+ if (target.type === 'mr') return `MR !${target.mrIid}`;
282
+ if (target.type === 'commit') return `Commit ${String(target.commitSha).slice(0, 7)}`;
283
+ if (target.type === 'folder') return `${t('Folder')} ${target.folderPath || '/'}`;
284
+ return `Branch ${target.branch}`;
285
+ };
286
+
287
+ // Derive re-run state for MR targets
288
+ const hasNewCommits =
289
+ existingReview &&
290
+ existingReview.headSha &&
291
+ existingReview.latestSha &&
292
+ existingReview.headSha !== existingReview.latestSha;
293
+ const isReReview = !!existingReview && existingReview.status !== 'pending';
294
+ const buttonLabel = isReReview
295
+ ? hasNewCommits
296
+ ? t('Re-review (new commits)')
297
+ : t('Re-run review')
298
+ : t('Code Review');
299
+ const ButtonIcon = isReReview ? ReloadOutlined : RobotOutlined;
300
+
301
+ const items = useMemo(
302
+ () => [
303
+ {
304
+ key: 'run',
305
+ icon: <ThunderboltOutlined />,
306
+ label: isReReview ? t('Re-run automated review') : t('Run automated review'),
307
+ onClick: () => setOpen(true),
308
+ },
309
+ ...(existingReview
310
+ ? [
311
+ {
312
+ key: 'view',
313
+ icon: <RobotOutlined />,
314
+ label: t(`Status: ${existingReview.status}`) + ' - ' + t('View in Review History tab'),
315
+ onClick: () => {
316
+ message.info(t('Please switch to the "Review History" tab to see the details.'));
317
+ },
318
+ },
319
+ ]
320
+ : []),
321
+ {
322
+ key: 'chat',
323
+ icon: <MessageOutlined />,
324
+ label: t('Ask AI Employee'),
325
+ onClick: handleOpenChat,
326
+ disabled: asking,
327
+ },
328
+ ],
329
+ [isReReview, existingReview, asking, handleOpenChat, t],
330
+ );
331
+
332
+ return (
333
+ <>
334
+ <Dropdown menu={{ items }} placement="bottomRight" trigger={['click']}>
335
+ <Button
336
+ size={size}
337
+ type={hasNewCommits ? 'primary' : type}
338
+ icon={<ButtonIcon />}
339
+ danger={!!hasNewCommits}
340
+ loading={asking}
341
+ >
342
+ {buttonLabel}
343
+ </Button>
344
+ </Dropdown>
345
+ <Modal
346
+ title={
347
+ <Space>
348
+ <RobotOutlined />
349
+ <span>{isReReview ? t('Re-run code review') : t('Run code review')}</span>
350
+ <span style={{ color: '#999', fontSize: 12, fontWeight: 400 }}>{buildContextHint()}</span>
351
+ </Space>
352
+ }
353
+ open={open}
354
+ onCancel={() => setOpen(false)}
355
+ onOk={handleRun}
356
+ okText={isReReview ? t('Re-run') : t('Start Review')}
357
+ confirmLoading={submitting}
358
+ destroyOnClose
359
+ >
360
+ {isReReview && (
361
+ <Alert
362
+ type={hasNewCommits ? 'warning' : 'info'}
363
+ showIcon
364
+ style={{ marginBottom: 12 }}
365
+ message={
366
+ hasNewCommits
367
+ ? t('New commits detected since last review. Re-running will overwrite the existing review.')
368
+ : t('A review already exists for this target. Re-running will overwrite it.')
369
+ }
370
+ description={
371
+ <Space size={8} wrap style={{ fontSize: 12 }}>
372
+ {existingReview?.headSha && (
373
+ <span>
374
+ {t('Reviewed at')}:&nbsp;
375
+ <Tag style={{ fontFamily: 'monospace' }}>{String(existingReview.headSha).slice(0, 7)}</Tag>
376
+ </span>
377
+ )}
378
+ {hasNewCommits && existingReview?.latestSha && (
379
+ <span>
380
+ {t('Latest')}:&nbsp;
381
+ <Tag color="orange" style={{ fontFamily: 'monospace' }}>
382
+ {String(existingReview.latestSha).slice(0, 7)}
383
+ </Tag>
384
+ </span>
385
+ )}
386
+ </Space>
387
+ }
388
+ />
389
+ )}
390
+ <Form form={form} layout="vertical">
391
+ <Form.Item
392
+ name="flowId"
393
+ label={t('Review Flow')}
394
+ rules={[{ required: true, message: t('Please select a review flow') }]}
395
+ extra={
396
+ flows.length === 0 ? (
397
+ <Tooltip title={t('Create a review flow in the Review Flows tab first')}>
398
+ <span style={{ color: '#faad14' }}>{t('No enabled flow found for this repository')}</span>
399
+ </Tooltip>
400
+ ) : null
401
+ }
402
+ >
403
+ <Select
404
+ options={flows.map((f) => ({
405
+ value: f.id,
406
+ label: `${f.name}${f.aiEmployeeUsername ? ` — @${f.aiEmployeeUsername}` : ''}${
407
+ f.repositoryId == null ? ` (${t('global')})` : ''
408
+ }`,
409
+ }))}
410
+ placeholder={t('Select a review flow')}
411
+ />
412
+ </Form.Item>
413
+ <Form.Item
414
+ label={t('Prompt template')}
415
+ extra={t('Selecting a template replaces the extra instructions text')}
416
+ >
417
+ <Select
418
+ allowClear
419
+ value={templateKey}
420
+ placeholder={t('Load a default prompt by code type')}
421
+ options={REVIEW_PROMPT_TEMPLATES.map((tpl) => ({ value: tpl.key, label: t(tpl.label) }))}
422
+ onChange={(key) => {
423
+ setTemplateKey(key);
424
+ const tpl = REVIEW_PROMPT_TEMPLATES.find((item) => item.key === key);
425
+ if (tpl) form.setFieldValue('extraInstructions', tpl.text);
426
+ }}
427
+ />
428
+ </Form.Item>
429
+ <Form.Item name="extraInstructions" label={t('Extra instructions (optional)')}>
430
+ <Input.TextArea rows={4} placeholder={t('e.g. Focus on security issues in authentication')} />
431
+ </Form.Item>
432
+ </Form>
433
+ </Modal>
434
+ </>
435
+ );
436
+ };
437
+