plugin-git-manager 1.3.3 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/client/{156.c27c2392746e7866.js → 156.8e36af3e2cee173e.js} +1 -1
  2. package/dist/client/317.e7b1d59371812c30.js +10 -0
  3. package/dist/client/434.05d0ba2b821105dc.js +10 -0
  4. package/dist/client/453.cdcba6d2d0c9522b.js +10 -0
  5. package/dist/client/454.625da741a7e1161f.js +10 -0
  6. package/dist/client/index.js +1 -1
  7. package/dist/client-v2/317.4e116f84ed9081b6.js +10 -0
  8. package/dist/client-v2/434.764113d20743a45b.js +10 -0
  9. package/dist/client-v2/453.5ab80c06d8e61a7e.js +10 -0
  10. package/dist/client-v2/454.b885b1d35ef7ff72.js +10 -0
  11. package/dist/client-v2/index.js +1 -1
  12. package/dist/externalVersion.js +10 -9
  13. package/dist/locale/en-US.json +38 -1
  14. package/dist/locale/vi-VN.json +38 -1
  15. package/dist/locale/zh-CN.json +41 -1
  16. package/dist/node_modules/simple-git/package.json +1 -1
  17. package/dist/node_modules/zod/package.json +1 -1
  18. package/dist/server/actions/chat-context.js +282 -0
  19. package/dist/server/actions/git-actions.js +387 -80
  20. package/dist/server/actions/gitlab-api.js +101 -15
  21. package/dist/server/actions/subtree.js +20 -10
  22. package/dist/server/chat-context-admission.js +187 -0
  23. package/dist/server/plugin.js +142 -10
  24. package/dist/server/repository-access.js +2 -2
  25. package/dist/server/request-method-policy.js +4 -1
  26. package/dist/server/services/review-source.js +2 -1
  27. package/dist/server/utils/cluster-git.js +181 -0
  28. package/package.json +2 -2
  29. package/src/client/__tests__/FileExplorerAndManage.test.tsx +236 -0
  30. package/src/client/__tests__/GitContextPicker.test.tsx +120 -0
  31. package/src/client/__tests__/ai-context.test.tsx +119 -0
  32. package/src/client/__tests__/workflowRoutes.test.ts +3 -1
  33. package/src/client/ai-context.tsx +3 -113
  34. package/src/client/components/CommitHistory.tsx +19 -7
  35. package/src/client/components/FileExplorer.tsx +80 -34
  36. package/src/client/components/GitManagerSettings.tsx +21 -5
  37. package/src/client/components/GitOperations.tsx +25 -4
  38. package/src/client/components/GitRuntimeBanner.tsx +97 -0
  39. package/src/client/components/RepositoryConfig.tsx +28 -6
  40. package/src/client/context/GitManagerContext.tsx +174 -15
  41. package/src/client/index.tsx +3 -5
  42. package/src/client/workflowRoutes.ts +11 -0
  43. package/src/client-v2/ai-context.tsx +135 -72
  44. package/src/client-v2/components/GitContextPicker.tsx +418 -0
  45. package/src/client-v2/git-context-api.ts +59 -0
  46. package/src/client-v2/plugin.tsx +2 -4
  47. package/src/locale/en-US.json +38 -1
  48. package/src/locale/vi-VN.json +38 -1
  49. package/src/locale/zh-CN.json +41 -1
  50. package/src/server/__tests__/chat-context-admission.test.ts +276 -0
  51. package/src/server/__tests__/chat-context-options.test.ts +144 -0
  52. package/src/server/__tests__/git-actions.test.ts +329 -4
  53. package/src/server/__tests__/git-chat-context.test.ts +138 -0
  54. package/src/server/__tests__/git-security.test.ts +52 -0
  55. package/src/server/__tests__/smoke.test.ts +232 -1
  56. package/src/server/actions/chat-context.ts +302 -0
  57. package/src/server/actions/git-actions.ts +428 -89
  58. package/src/server/actions/gitlab-api.ts +113 -14
  59. package/src/server/actions/subtree.ts +23 -6
  60. package/src/server/chat-context-admission.ts +182 -0
  61. package/src/server/plugin.ts +163 -3
  62. package/src/server/repository-access.ts +2 -2
  63. package/src/server/request-method-policy.ts +3 -0
  64. package/src/server/services/review-source.ts +3 -2
  65. package/src/server/utils/cluster-git.ts +209 -0
  66. package/dist/client/317.17ed0018e3e7db00.js +0 -10
  67. package/dist/client/434.b2eeaaef33aae6e0.js +0 -10
  68. package/dist/client/453.fc3042c9740d8fab.js +0 -10
  69. package/dist/client-v2/317.d2466574d00f94d0.js +0 -10
  70. package/dist/client-v2/434.19c7579c06b9077c.js +0 -10
  71. package/dist/client-v2/453.5e507c94c59277b1.js +0 -10
@@ -1,7 +1,17 @@
1
- import React, { createContext, useContext, useState, useCallback, useRef } from 'react';
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
- interface Repository {
14
+ export interface Repository {
5
15
  id: number;
6
16
  name: string;
7
17
  repoUrl: string;
@@ -12,19 +22,65 @@ interface Repository {
12
22
  autoReviewFlowId?: number | null;
13
23
  }
14
24
 
25
+ export interface GitRuntimeInfo {
26
+ checked: boolean;
27
+ gitAvailable: boolean;
28
+ gitBinary: string;
29
+ clusterManager: {
30
+ available: boolean;
31
+ gitConfigured: boolean;
32
+ status: 'idle' | 'running' | 'succeeded' | 'failed';
33
+ progressPercent: number;
34
+ };
35
+ }
36
+
15
37
  interface GitManagerContextType {
16
38
  repos: Repository[];
17
39
  selectedRepo: Repository | null;
18
40
  loading: boolean;
19
41
  branches: string[];
20
42
  currentBranch: string;
43
+ gitRuntime: GitRuntimeInfo;
44
+ installingGit: boolean;
21
45
  setSelectedRepo: (repo: Repository | null) => void;
22
46
  refreshRepos: () => Promise<void>;
23
- refreshBranches: () => Promise<void>;
47
+ refreshBranches: () => Promise<string>;
48
+ refreshRuntimeStatus: () => Promise<void>;
49
+ installGitViaCluster: () => Promise<boolean>;
24
50
  }
25
51
 
52
+ const DEFAULT_GIT_RUNTIME: GitRuntimeInfo = {
53
+ checked: false,
54
+ gitAvailable: true,
55
+ gitBinary: 'git',
56
+ clusterManager: {
57
+ available: false,
58
+ gitConfigured: false,
59
+ status: 'idle',
60
+ progressPercent: 0,
61
+ },
62
+ };
63
+
26
64
  const GitManagerContext = createContext<GitManagerContextType | null>(null);
27
65
 
66
+ function readQueryRepositoryId(): string | null {
67
+ if (typeof window === 'undefined') return null;
68
+ return new URLSearchParams(window.location.search).get('repositoryId');
69
+ }
70
+
71
+ function syncManageQueryRepositoryId(repositoryId: number | null): void {
72
+ if (typeof window === 'undefined' || !window.location.pathname.endsWith('/git-manager/manage')) {
73
+ return;
74
+ }
75
+ const url = new URL(window.location.href);
76
+ if (repositoryId == null) {
77
+ url.searchParams.delete('repositoryId');
78
+ } else {
79
+ url.searchParams.set('repositoryId', String(repositoryId));
80
+ }
81
+ window.history.replaceState(window.history.state, '', `${url.pathname}${url.search}${url.hash}`);
82
+ }
83
+
28
84
  export function useGitManager() {
29
85
  const context = useContext(GitManagerContext);
30
86
  if (!context) {
@@ -34,48 +90,138 @@ export function useGitManager() {
34
90
  }
35
91
 
36
92
  export const GitManagerProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
37
- const api = useApp().apiClient;
93
+ const app = useApp();
94
+ const api = app.apiClient;
38
95
  const [repos, setRepos] = useState<Repository[]>([]);
39
- const [selectedRepo, setSelectedRepo] = useState<Repository | null>(null);
96
+ const [selectedRepo, setSelectedRepoState] = useState<Repository | null>(null);
40
97
  const [loading, setLoading] = useState(false);
41
98
  const [branches, setBranches] = useState<string[]>([]);
42
99
  const [currentBranch, setCurrentBranch] = useState('');
100
+ const [gitRuntime, setGitRuntime] = useState<GitRuntimeInfo>(DEFAULT_GIT_RUNTIME);
101
+ const [installingGit, setInstallingGit] = useState(false);
43
102
  const selectedRepoRef = useRef(selectedRepo);
44
103
  selectedRepoRef.current = selectedRepo;
104
+ const gitRuntimeRef = useRef(gitRuntime);
105
+ gitRuntimeRef.current = gitRuntime;
106
+
107
+ const setSelectedRepo = useCallback((repo: Repository | null) => {
108
+ setSelectedRepoState(repo);
109
+ syncManageQueryRepositoryId(repo?.id ?? null);
110
+ }, []);
111
+
112
+ useEffect(() => {
113
+ setCurrentGitRepository(app, selectedRepo?.id);
114
+ return () => setCurrentGitRepository(app);
115
+ }, [app, selectedRepo?.id]);
45
116
 
46
- const refreshBranches = useCallback(async () => {
117
+ const refreshRuntimeStatus = useCallback(async () => {
118
+ try {
119
+ const { data } = await api.request({
120
+ url: 'gitManager:runtimeStatus',
121
+ skipNotify: true,
122
+ });
123
+ const payload = data?.data?.data || data?.data;
124
+ if (payload && typeof payload.gitAvailable === 'boolean') {
125
+ const cluster = payload.clusterManager || {};
126
+ setGitRuntime({
127
+ checked: true,
128
+ gitAvailable: payload.gitAvailable,
129
+ gitBinary: typeof payload.gitBinary === 'string' ? payload.gitBinary : 'git',
130
+ clusterManager: {
131
+ available: Boolean(cluster.available),
132
+ gitConfigured: Boolean(cluster.gitConfigured),
133
+ status:
134
+ cluster.status === 'running' || cluster.status === 'succeeded' || cluster.status === 'failed'
135
+ ? cluster.status
136
+ : 'idle',
137
+ progressPercent: typeof cluster.progressPercent === 'number' ? cluster.progressPercent : 0,
138
+ },
139
+ });
140
+ }
141
+ } catch {
142
+ // Preserve optimistic default when runtimeStatus is unavailable in test mocks.
143
+ }
144
+ }, [api]);
145
+
146
+ useEffect(() => {
147
+ refreshRuntimeStatus();
148
+ }, [refreshRuntimeStatus]);
149
+
150
+ useEffect(() => {
151
+ if (!gitRuntime.checked || gitRuntime.gitAvailable || gitRuntime.clusterManager.status !== 'running') {
152
+ return;
153
+ }
154
+ const interval = setInterval(() => {
155
+ refreshRuntimeStatus();
156
+ }, 3000);
157
+ return () => clearInterval(interval);
158
+ }, [gitRuntime.checked, gitRuntime.gitAvailable, gitRuntime.clusterManager.status, refreshRuntimeStatus]);
159
+
160
+ const installGitViaCluster = useCallback(async (): Promise<boolean> => {
161
+ setInstallingGit(true);
162
+ try {
163
+ await api.request({
164
+ url: 'gitManager:installGit',
165
+ method: 'post',
166
+ });
167
+ await refreshRuntimeStatus();
168
+ return true;
169
+ } catch {
170
+ return false;
171
+ } finally {
172
+ setInstallingGit(false);
173
+ }
174
+ }, [api, refreshRuntimeStatus]);
175
+
176
+ const refreshBranches = useCallback(async (): Promise<string> => {
47
177
  const repo = selectedRepoRef.current;
48
- if (!repo || repo.status !== 'connected') {
178
+ if (
179
+ !repo ||
180
+ repo.status !== 'connected' ||
181
+ (gitRuntimeRef.current.checked && !gitRuntimeRef.current.gitAvailable)
182
+ ) {
49
183
  setBranches([]);
50
184
  setCurrentBranch('');
51
- return;
185
+ return '';
52
186
  }
53
187
  try {
54
188
  const { data } = await api.request({
55
189
  url: 'gitManager:branches',
56
190
  params: { repositoryId: repo.id },
191
+ skipNotify: true,
57
192
  });
58
193
  const responseData = data?.data?.data || data?.data;
59
194
  if (responseData) {
60
- setBranches(responseData.all || []);
61
- setCurrentBranch(responseData.current || '');
195
+ const nextBranches = Array.isArray(responseData.all) ? (responseData.all as string[]) : [];
196
+ const nextCurrent = typeof responseData.current === 'string' ? responseData.current : '';
197
+ setBranches(nextBranches);
198
+ setCurrentBranch(nextCurrent);
199
+ return nextCurrent;
62
200
  }
63
201
  } catch {
64
202
  setBranches([]);
65
203
  setCurrentBranch('');
204
+ refreshRuntimeStatus();
66
205
  }
67
- }, [api]);
206
+ return '';
207
+ }, [api, refreshRuntimeStatus]);
68
208
 
69
209
  const refreshRepos = useCallback(async () => {
70
210
  setLoading(true);
71
211
  try {
72
212
  const { data } = await api.request({ url: 'gitRepositories:list', params: { pageSize: 100 } });
73
- const list = data?.data || [];
213
+ const list = (data?.data || []) as Repository[];
74
214
  setRepos(list);
75
215
  const current = selectedRepoRef.current;
76
216
  if (current) {
77
- const updated = list.find((r: Repository) => r.id === current.id);
78
- if (updated) setSelectedRepo(updated);
217
+ const updated = list.find((r) => r.id === current.id);
218
+ if (updated) setSelectedRepoState(updated);
219
+ } else {
220
+ const queryRepoId = readQueryRepositoryId();
221
+ if (queryRepoId) {
222
+ const matched = list.find((r) => String(r.id) === queryRepoId);
223
+ if (matched) setSelectedRepoState(matched);
224
+ }
79
225
  }
80
226
  } finally {
81
227
  setLoading(false);
@@ -84,7 +230,20 @@ export const GitManagerProvider: React.FC<{ children: React.ReactNode }> = ({ ch
84
230
 
85
231
  return (
86
232
  <GitManagerContext.Provider
87
- value={{ repos, selectedRepo, loading, branches, currentBranch, setSelectedRepo, refreshRepos, refreshBranches }}
233
+ value={{
234
+ repos,
235
+ selectedRepo,
236
+ loading,
237
+ branches,
238
+ currentBranch,
239
+ gitRuntime,
240
+ installingGit,
241
+ setSelectedRepo,
242
+ refreshRepos,
243
+ refreshBranches,
244
+ refreshRuntimeStatus,
245
+ installGitViaCluster,
246
+ }}
88
247
  >
89
248
  {children}
90
249
  </GitManagerContext.Provider>
@@ -3,7 +3,7 @@
3
3
  import { Plugin } from '@nocobase/client';
4
4
  import type PluginAIClientV2 from '@nocobase/plugin-ai/client-v2';
5
5
  import React from 'react';
6
- import { GitRepositoryWorkContext, GitMergeRequestWorkContext, GitCommitWorkContext } from './ai-context';
6
+ import { registerGitWorkContexts } from './ai-context';
7
7
 
8
8
  const GitManagerSettings = React.lazy(() =>
9
9
  import('./components/GitManagerSettings').then((m) => ({ default: m.GitManagerSettings })),
@@ -70,10 +70,8 @@ export class PluginGitManagerClient extends Plugin {
70
70
  });
71
71
 
72
72
  const aiManager = this.app.pm.get<PluginAIClientV2>('ai')?.aiManager;
73
- if (aiManager?.registerWorkContext) {
74
- aiManager.registerWorkContext('git-repository', GitRepositoryWorkContext);
75
- aiManager.registerWorkContext('git-merge-request', GitMergeRequestWorkContext);
76
- aiManager.registerWorkContext('git-commit', GitCommitWorkContext);
73
+ if (aiManager) {
74
+ await registerGitWorkContexts(this.app, aiManager);
77
75
  }
78
76
 
79
77
  const aclPlugin = this.app.pm.get<PluginACLClient>('acl');
@@ -25,3 +25,14 @@ export function reviewApprovalHref(app: App) {
25
25
  const base = getRouteRuntimeVersion() === 'modern' ? getV2EffectiveBasePath(app) : legacyBase(app);
26
26
  return join(base, '/admin/workflow/tasks/git-review-approval/pending');
27
27
  }
28
+
29
+ export function gitManagerManageHref(app: App, repositoryId?: string | number) {
30
+ const base = getRouteRuntimeVersion() === 'modern' ? getV2EffectiveBasePath(app) : legacyBase(app);
31
+ const path = join(base, '/admin/settings/git-manager/manage');
32
+ return repositoryId == null ? path : `${path}?repositoryId=${encodeURIComponent(String(repositoryId))}`;
33
+ }
34
+
35
+ export function clusterPackageInstallerHref(app: App) {
36
+ const base = getRouteRuntimeVersion() === 'modern' ? getV2EffectiveBasePath(app) : legacyBase(app);
37
+ return join(base, '/admin/settings/plugin-cluster-manager');
38
+ }
@@ -1,12 +1,22 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
1
3
  import { BranchesOutlined, MergeOutlined, NodeIndexOutlined } from '@ant-design/icons';
2
4
  import type { AIManager, ContextItem } from '@nocobase/plugin-ai/client-v2';
3
- import { Space } from 'antd';
5
+ import { Registry } from '@nocobase/utils/client';
6
+ import { message, Space } from 'antd';
4
7
  import React from 'react';
5
8
  import { useTranslation } from 'react-i18next';
9
+ import { GitContextPicker } from './components/GitContextPicker';
10
+ import { actionData, fetchGitContext, type GitContextApp, type GitContextKind } from './git-context-api';
6
11
 
7
12
  type WorkContextOptions = Parameters<AIManager['registerWorkContext']>[1];
13
+ type ContextCapabilities = Record<GitContextKind, boolean>;
14
+
15
+ const kinds: GitContextKind[] = ['repository', 'merge-request', 'commit'];
16
+ const emptyCapabilities = (): ContextCapabilities => ({ repository: false, 'merge-request': false, commit: false });
17
+ const registrations = new WeakMap<AIManager, Promise<void>>();
8
18
 
9
- function ContextLabel({ kind, title }: { kind: 'repository' | 'merge-request' | 'commit'; title?: string }) {
19
+ function ContextLabel({ kind, title }: { kind: GitContextKind; title?: string }) {
10
20
  const { t } = useTranslation('plugin-git-manager');
11
21
  const labels = { repository: 'Git Repository', 'merge-request': 'Git Merge Request', commit: 'Git Commit' };
12
22
  const icons = { repository: <BranchesOutlined />, 'merge-request': <MergeOutlined />, commit: <NodeIndexOutlined /> };
@@ -18,82 +28,135 @@ function ContextLabel({ kind, title }: { kind: 'repository' | 'merge-request' |
18
28
  );
19
29
  }
20
30
 
21
- function recordFromResponse(response: unknown): Record<string, unknown> | null {
22
- const data = (response as { data?: { data?: unknown } })?.data?.data;
23
- return data && typeof data === 'object' ? (data as Record<string, unknown>) : null;
24
- }
25
-
26
- function contextComponents(kind: 'repository' | 'merge-request' | 'commit') {
31
+ function contextDefinition(app: GitContextApp, kind: GitContextKind): WorkContextOptions {
27
32
  return {
28
- menu: { Component: () => <ContextLabel kind={kind} /> },
33
+ name: `git-${kind}`,
29
34
  tag: {
30
35
  Component: ({ item }: { item: ContextItem }) => <ContextLabel kind={kind} title={item.title || item.uid} />,
31
36
  },
37
+ getContent: async (currentApp, { uid }) => {
38
+ try {
39
+ return await fetchGitContext(app, kind, uid);
40
+ } catch (error) {
41
+ message.error(
42
+ currentApp.i18n.t('Git context is unavailable. Check your access and select it again.', {
43
+ ns: 'plugin-git-manager',
44
+ }),
45
+ );
46
+ throw error;
47
+ }
48
+ },
32
49
  };
33
50
  }
34
51
 
35
- export const GitRepositoryWorkContext: WorkContextOptions = {
36
- name: 'git-repository',
37
- ...contextComponents('repository'),
38
- getContent: async (app, { uid }) => {
39
- const repo = recordFromResponse(
40
- await app.apiClient.request({ url: 'gitRepositories:get', params: { filterByTk: uid } }),
41
- );
42
- if (!repo) return null;
43
- return {
44
- type: 'git-repository',
45
- repositoryId: repo.id,
46
- name: repo.name,
47
- repoUrl: repo.repoUrl,
48
- defaultBranch: repo.defaultBranch,
49
- status: repo.status,
50
- };
51
- },
52
- };
52
+ function contextMenu(
53
+ app: GitContextApp,
54
+ kind: GitContextKind,
55
+ isAllowed: () => boolean,
56
+ ): NonNullable<WorkContextOptions['menu']> {
57
+ return {
58
+ Component: () => <ContextLabel kind={kind} />,
59
+ onClick: ({ ctx, onAdd }) => {
60
+ if (!isAllowed()) return;
61
+ let active = true;
62
+ const dialog = ctx.viewer.dialog({
63
+ title: <ContextLabel kind={kind} />,
64
+ width: 720,
65
+ zIndex: 2200,
66
+ onClose: () => {
67
+ active = false;
68
+ },
69
+ content: () => (
70
+ <GitContextPicker
71
+ app={app}
72
+ kind={kind}
73
+ onAdd={onAdd}
74
+ isActive={() => active && isAllowed()}
75
+ onClose={() => {
76
+ dialog.close();
77
+ }}
78
+ />
79
+ ),
80
+ });
81
+ },
82
+ };
83
+ }
53
84
 
54
- export const GitMergeRequestWorkContext: WorkContextOptions = {
55
- name: 'git-merge-request',
56
- ...contextComponents('merge-request'),
57
- getContent: async (app, { uid }) => {
58
- const [repositoryId, iid] = uid.split(':');
59
- const mrIid = Number(iid);
60
- if (!repositoryId || !Number.isSafeInteger(mrIid) || mrIid <= 0) return null;
61
- const data = recordFromResponse(
62
- await app.apiClient.request({
63
- url: 'gitManager:mergeRequestDetail',
64
- params: { repositoryId, mrIid },
65
- }),
66
- );
67
- if (!data) return null;
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
- };
85
+ /** Register readers even when the current role cannot add Git context. */
86
+ export function registerGitWorkContexts(app: GitContextApp, manager: AIManager): Promise<void> {
87
+ let registration = registrations.get(manager);
88
+ if (!registration) {
89
+ registration = initializeGitWorkContexts(app, manager);
90
+ registrations.set(manager, registration);
91
+ }
92
+ return registration;
93
+ }
94
+
95
+ async function initializeGitWorkContexts(app: GitContextApp, manager: AIManager): Promise<void> {
96
+ let capabilities = emptyCapabilities();
97
+ let requestSequence = 0;
98
+
99
+ for (const kind of kinds) {
100
+ const name = `git-${kind}`;
101
+ if (!manager.getWorkContext(name)) manager.registerWorkContext(name, contextDefinition(app, kind));
102
+ }
103
+
104
+ const updateMenus = () => {
105
+ const registry = new Registry<WorkContextOptions>();
106
+ for (const [name, existing] of manager.workContext.getEntities()) {
107
+ const kind = kinds.find((item) => name === `git-${item}`);
108
+ if (!kind) {
109
+ registry.register(name, existing);
110
+ continue;
111
+ }
112
+ const { menu: _menu, ...definition } = existing;
113
+ registry.register(name, {
114
+ ...definition,
115
+ ...(capabilities[kind] ? { menu: contextMenu(app, kind, () => capabilities[kind]) } : {}),
116
+ });
117
+ }
118
+ manager.workContext = registry;
119
+ };
82
120
 
83
- export const GitCommitWorkContext: WorkContextOptions = {
84
- name: 'git-commit',
85
- ...contextComponents('commit'),
86
- getContent: async (app, { uid }) => {
87
- const separator = uid.indexOf(':');
88
- const repositoryId = uid.slice(0, separator),
89
- commitSha = uid.slice(separator + 1);
90
- if (separator <= 0 || !commitSha) return null;
91
- const data = recordFromResponse(
92
- await app.apiClient.request({
93
- url: 'gitManager:commitDetail',
94
- params: { repositoryId, commitHash: commitSha },
95
- }),
96
- );
97
- return data ? { ...data, type: 'git-commit', repositoryId, commitSha } : null;
98
- },
99
- };
121
+ const refresh = async () => {
122
+ const sequence = ++requestSequence;
123
+ capabilities = emptyCapabilities();
124
+ updateMenus();
125
+ if (app.apiClient.auth && !app.apiClient.auth.token) return;
126
+ try {
127
+ const result = actionData(
128
+ await app.apiClient.request({ url: 'gitManager:chatContextOptions', skipNotify: true, timeout: 5000 }),
129
+ ) as { capabilities?: Partial<ContextCapabilities> } | undefined;
130
+ if (sequence !== requestSequence) return;
131
+ capabilities = {
132
+ repository: result?.capabilities?.repository === true,
133
+ 'merge-request': result?.capabilities?.['merge-request'] === true,
134
+ commit: result?.capabilities?.commit === true,
135
+ };
136
+ updateMenus();
137
+ } catch {
138
+ // A failed capability request keeps all menu entries hidden.
139
+ }
140
+ };
141
+
142
+ app.eventBus.addEventListener('auth:tokenChanged', () => {
143
+ refresh();
144
+ });
145
+ const client = app.apiClient as typeof app.apiClient & {
146
+ axios?: {
147
+ interceptors?: {
148
+ response?: {
149
+ use: (handler: (response: { config?: { url?: string } }) => { config?: { url?: string } }) => unknown;
150
+ };
151
+ };
152
+ };
153
+ };
154
+ client.axios?.interceptors?.response?.use((response) => {
155
+ if (/(^|\/)roles:check(?:\?|$)/.test(response.config?.url || '')) {
156
+ // ACLRolesCheckProvider applies the returned role after this interceptor resolves.
157
+ setTimeout(() => refresh(), 0);
158
+ }
159
+ return response;
160
+ });
161
+ await refresh();
162
+ }