-
Notifications
You must be signed in to change notification settings - Fork 313
Expand file tree
/
Copy pathconnectorsMenu.tsx
More file actions
348 lines (320 loc) · 15.3 KB
/
Copy pathconnectorsMenu.tsx
File metadata and controls
348 lines (320 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
'use client';
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Switch } from "@/components/ui/switch";
import { connectMcpToAsk, getMcpServersWithStatus } from "@/app/api/(client)/client";
import { useToast } from "@/components/hooks/use-toast";
import { McpFavicon } from "@/ee/features/chat/mcp/components/mcpFavicon";
import { mcpQueryKeys } from "@/ee/features/chat/mcp/queryKeys";
import { ErrorCode } from "@/lib/errorCodes";
import type { ServiceError } from "@/lib/serviceError";
import { isServiceError } from "@/lib/utils";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { AlertTriangleIcon, CableIcon, Loader2Icon, LogInIcon, PlusCircleIcon, PlusIcon, RefreshCwIcon, SettingsIcon } from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { useSlate } from "slate-react";
import { Editor } from "slate";
import type { CustomEditor, SearchScope } from "@/features/chat/types";
import {
clearMcpOAuthDraft,
consumeMcpOAuthDraftForPath,
createMcpOAuthDraftPath,
saveMcpOAuthDraft,
} from "@/features/chat/mcpOAuthDraft";
import { clearEditorHistory, resetEditor } from "@/features/chat/utils";
import { useRole } from "@/features/auth/useRole";
import { OrgRole } from "@sourcebot/db";
interface ConnectorsMenuProps {
selectedSearchScopes: SearchScope[];
onSelectedSearchScopesChange: (items: SearchScope[]) => void;
disabledMcpServerIds: string[];
onDisabledMcpServerIdsChange: (ids: string[]) => void;
isAuthenticated: boolean;
}
interface ChatMenuMcpServer {
isConnected: boolean;
isAuthExpired: boolean;
}
export class McpServersLoadError extends Error {
constructor(public readonly serviceError: ServiceError) {
super("Failed to load connectors");
}
}
export function shouldRetryMcpServersLoad(failureCount: number, error: Error) {
if (error instanceof McpServersLoadError && error.serviceError.errorCode === ErrorCode.NOT_AUTHENTICATED) {
return false;
}
return failureCount < 3;
}
export function splitMcpServersForChatMenu<T extends ChatMenuMcpServer>(servers: T[]) {
return {
connectedServers: servers.filter((server) => server.isConnected || server.isAuthExpired),
connectableServers: servers.filter((server) => !server.isConnected && !server.isAuthExpired),
};
}
function restoreEditorChildren(editor: CustomEditor, children: CustomEditor['children']) {
editor.children = children;
editor.selection = {
anchor: Editor.end(editor, []),
focus: Editor.end(editor, []),
};
clearEditorHistory(editor);
editor.onChange();
}
export const ConnectorsMenu = ({
selectedSearchScopes,
onSelectedSearchScopesChange,
disabledMcpServerIds,
onDisabledMcpServerIdsChange,
isAuthenticated,
}: ConnectorsMenuProps) => {
const [connectingServerId, setConnectingServerId] = useState<string | null>(null);
const editor = useSlate();
const hasRestoredMcpOAuthDraft = useRef(false);
const isMountedRef = useRef(false);
const queryClient = useQueryClient();
const router = useRouter();
const pathname = usePathname();
const { toast } = useToast();
const isOwner = useRole() === OrgRole.OWNER;
const loginHref = `/login?callbackUrl=${encodeURIComponent(pathname)}`;
const { data: servers = [], error, isError, isLoading, refetch } = useQuery({
queryKey: mcpQueryKeys.serversWithStatus,
queryFn: async () => {
const result = await getMcpServersWithStatus();
if (isServiceError(result)) {
throw new McpServersLoadError(result);
}
return result;
},
retry: shouldRetryMcpServersLoad,
enabled: isAuthenticated,
});
useEffect(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
};
}, []);
useEffect(() => {
if (hasRestoredMcpOAuthDraft.current) {
return;
}
const currentPath = createMcpOAuthDraftPath(window.location.pathname, window.location.search);
if (!currentPath) {
return;
}
const draft = consumeMcpOAuthDraftForPath(currentPath);
if (!draft) {
return;
}
hasRestoredMcpOAuthDraft.current = true;
try {
restoreEditorChildren(editor, draft.children);
onSelectedSearchScopesChange(draft.selectedSearchScopes);
onDisabledMcpServerIdsChange(draft.disabledMcpServerIds);
} catch (error) {
resetEditor(editor);
editor.onChange();
console.error('Failed to restore MCP OAuth draft:', error);
}
}, [editor, onDisabledMcpServerIdsChange, onSelectedSearchScopesChange]);
const onToggle = (serverId: string, checked: boolean) => {
if (checked) {
onDisabledMcpServerIdsChange(disabledMcpServerIds.filter((id) => id !== serverId));
} else {
onDisabledMcpServerIdsChange([...disabledMcpServerIds, serverId]);
}
};
const handleConnect = async (serverId: string) => {
setConnectingServerId(serverId);
const returnTo = createMcpOAuthDraftPath(window.location.pathname, window.location.search) ?? '/chat';
saveMcpOAuthDraft({
returnTo,
children: editor.children,
selectedSearchScopes,
disabledMcpServerIds,
});
try {
const result = await connectMcpToAsk({
serverId,
returnTo,
});
if (!isMountedRef.current) {
return;
}
if (isServiceError(result)) {
clearMcpOAuthDraft();
toast({
description: `Failed to connect connector. ${result.message}`,
variant: "destructive",
});
setConnectingServerId(null);
return;
}
if (result.authorizationUrl) {
window.location.href = result.authorizationUrl;
return;
}
clearMcpOAuthDraft();
toast({ description: 'Connector is already connected.' });
await queryClient.invalidateQueries({ queryKey: mcpQueryKeys.serversWithStatus });
if (!isMountedRef.current) {
return;
}
setConnectingServerId(null);
} catch {
if (!isMountedRef.current) {
return;
}
clearMcpOAuthDraft();
toast({
description: "Failed to connect connector.",
variant: "destructive",
});
setConnectingServerId(null);
return;
}
};
const { connectedServers, connectableServers } = splitMcpServersForChatMenu(servers);
const hasServers = connectedServers.length > 0 || connectableServers.length > 0;
const isAuthenticationError = error instanceof McpServersLoadError && error.serviceError.errorCode === ErrorCode.NOT_AUTHENTICATED;
const shouldShowLoginConnectorItem = !isAuthenticated || isAuthenticationError;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
className="w-6 h-6 text-muted-foreground hover:text-primary"
>
<PlusIcon className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent side="bottom" align="start" className="w-52" onCloseAutoFocus={(e) => e.preventDefault()}>
<DropdownMenuSub>
<DropdownMenuSubTrigger className="gap-2">
<CableIcon className="w-4 h-4 text-muted-foreground" />
Connectors
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="w-56">
{!shouldShowLoginConnectorItem && (
<>
{isError && !hasServers ? (
<DropdownMenuItem
onSelect={(e) => {
e.preventDefault();
refetch();
}}
className="gap-2 text-destructive"
>
<RefreshCwIcon className="w-4 h-4" />
Failed to load. Retry?
</DropdownMenuItem>
) : isLoading ? (
<DropdownMenuItem disabled>
Loading connectors...
</DropdownMenuItem>
) : !hasServers ? (
<DropdownMenuItem disabled>
No connectors available
</DropdownMenuItem>
) : (
<>
{connectedServers.map((server) => {
const isEnabled = !server.isAuthExpired && !disabledMcpServerIds.includes(server.id);
return (
<DropdownMenuItem
key={server.id}
onSelect={(e) => e.preventDefault()}
disabled={server.isAuthExpired}
className="flex items-center justify-between gap-2"
>
<div className="flex items-center gap-2 min-w-0">
{server.isAuthExpired ? (
<AlertTriangleIcon className="w-4 h-4 shrink-0 text-yellow-500" />
) : (
<McpFavicon faviconUrl={server.faviconUrl} className="w-4 h-4 rounded-sm" />
)}
<span className="truncate text-sm">{server.name}</span>
</div>
<Switch
checked={isEnabled}
onCheckedChange={(checked) => onToggle(server.id, checked)}
disabled={server.isAuthExpired}
className="scale-75"
/>
</DropdownMenuItem>
);
})}
{connectedServers.length > 0 && connectableServers.length > 0 && <DropdownMenuSeparator />}
{connectableServers.map((server) => (
<DropdownMenuItem
key={server.id}
onSelect={(e) => {
e.preventDefault();
void handleConnect(server.id);
}}
disabled={connectingServerId !== null}
className="group flex cursor-pointer items-center justify-between gap-2"
>
<div className="flex items-center gap-2 min-w-0">
<McpFavicon faviconUrl={server.faviconUrl} className="w-4 h-4 rounded-sm" />
<span className="truncate text-sm">{server.name}</span>
</div>
{connectingServerId === server.id ? (
<Loader2Icon className="w-4 h-4 shrink-0 animate-spin text-muted-foreground" />
) : (
<PlusCircleIcon className="w-4 h-4 shrink-0 text-green-600/80 transition-colors group-focus:text-green-500 group-hover:text-green-500 dark:text-green-400/80 dark:group-focus:text-green-400 dark:group-hover:text-green-400" />
)}
</DropdownMenuItem>
))}
</>
)}
<DropdownMenuSeparator />
</>
)}
{shouldShowLoginConnectorItem ? (
<DropdownMenuItem asChild className="gap-2 text-link focus:text-link">
<Link href={loginHref}>
<LogInIcon className="w-4 h-4" />
Log in to use connectors
</Link>
</DropdownMenuItem>
) : (
<>
<DropdownMenuItem
className="gap-2 text-muted-foreground"
onSelect={() => router.push(`/settings/accountAskAgent`)}
>
<CableIcon className="w-4 h-4" />
My connectors
</DropdownMenuItem>
{isOwner && (
<DropdownMenuItem
className="gap-2 text-muted-foreground"
onSelect={() => router.push(`/settings/workspaceAskAgent`)}
>
<SettingsIcon className="w-4 h-4" />
Workspace connectors
</DropdownMenuItem>
)}
</>
)}
</DropdownMenuSubContent>
</DropdownMenuSub>
</DropdownMenuContent>
</DropdownMenu>
);
};