Elffuss BraidHub

kikocis/continue public

9875eaa07e45 · 10.4 KiBRawPermalink
1import { Box, Text, useInput } from "ink";
2import React, { useState } from "react";
3import { quote } from "shell-quote";
4
5import { useServices } from "../hooks/useService.js";
6import { MCPServiceState, SERVICE_NAMES } from "../services/types.js";
7import { logger } from "../util/logger.js";
8
9// Utility function to get status icon and color based on server connection
10const getServerStatusDisplay = (conn: any) => {
11 let icon = "⚪️"; // note, white circle causes extra blank line bug
12 let color: "green" | "yellow" | "red" | "white" | "dim" = "white";
13 let statusText = conn.status;
14
15 if (conn.status === "connecting") {
16 icon = "🟡";
17 color = "yellow";
18 } else if (conn.status === "error") {
19 icon = "🔴";
20 color = "red";
21 } else if (conn.status === "connected") {
22 if (conn.warnings && conn.warnings.length > 0) {
23 icon = "🟡";
24 color = "yellow";
25 statusText = "connected (with warnings)";
26 } else {
27 icon = "🟢";
28 color = "green";
29 }
30 }
31
32 return { icon, color, statusText };
33};
34
35interface MCPSelectorProps {
36 onCancel: () => void;
37}
38
39type MCPMenuState = "main" | "server-detail";
40
41interface MCPMenuItem {
42 label: string;
43 value: string;
44}
45
46export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
47 const [menuState, setMenuState] = useState<MCPMenuState>("main");
48 const [selectedServer, setSelectedServer] = useState<string | null>(null);
49 const [selectedIndex, setSelectedIndex] = useState(0);
50 const [isLoading, setIsLoading] = useState(false);
51 const [message, setMessage] = useState<string | null>(null);
52
53 const { services } = useServices<{ mcp: MCPServiceState }>([
54 SERVICE_NAMES.MCP,
55 ]);
56 const connections = services.mcp?.connections ?? [];
57 const mcpService = services.mcp?.mcpService;
58
59 const backItem = { label: "Back", value: "back" };
60
61 const handleBack = () => {
62 if (menuState === "server-detail") {
63 setSelectedServer(null);
64 setMenuState("main");
65 setSelectedIndex(0);
66 } else {
67 onCancel();
68 }
69 setMessage(null);
70 };
71
72 // Main menu items (includes servers)
73 const getMainMenuItems = (): MCPMenuItem[] => {
74 const options: MCPMenuItem[] = [];
75
76 // Add individual servers first
77 if (connections.length > 0) {
78 connections.forEach((conn) => {
79 const { icon } = getServerStatusDisplay(conn);
80
81 let serverLabel = `${icon} ${conn.config.name}`;
82
83 // Add tools and prompts count if server is connected
84 if (conn.status === "connected") {
85 const toolsCount = conn.tools.length;
86 const promptsCount = conn.prompts.length;
87
88 const counts = [];
89 if (toolsCount > 0) {
90 counts.push(`🔧${toolsCount}`);
91 }
92 if (promptsCount > 0) {
93 counts.push(`📝${promptsCount}`);
94 }
95
96 if (counts.length > 0) {
97 serverLabel += ` (${counts.join(" ")})`;
98 }
99 }
100
101 options.push({
102 label: serverLabel,
103 value: `server:${conn.config.name}`,
104 });
105 });
106
107 // Add bulk actions
108 options.push(
109 { label: "🔄 Restart all servers", value: "restart-all" },
110 { label: "⏹️ Stop all servers", value: "stop-all" },
111 );
112 }
113 return options;
114 };
115
116 // Server detail items
117 const getServerDetailItems = (): MCPMenuItem[] => {
118 if (!selectedServer) return [];
119
120 const serverInfo = connections.find(
121 (conn) => conn.config.name === selectedServer,
122 );
123 if (!serverInfo) return [];
124
125 const items: MCPMenuItem[] = [
126 { label: "🔄 Restart server", value: "restart" },
127 ];
128
129 // Only show stop server if it's connected
130 if (serverInfo.status === "connected") {
131 items.push({ label: "⏹️ Stop server", value: "stop" });
132 }
133
134 return items;
135 };
136 const getServerInfoDisplay = () => {
137 if (menuState !== "server-detail" || !selectedServer) return null;
138
139 const serverInfo = connections.find(
140 (conn) => conn.config.name === selectedServer,
141 );
142 if (!serverInfo) return null;
143
144 return (
145 <Box flexDirection="column">
146 {/* Add error if server has error status */}
147 {serverInfo.status === "error" && serverInfo.error && (
148 <Box flexDirection="column" marginBottom={1}>
149 <Text color="red" bold>
150 🚫 Error:
151 </Text>
152 <Text color="red">{serverInfo.error}</Text>
153 </Box>
154 )}
155
156 {/* Add warnings if any */}
157 {serverInfo.warnings.length > 0 && (
158 <Box flexDirection="column" marginBottom={1}>
159 <Text color="yellow" bold>
160 ⚠️ Warnings:
161 </Text>
162 {serverInfo.warnings.map((warning, index) => (
163 <Text key={index} color="yellow">
164 • {warning}
165 </Text>
166 ))}
167 </Box>
168 )}
169
170 {/* Add prompts if any */}
171 {serverInfo.prompts.length > 0 && (
172 <Box flexDirection="column" marginBottom={1}>
173 <Text color="cyan">📝 Prompts: {serverInfo.prompts.length}</Text>
174 {serverInfo.prompts.map((prompt, index) => (
175 <Text key={index} color="dim">
176 • {prompt.name}
177 </Text>
178 ))}
179 </Box>
180 )}
181
182 {/* Add tools if any */}
183 {serverInfo.tools.length > 0 && (
184 <Box flexDirection="column" marginBottom={1}>
185 <Text color="cyan">🔧 Tools: {serverInfo.tools.length}</Text>
186 {serverInfo.tools.map((tool, index) => (
187 <Text key={index} color="dim">
188 • {tool.name}
189 </Text>
190 ))}
191 </Box>
192 )}
193 </Box>
194 );
195 };
196
197 let items: MCPMenuItem[] = [];
198
199 switch (menuState) {
200 case "main":
201 items = getMainMenuItems();
202 break;
203 case "server-detail":
204 items = getServerDetailItems();
205 break;
206 }
207
208 items = [...items, backItem];
209
210 const maxIndex = Math.max(0, items.length - 1);
211
212 useInput(async (input, key) => {
213 if (isLoading) return;
214
215 if (key.escape) {
216 handleBack();
217 return;
218 }
219
220 if (key.upArrow) {
221 setSelectedIndex(selectedIndex <= 0 ? maxIndex : selectedIndex - 1);
222 return;
223 }
224
225 if (key.downArrow) {
226 setSelectedIndex((prev) => (prev >= maxIndex ? 0 : prev + 1));
227 return;
228 }
229
230 if (key.return) {
231 const selectedItem = items[selectedIndex];
232 if (!selectedItem) return;
233
234 setIsLoading(true);
235 setMessage(null);
236
237 try {
238 switch (menuState) {
239 case "main":
240 await handleMainMenuSelect(selectedItem.value);
241 break;
242 case "server-detail":
243 await handleServerAction(selectedItem.value);
244 break;
245 }
246 } catch (error: any) {
247 setMessage(`Error: ${error.message}`);
248 } finally {
249 setIsLoading(false);
250 }
251 }
252 });
253
254 const handleMainMenuSelect = async (value: string) => {
255 if (!mcpService) return;
256
257 if (value.startsWith("server:")) {
258 // Handle server selection
259 const serverName = value.replace("server:", "");
260 setSelectedServer(serverName);
261 setMenuState("server-detail");
262 setSelectedIndex(0);
263 return;
264 }
265
266 switch (value) {
267 case "restart-all":
268 await mcpService.restartAllServers();
269 setMessage("All servers restarted");
270 break;
271 case "stop-all":
272 await mcpService.shutdownConnections();
273 setMessage("All servers stopped");
274 break;
275 case "back":
276 onCancel();
277 return;
278 }
279 };
280
281 const handleServerAction = async (action: string) => {
282 if (!mcpService || !selectedServer) return;
283 try {
284 switch (action) {
285 case "restart":
286 await mcpService.restartServer(selectedServer);
287 setMessage(`Server "${selectedServer}" restarted`);
288 break;
289 case "stop":
290 await mcpService.stopServer(selectedServer);
291 setMessage(`Server "${selectedServer}" stopped`);
292 break;
293 case "back":
294 handleBack();
295 return;
296 }
297 } catch {
298 logger.error("Error handling MCP action");
299 }
300 };
301
302 const renderHeader = () => {
303 return (
304 <Box flexDirection="column" marginBottom={1}>
305 <Text bold color="cyan">
306 {menuState === "server-detail" && selectedServer
307 ? `Server: ${selectedServer}`
308 : "MCP Servers"}
309 </Text>
310 {connections.length === 0 && (
311 <Text color="gray">No servers configured</Text>
312 )}
313 {menuState === "server-detail" &&
314 selectedServer &&
315 (() => {
316 const serverInfo = connections.find(
317 (conn) => conn.config.name === selectedServer,
318 );
319 if (!serverInfo) return null;
320
321 const { color: statusColor, statusText } =
322 getServerStatusDisplay(serverInfo);
323 const { command, args } = serverInfo.config;
324 let cmd = command ? quote([command, ...(args ?? [])]) : "";
325 cmd = cmd.replace(/\$\{\{.*\}\}/, "(secret)");
326
327 return (
328 <Text color="dim">
329 Status: <Text color={statusColor}>{statusText}</Text>
330 {cmd && ` • Command: ${cmd}`}
331 </Text>
332 );
333 })()}
334 </Box>
335 );
336 };
337
338 return (
339 <Box
340 flexDirection="column"
341 borderStyle="round"
342 borderColor="cyan"
343 padding={1}
344 minHeight={10}
345 >
346 {renderHeader()}
347
348 {message && (
349 <Box marginBottom={1}>
350 <Text color={message.startsWith("Error:") ? "red" : "green"}>
351 {message}
352 </Text>
353 </Box>
354 )}
355
356 {menuState === "server-detail" && getServerInfoDisplay()}
357
358 {isLoading ? (
359 <Box>
360 <Text color="yellow">Working...</Text>
361 </Box>
362 ) : (
363 <Box flexDirection="column">
364 {items.map((item, index) => {
365 const isSelected = index === selectedIndex;
366
367 return (
368 <Text
369 key={`${item.value}-${index}`}
370 color={isSelected ? "blue" : "white"}
371 bold={isSelected}
372 inverse={isSelected}
373 >
374 {isSelected ? "> " : " "}
375 {item.label}
376 </Text>
377 );
378 })}
379 </Box>
380 )}
381
382 <Box marginTop={1}>
383 <Text color="dim">
384 Use ↑/↓ to navigate, Enter to select, Esc to go back
385 </Text>
386 </Box>
387 </Box>
388 );
389};