forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathManagePlugins.tsx
More file actions
2215 lines (2089 loc) · 314 KB
/
Copy pathManagePlugins.tsx
File metadata and controls
2215 lines (2089 loc) · 314 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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import figures from 'figures';
import type { Dirent } from 'fs';
import * as fs from 'fs/promises';
import * as path from 'path';
import * as React from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ConfigurableShortcutHint } from '../../components/ConfigurableShortcutHint.js';
import { Byline } from '../../components/design-system/Byline.js';
import { MCPRemoteServerMenu } from '../../components/mcp/MCPRemoteServerMenu.js';
import { MCPStdioServerMenu } from '../../components/mcp/MCPStdioServerMenu.js';
import { MCPToolDetailView } from '../../components/mcp/MCPToolDetailView.js';
import { MCPToolListView } from '../../components/mcp/MCPToolListView.js';
import type { ClaudeAIServerInfo, HTTPServerInfo, SSEServerInfo, StdioServerInfo } from '../../components/mcp/types.js';
import { SearchBox } from '../../components/SearchBox.js';
import { useSearchInput } from '../../hooks/useSearchInput.js';
import { useTerminalSize } from '../../hooks/useTerminalSize.js';
// eslint-disable-next-line custom-rules/prefer-use-keybindings -- useInput needed for raw search mode text input
import { Box, Text, useInput, useTerminalFocus } from '../../ink.js';
import { useKeybinding, useKeybindings } from '../../keybindings/useKeybinding.js';
import { getBuiltinPluginDefinition } from '../../plugins/builtinPlugins.js';
import { useMcpToggleEnabled } from '../../services/mcp/MCPConnectionManager.js';
import type { MCPServerConnection, McpClaudeAIProxyServerConfig, McpHTTPServerConfig, McpSSEServerConfig, McpStdioServerConfig } from '../../services/mcp/types.js';
import { filterToolsByServer } from '../../services/mcp/utils.js';
import { disablePluginOp, enablePluginOp, getPluginInstallationFromV2, isInstallableScope, isPluginEnabledAtProjectScope, uninstallPluginOp, updatePluginOp } from '../../services/plugins/pluginOperations.js';
import { useAppState } from '../../state/AppState.js';
import type { Tool } from '../../Tool.js';
import type { LoadedPlugin, PluginError } from '../../types/plugin.js';
import { count } from '../../utils/array.js';
import { openBrowser } from '../../utils/browser.js';
import { logForDebugging } from '../../utils/debug.js';
import { errorMessage, toError } from '../../utils/errors.js';
import { logError } from '../../utils/log.js';
import { clearAllCaches } from '../../utils/plugins/cacheUtils.js';
import { loadInstalledPluginsV2 } from '../../utils/plugins/installedPluginsManager.js';
import { getMarketplace } from '../../utils/plugins/marketplaceManager.js';
import { isMcpbSource, loadMcpbFile, type McpbNeedsConfigResult, type UserConfigValues } from '../../utils/plugins/mcpbHandler.js';
import { getPluginDataDirSize, pluginDataDirPath } from '../../utils/plugins/pluginDirectories.js';
import { getFlaggedPlugins, markFlaggedPluginsSeen, removeFlaggedPlugin } from '../../utils/plugins/pluginFlagging.js';
import { type PersistablePluginScope, parsePluginIdentifier } from '../../utils/plugins/pluginIdentifier.js';
import { loadAllPlugins } from '../../utils/plugins/pluginLoader.js';
import { loadPluginOptions, type PluginOptionSchema, savePluginOptions } from '../../utils/plugins/pluginOptionsStorage.js';
import { isPluginBlockedByPolicy } from '../../utils/plugins/pluginPolicy.js';
import { getPluginEditableScopes } from '../../utils/plugins/pluginStartupCheck.js';
import { getSettings_DEPRECATED, getSettingsForSource, updateSettingsForSource } from '../../utils/settings/settings.js';
import { jsonParse } from '../../utils/slowOperations.js';
import { plural } from '../../utils/stringUtils.js';
import { formatErrorMessage, getErrorGuidance } from './PluginErrors.js';
import { PluginOptionsDialog } from './PluginOptionsDialog.js';
import { PluginOptionsFlow } from './PluginOptionsFlow.js';
import type { ViewState as ParentViewState } from './types.js';
import { UnifiedInstalledCell } from './UnifiedInstalledCell.js';
import type { UnifiedInstalledItem } from './unifiedTypes.js';
import { usePagination } from './usePagination.js';
type Props = {
setViewState: (state: ParentViewState) => void;
setResult: (result: string | null) => void;
onManageComplete?: () => void | Promise<void>;
onSearchModeChange?: (isActive: boolean) => void;
targetPlugin?: string;
targetMarketplace?: string;
action?: 'enable' | 'disable' | 'uninstall';
};
type FlaggedPluginInfo = {
id: string;
name: string;
marketplace: string;
reason: string;
text: string;
flaggedAt: string;
};
type FailedPluginInfo = {
id: string;
name: string;
marketplace: string;
errors: PluginError[];
scope: PersistablePluginScope;
};
type ViewState = 'plugin-list' | 'plugin-details' | 'configuring' | {
type: 'plugin-options';
} | {
type: 'configuring-options';
schema: PluginOptionSchema;
} | 'confirm-project-uninstall' | {
type: 'confirm-data-cleanup';
size: {
bytes: number;
human: string;
};
} | {
type: 'flagged-detail';
plugin: FlaggedPluginInfo;
} | {
type: 'failed-plugin-details';
plugin: FailedPluginInfo;
} | {
type: 'mcp-detail';
client: MCPServerConnection;
} | {
type: 'mcp-tools';
client: MCPServerConnection;
} | {
type: 'mcp-tool-detail';
client: MCPServerConnection;
tool: Tool;
};
type MarketplaceInfo = {
name: string;
installedPlugins: LoadedPlugin[];
enabledCount?: number;
disabledCount?: number;
};
type PluginState = {
plugin: LoadedPlugin;
marketplace: string;
scope?: 'user' | 'project' | 'local' | 'managed' | 'builtin';
pendingEnable?: boolean; // Toggle enable/disable
pendingUpdate?: boolean; // Marked for update
};
/**
* Get list of base file names (without .md extension) from a directory
* @param dirPath The directory path to list files from
* @returns Array of base file names without .md extension
* @example
* // Given directory contains: agent-sdk-verifier-py.md, agent-sdk-verifier-ts.md, README.txt
* await getBaseFileNames('/path/to/agents')
* // Returns: ['agent-sdk-verifier-py', 'agent-sdk-verifier-ts']
*/
async function getBaseFileNames(dirPath: string): Promise<string[]> {
try {
const entries = await fs.readdir(dirPath, {
withFileTypes: true
});
return entries.filter((entry: Dirent) => entry.isFile() && entry.name.endsWith('.md')).map((entry: Dirent) => {
// Remove .md extension specifically
const baseName = path.basename(entry.name, '.md');
return baseName;
});
} catch (error) {
const errorMsg = errorMessage(error);
logForDebugging(`Failed to read plugin components from ${dirPath}: ${errorMsg}`, {
level: 'error'
});
logError(toError(error));
// Return empty array to allow graceful degradation - plugin details can still be shown
return [];
}
}
/**
* Get list of skill directory names from a skills directory
* Skills are directories containing a SKILL.md file
* @param dirPath The skills directory path to scan
* @returns Array of skill directory names that contain SKILL.md
* @example
* // Given directory contains: my-skill/SKILL.md, another-skill/SKILL.md, README.txt
* await getSkillDirNames('/path/to/skills')
* // Returns: ['my-skill', 'another-skill']
*/
async function getSkillDirNames(dirPath: string): Promise<string[]> {
try {
const entries = await fs.readdir(dirPath, {
withFileTypes: true
});
const skillNames: string[] = [];
for (const entry of entries) {
// Check if it's a directory or symlink (symlinks may point to skill directories)
if (entry.isDirectory() || entry.isSymbolicLink()) {
// Check if this directory contains a SKILL.md file
const skillFilePath = path.join(dirPath, entry.name, 'SKILL.md');
try {
const st = await fs.stat(skillFilePath);
if (st.isFile()) {
skillNames.push(entry.name);
}
} catch {
// No SKILL.md file in this directory, skip it
}
}
}
return skillNames;
} catch (error) {
const errorMsg = errorMessage(error);
logForDebugging(`Failed to read skill directories from ${dirPath}: ${errorMsg}`, {
level: 'error'
});
logError(toError(error));
// Return empty array to allow graceful degradation - plugin details can still be shown
return [];
}
}
// Component to display installed plugin components
function PluginComponentsDisplay({
plugin,
marketplace
}: {
plugin: LoadedPlugin;
marketplace: string;
}): React.ReactNode {
const [components, setComponents] = useState<{
commands?: string | string[] | Record<string, unknown> | null;
agents?: string | string[] | Record<string, unknown> | null;
skills?: string | string[] | Record<string, unknown> | null;
hooks?: unknown;
mcpServers?: unknown;
} | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
async function loadComponents() {
try {
// Built-in plugins don't have a marketplace entry — read from the
// registered definition directly.
if (marketplace === 'builtin') {
const builtinDef = getBuiltinPluginDefinition(plugin.name);
if (builtinDef) {
const skillNames = builtinDef.skills?.map(s => s.name) ?? [];
const hookEvents = builtinDef.hooks ? Object.keys(builtinDef.hooks) : [];
const mcpServerNames = builtinDef.mcpServers ? Object.keys(builtinDef.mcpServers) : [];
setComponents({
commands: null,
agents: null,
skills: skillNames.length > 0 ? skillNames : null,
hooks: hookEvents.length > 0 ? hookEvents : null,
mcpServers: mcpServerNames.length > 0 ? mcpServerNames : null
});
} else {
setError(`Built-in plugin ${plugin.name} not found`);
}
setLoading(false);
return;
}
const marketplaceData = await getMarketplace(marketplace);
// Find the plugin entry in the array
const pluginEntry = marketplaceData.plugins.find(p => p.name === plugin.name);
if (pluginEntry) {
// Combine commands from both sources
const commandPathList = [];
if (plugin.commandsPath) {
commandPathList.push(plugin.commandsPath);
}
if (plugin.commandsPaths) {
commandPathList.push(...plugin.commandsPaths);
}
// Get base file names from all command paths
const commandList: string[] = [];
for (const commandPath of commandPathList) {
if (typeof commandPath === 'string') {
// commandPath is already a full path
const baseNames = await getBaseFileNames(commandPath);
commandList.push(...baseNames);
}
}
// Combine agents from both sources
const agentPathList = [];
if (plugin.agentsPath) {
agentPathList.push(plugin.agentsPath);
}
if (plugin.agentsPaths) {
agentPathList.push(...plugin.agentsPaths);
}
// Get base file names from all agent paths
const agentList: string[] = [];
for (const agentPath of agentPathList) {
if (typeof agentPath === 'string') {
// agentPath is already a full path
const baseNames_0 = await getBaseFileNames(agentPath);
agentList.push(...baseNames_0);
}
}
// Combine skills from both sources
const skillPathList = [];
if (plugin.skillsPath) {
skillPathList.push(plugin.skillsPath);
}
if (plugin.skillsPaths) {
skillPathList.push(...plugin.skillsPaths);
}
// Get skill directory names from all skill paths
// Skills are directories containing SKILL.md files
const skillList: string[] = [];
for (const skillPath of skillPathList) {
if (typeof skillPath === 'string') {
// skillPath is already a full path to a skills directory
const skillDirNames = await getSkillDirNames(skillPath);
skillList.push(...skillDirNames);
}
}
// Combine hooks from both sources
const hooksList = [];
if (plugin.hooksConfig) {
hooksList.push(Object.keys(plugin.hooksConfig));
}
if (pluginEntry.hooks) {
hooksList.push(pluginEntry.hooks);
}
// Combine MCP servers from both sources
const mcpServersList = [];
if (plugin.mcpServers) {
mcpServersList.push(Object.keys(plugin.mcpServers));
}
if (pluginEntry.mcpServers) {
mcpServersList.push(pluginEntry.mcpServers);
}
setComponents({
commands: commandList.length > 0 ? commandList : null,
agents: agentList.length > 0 ? agentList : null,
skills: skillList.length > 0 ? skillList : null,
hooks: hooksList.length > 0 ? hooksList : null,
mcpServers: mcpServersList.length > 0 ? mcpServersList : null
});
} else {
setError(`Plugin ${plugin.name} not found in marketplace`);
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load components');
} finally {
setLoading(false);
}
}
void loadComponents();
}, [plugin.name, plugin.commandsPath, plugin.commandsPaths, plugin.agentsPath, plugin.agentsPaths, plugin.skillsPath, plugin.skillsPaths, plugin.hooksConfig, plugin.mcpServers, marketplace]);
if (loading) {
return null; // Don't show loading state for cleaner UI
}
if (error) {
return <Box flexDirection="column" marginBottom={1}>
<Text bold>Components:</Text>
<Text dimColor>Error: {error}</Text>
</Box>;
}
if (!components) {
return null; // No components info available
}
const hasComponents = components.commands || components.agents || components.skills || components.hooks || components.mcpServers;
if (!hasComponents) {
return null; // No components defined
}
return <Box flexDirection="column" marginBottom={1}>
<Text bold>Installed components:</Text>
{components.commands ? <Text dimColor>
• Commands:{' '}
{typeof components.commands === 'string' ? components.commands : Array.isArray(components.commands) ? components.commands.join(', ') : Object.keys(components.commands).join(', ')}
</Text> : null}
{components.agents ? <Text dimColor>
• Agents:{' '}
{typeof components.agents === 'string' ? components.agents : Array.isArray(components.agents) ? components.agents.join(', ') : Object.keys(components.agents).join(', ')}
</Text> : null}
{components.skills ? <Text dimColor>
• Skills:{' '}
{typeof components.skills === 'string' ? components.skills : Array.isArray(components.skills) ? components.skills.join(', ') : Object.keys(components.skills).join(', ')}
</Text> : null}
{components.hooks ? <Text dimColor>
• Hooks:{' '}
{typeof components.hooks === 'string' ? components.hooks : Array.isArray(components.hooks) ? components.hooks.map(String).join(', ') : typeof components.hooks === 'object' && components.hooks !== null ? Object.keys(components.hooks).join(', ') : String(components.hooks)}
</Text> : null}
{components.mcpServers ? <Text dimColor>
• MCP Servers:{' '}
{typeof components.mcpServers === 'string' ? components.mcpServers : Array.isArray(components.mcpServers) ? components.mcpServers.map(String).join(', ') : typeof components.mcpServers === 'object' && components.mcpServers !== null ? Object.keys(components.mcpServers).join(', ') : String(components.mcpServers)}
</Text> : null}
</Box>;
}
/**
* Check if a plugin is from a local source and cannot be remotely updated
* @returns Error message if local, null if remote/updatable
*/
async function checkIfLocalPlugin(pluginName: string, marketplaceName: string): Promise<string | null> {
const marketplace = await getMarketplace(marketplaceName);
const entry = marketplace?.plugins.find(p => p.name === pluginName);
if (entry && typeof entry.source === 'string') {
return `Local plugins cannot be updated remotely. To update, modify the source at: ${entry.source}`;
}
return null;
}
/**
* Filter out plugins that are force-disabled by org policy (policySettings).
* These are blocked by the organization and cannot be re-enabled by the user.
* Checks policySettings directly rather than installation scope, since managed
* settings don't create installation records with scope 'managed'.
*/
export function filterManagedDisabledPlugins(plugins: LoadedPlugin[]): LoadedPlugin[] {
return plugins.filter(plugin => {
const marketplace = plugin.source.split('@')[1] || 'local';
return !isPluginBlockedByPolicy(`${plugin.name}@${marketplace}`);
});
}
export function ManagePlugins({
setViewState: setParentViewState,
setResult,
onManageComplete,
onSearchModeChange,
targetPlugin,
targetMarketplace,
action
}: Props): React.ReactNode {
// App state for MCP access
const mcpClients = useAppState(s => s.mcp.clients);
const mcpTools = useAppState(s_0 => s_0.mcp.tools);
const pluginErrors = useAppState(s_1 => s_1.plugins.errors);
const flaggedPlugins = getFlaggedPlugins();
// Search state
const [isSearchMode, setIsSearchModeRaw] = useState(false);
const setIsSearchMode = useCallback((active: boolean) => {
setIsSearchModeRaw(active);
onSearchModeChange?.(active);
}, [onSearchModeChange]);
const isTerminalFocused = useTerminalFocus();
const {
columns: terminalWidth
} = useTerminalSize();
// View state
const [viewState, setViewState] = useState<ViewState>('plugin-list');
const {
query: searchQuery,
setQuery: setSearchQuery,
cursorOffset: searchCursorOffset
} = useSearchInput({
isActive: viewState === 'plugin-list' && isSearchMode,
onExit: () => {
setIsSearchMode(false);
}
});
const [selectedPlugin, setSelectedPlugin] = useState<PluginState | null>(null);
// Data state
const [marketplaces, setMarketplaces] = useState<MarketplaceInfo[]>([]);
const [pluginStates, setPluginStates] = useState<PluginState[]>([]);
const [loading, setLoading] = useState(true);
const [pendingToggles, setPendingToggles] = useState<Map<string, 'will-enable' | 'will-disable'>>(new Map());
// Guard to prevent auto-navigation from re-triggering after the user
// navigates away (targetPlugin is never cleared by the parent).
const hasAutoNavigated = useRef(false);
// Auto-action (enable/disable/uninstall) to fire after auto-navigation lands.
// Ref, not state: it's consumed by a one-shot effect that already re-runs on
// viewState/selectedPlugin, so a render-triggering state var would be redundant.
const pendingAutoActionRef = useRef<'enable' | 'disable' | 'uninstall' | undefined>(undefined);
// MCP toggle hook
const toggleMcpServer = useMcpToggleEnabled();
// Handle escape to go back - viewState-dependent navigation
const handleBack = React.useCallback(() => {
if (viewState === 'plugin-details') {
setViewState('plugin-list');
setSelectedPlugin(null);
setProcessError(null);
} else if (typeof viewState === 'object' && viewState.type === 'failed-plugin-details') {
setViewState('plugin-list');
setProcessError(null);
} else if (viewState === 'configuring') {
setViewState('plugin-details');
setConfigNeeded(null);
} else if (typeof viewState === 'object' && (viewState.type === 'plugin-options' || viewState.type === 'configuring-options')) {
// Cancel mid-sequence — plugin is already enabled, just bail to list.
// User can configure later via the Configure options menu if they want.
setViewState('plugin-list');
setSelectedPlugin(null);
setResult('Plugin enabled. Configuration skipped — run /reload-plugins to apply.');
if (onManageComplete) {
void onManageComplete();
}
} else if (typeof viewState === 'object' && viewState.type === 'flagged-detail') {
setViewState('plugin-list');
setProcessError(null);
} else if (typeof viewState === 'object' && viewState.type === 'mcp-detail') {
setViewState('plugin-list');
setProcessError(null);
} else if (typeof viewState === 'object' && viewState.type === 'mcp-tools') {
setViewState({
type: 'mcp-detail',
client: viewState.client
});
} else if (typeof viewState === 'object' && viewState.type === 'mcp-tool-detail') {
setViewState({
type: 'mcp-tools',
client: viewState.client
});
} else {
if (pendingToggles.size > 0) {
setResult('Run /reload-plugins to apply plugin changes.');
return;
}
setParentViewState({
type: 'menu'
});
}
}, [viewState, setParentViewState, pendingToggles, setResult]);
// Escape when not in search mode - go back.
// Excludes confirm-project-uninstall (has its own confirm:no handler in
// Confirmation context — letting this fire would create competing handlers)
// and confirm-data-cleanup (uses raw useInput where n and escape are
// DIFFERENT actions: keep-data vs cancel).
useKeybinding('confirm:no', handleBack, {
context: 'Confirmation',
isActive: (viewState !== 'plugin-list' || !isSearchMode) && viewState !== 'confirm-project-uninstall' && !(typeof viewState === 'object' && viewState.type === 'confirm-data-cleanup')
});
// Helper to get MCP status
const getMcpStatus = (client: MCPServerConnection): 'connected' | 'disabled' | 'pending' | 'needs-auth' | 'failed' => {
if (client.type === 'connected') return 'connected';
if (client.type === 'disabled') return 'disabled';
if (client.type === 'pending') return 'pending';
if (client.type === 'needs-auth') return 'needs-auth';
return 'failed';
};
// Derive unified items from plugins and MCP servers
const unifiedItems = useMemo(() => {
const mergedSettings = getSettings_DEPRECATED();
// Build map of plugin name -> child MCPs
// Plugin MCPs have names like "plugin:pluginName:serverName"
const pluginMcpMap = new Map<string, Array<{
displayName: string;
client: MCPServerConnection;
}>>();
for (const client_0 of mcpClients) {
if (client_0.name.startsWith('plugin:')) {
const parts = client_0.name.split(':');
if (parts.length >= 3) {
const pluginName = parts[1]!;
const serverName = parts.slice(2).join(':');
const existing = pluginMcpMap.get(pluginName) || [];
existing.push({
displayName: serverName,
client: client_0
});
pluginMcpMap.set(pluginName, existing);
}
}
}
// Build plugin items (unsorted for now)
type PluginWithChildren = {
item: UnifiedInstalledItem & {
type: 'plugin';
};
originalScope: 'user' | 'project' | 'local' | 'managed' | 'builtin';
childMcps: Array<{
displayName: string;
client: MCPServerConnection;
}>;
};
const pluginsWithChildren: PluginWithChildren[] = [];
for (const state of pluginStates) {
const pluginId = `${state.plugin.name}@${state.marketplace}`;
const isEnabled = mergedSettings?.enabledPlugins?.[pluginId] !== false;
const errors = pluginErrors.filter(e => 'plugin' in e && e.plugin === state.plugin.name || e.source === pluginId || e.source.startsWith(`${state.plugin.name}@`));
// Built-in plugins use 'builtin' scope; others look up from V2 data.
const originalScope = state.plugin.isBuiltin ? 'builtin' : state.scope || 'user';
pluginsWithChildren.push({
item: {
type: 'plugin',
id: pluginId,
name: state.plugin.name,
description: state.plugin.manifest.description,
marketplace: state.marketplace,
scope: originalScope,
isEnabled,
errorCount: errors.length,
errors,
plugin: state.plugin,
pendingEnable: state.pendingEnable,
pendingUpdate: state.pendingUpdate,
pendingToggle: pendingToggles.get(pluginId)
},
originalScope,
childMcps: pluginMcpMap.get(state.plugin.name) || []
});
}
// Find orphan errors (errors for plugins that failed to load entirely)
const matchedPluginIds = new Set(pluginsWithChildren.map(({
item
}) => item.id));
const matchedPluginNames = new Set(pluginsWithChildren.map(({
item: item_0
}) => item_0.name));
const orphanErrorsBySource = new Map<string, typeof pluginErrors>();
for (const error of pluginErrors) {
if (matchedPluginIds.has(error.source) || 'plugin' in error && typeof error.plugin === 'string' && matchedPluginNames.has(error.plugin)) {
continue;
}
const existing_0 = orphanErrorsBySource.get(error.source) || [];
existing_0.push(error);
orphanErrorsBySource.set(error.source, existing_0);
}
const pluginScopes = getPluginEditableScopes();
const failedPluginItems: UnifiedInstalledItem[] = [];
for (const [pluginId_0, errors_0] of orphanErrorsBySource) {
// Skip plugins that are already shown in the flagged section
if (pluginId_0 in flaggedPlugins) continue;
const parsed = parsePluginIdentifier(pluginId_0);
const pluginName_0 = parsed.name || pluginId_0;
const marketplace = parsed.marketplace || 'unknown';
const rawScope = pluginScopes.get(pluginId_0);
// 'flag' is session-only (from --plugin-dir / flagSettings) and undefined
// means the plugin isn't in any settings source. Default both to 'user'
// since UnifiedInstalledItem doesn't have a 'flag' scope variant.
const scope = rawScope === 'flag' || rawScope === undefined ? 'user' : rawScope;
failedPluginItems.push({
type: 'failed-plugin',
id: pluginId_0,
name: pluginName_0,
marketplace,
scope,
errorCount: errors_0.length,
errors: errors_0
});
}
// Build standalone MCP items
const standaloneMcps: UnifiedInstalledItem[] = [];
for (const client_1 of mcpClients) {
if (client_1.name === 'ide') continue;
if (client_1.name.startsWith('plugin:')) continue;
standaloneMcps.push({
type: 'mcp',
id: `mcp:${client_1.name}`,
name: client_1.name,
description: undefined,
scope: client_1.config.scope,
status: getMcpStatus(client_1),
client: client_1
});
}
// Define scope order for display
const scopeOrder: Record<string, number> = {
flagged: -1,
project: 0,
local: 1,
user: 2,
enterprise: 3,
managed: 4,
dynamic: 5,
builtin: 6
};
// Build final list by merging plugins (with their child MCPs) and standalone MCPs
// Group by scope to avoid duplicate scope headers
const unified: UnifiedInstalledItem[] = [];
// Create a map of scope -> items for proper merging
const itemsByScope = new Map<string, UnifiedInstalledItem[]>();
// Add plugins with their child MCPs
for (const {
item: item_1,
originalScope: originalScope_0,
childMcps
} of pluginsWithChildren) {
const scope_0 = item_1.scope;
if (!itemsByScope.has(scope_0)) {
itemsByScope.set(scope_0, []);
}
itemsByScope.get(scope_0)!.push(item_1);
// Add child MCPs right after the plugin, indented (use original scope, not 'flagged').
// Built-in plugins map to 'user' for display since MCP ConfigScope doesn't include 'builtin'.
for (const {
displayName,
client: client_2
} of childMcps) {
const displayScope = originalScope_0 === 'builtin' ? 'user' : originalScope_0;
if (!itemsByScope.has(displayScope)) {
itemsByScope.set(displayScope, []);
}
itemsByScope.get(displayScope)!.push({
type: 'mcp',
id: `mcp:${client_2.name}`,
name: displayName,
description: undefined,
scope: displayScope,
status: getMcpStatus(client_2),
client: client_2,
indented: true
});
}
}
// Add standalone MCPs to their respective scope groups
for (const mcp of standaloneMcps) {
const scope_1 = mcp.scope;
if (!itemsByScope.has(scope_1)) {
itemsByScope.set(scope_1, []);
}
itemsByScope.get(scope_1)!.push(mcp);
}
// Add failed plugins to their respective scope groups
for (const failedPlugin of failedPluginItems) {
const scope_2 = failedPlugin.scope;
if (!itemsByScope.has(scope_2)) {
itemsByScope.set(scope_2, []);
}
itemsByScope.get(scope_2)!.push(failedPlugin);
}
// Add flagged (delisted) plugins from user settings.
// Reason/text are looked up from the cached security messages file.
for (const [pluginId_1, entry] of Object.entries(flaggedPlugins)) {
const parsed_0 = parsePluginIdentifier(pluginId_1);
const pluginName_1 = parsed_0.name || pluginId_1;
const marketplace_0 = parsed_0.marketplace || 'unknown';
if (!itemsByScope.has('flagged')) {
itemsByScope.set('flagged', []);
}
itemsByScope.get('flagged')!.push({
type: 'flagged-plugin',
id: pluginId_1,
name: pluginName_1,
marketplace: marketplace_0,
scope: 'flagged',
reason: 'delisted',
text: 'Removed from marketplace',
flaggedAt: entry.flaggedAt
});
}
// Sort scopes and build final list
const sortedScopes = [...itemsByScope.keys()].sort((a, b) => (scopeOrder[a] ?? 99) - (scopeOrder[b] ?? 99));
for (const scope_3 of sortedScopes) {
const items = itemsByScope.get(scope_3)!;
// Separate items into plugin groups (with their child MCPs) and standalone MCPs
// This preserves parent-child relationships that would be broken by naive sorting
const pluginGroups: UnifiedInstalledItem[][] = [];
const standaloneMcpsInScope: UnifiedInstalledItem[] = [];
let i = 0;
while (i < items.length) {
const item_2 = items[i]!;
if (item_2.type === 'plugin' || item_2.type === 'failed-plugin' || item_2.type === 'flagged-plugin') {
// Collect the plugin and its child MCPs as a group
const group: UnifiedInstalledItem[] = [item_2];
i++;
// Look ahead for indented child MCPs
let nextItem = items[i];
while (nextItem?.type === 'mcp' && nextItem.indented) {
group.push(nextItem);
i++;
nextItem = items[i];
}
pluginGroups.push(group);
} else if (item_2.type === 'mcp' && !item_2.indented) {
// Standalone MCP (not a child of a plugin)
standaloneMcpsInScope.push(item_2);
i++;
} else {
// Skip orphaned indented MCPs (shouldn't happen)
i++;
}
}
// Sort plugin groups by the plugin name (first item in each group)
pluginGroups.sort((a_0, b_0) => a_0[0]!.name.localeCompare(b_0[0]!.name));
// Sort standalone MCPs by name
standaloneMcpsInScope.sort((a_1, b_1) => a_1.name.localeCompare(b_1.name));
// Build final list: plugins (with their children) first, then standalone MCPs
for (const group_0 of pluginGroups) {
unified.push(...group_0);
}
unified.push(...standaloneMcpsInScope);
}
return unified;
}, [pluginStates, mcpClients, pluginErrors, pendingToggles, flaggedPlugins]);
// Mark flagged plugins as seen when the Installed view renders them.
// After 48 hours from seenAt, they auto-clear on next load.
const flaggedIds = useMemo(() => unifiedItems.filter(item_3 => item_3.type === 'flagged-plugin').map(item_4 => item_4.id), [unifiedItems]);
useEffect(() => {
if (flaggedIds.length > 0) {
void markFlaggedPluginsSeen(flaggedIds);
}
}, [flaggedIds]);
// Filter items based on search query (matches name or description)
const filteredItems = useMemo(() => {
if (!searchQuery) return unifiedItems;
const lowerQuery = searchQuery.toLowerCase();
return unifiedItems.filter(item_5 => item_5.name.toLowerCase().includes(lowerQuery) || 'description' in item_5 && item_5.description?.toLowerCase().includes(lowerQuery));
}, [unifiedItems, searchQuery]);
// Selection state
const [selectedIndex, setSelectedIndex] = useState(0);
// Pagination for unified list (continuous scrolling)
const pagination = usePagination<UnifiedInstalledItem>({
totalItems: filteredItems.length,
selectedIndex,
maxVisible: 8
});
// Details view state
const [detailsMenuIndex, setDetailsMenuIndex] = useState(0);
const [isProcessing, setIsProcessing] = useState(false);
const [processError, setProcessError] = useState<string | null>(null);
// Configuration state
const [configNeeded, setConfigNeeded] = useState<McpbNeedsConfigResult | null>(null);
const [_isLoadingConfig, setIsLoadingConfig] = useState(false);
const [selectedPluginHasMcpb, setSelectedPluginHasMcpb] = useState(false);
// Detect if selected plugin has MCPB
// Reads raw marketplace.json to work with old cached marketplaces
useEffect(() => {
if (!selectedPlugin) {
setSelectedPluginHasMcpb(false);
return;
}
async function detectMcpb() {
// Check plugin manifest first
const mcpServersSpec = selectedPlugin!.plugin.manifest.mcpServers;
let hasMcpb = false;
if (mcpServersSpec) {
hasMcpb = typeof mcpServersSpec === 'string' && isMcpbSource(mcpServersSpec) || Array.isArray(mcpServersSpec) && mcpServersSpec.some(s_2 => typeof s_2 === 'string' && isMcpbSource(s_2));
}
// If not in manifest, read raw marketplace.json directly (bypassing schema validation)
// This works even with old cached marketplaces from before MCPB support
if (!hasMcpb) {
try {
const marketplaceDir = path.join(selectedPlugin!.plugin.path, '..');
const marketplaceJsonPath = path.join(marketplaceDir, '.claude-plugin', 'marketplace.json');
const content = await fs.readFile(marketplaceJsonPath, 'utf-8');
const marketplace_1 = jsonParse(content);
const entry_0 = marketplace_1.plugins?.find((p: {
name: string;
}) => p.name === selectedPlugin!.plugin.name);
if (entry_0?.mcpServers) {
const spec = entry_0.mcpServers;
hasMcpb = typeof spec === 'string' && isMcpbSource(spec) || Array.isArray(spec) && spec.some((s_3: unknown) => typeof s_3 === 'string' && isMcpbSource(s_3));
}
} catch (err) {
logForDebugging(`Failed to read raw marketplace.json: ${err}`);
}
}
setSelectedPluginHasMcpb(hasMcpb);
}
void detectMcpb();
}, [selectedPlugin]);
// Load installed plugins grouped by marketplace
useEffect(() => {
async function loadInstalledPlugins() {
setLoading(true);
try {
const {
enabled,
disabled
} = await loadAllPlugins();
const mergedSettings = getSettings_DEPRECATED(); // Use merged settings to respect all layers
const allPlugins = filterManagedDisabledPlugins([...enabled, ...disabled]);
// Group plugins by marketplace
const pluginsByMarketplace: Record<string, LoadedPlugin[]> = {};
for (const plugin of allPlugins) {
const marketplace = plugin.source.split('@')[1] || 'local';
if (!pluginsByMarketplace[marketplace]) {
pluginsByMarketplace[marketplace] = [];
}
pluginsByMarketplace[marketplace]!.push(plugin);
}
// Create marketplace info array with enabled/disabled counts
const marketplaceInfos: MarketplaceInfo[] = [];
for (const [name, plugins] of Object.entries(pluginsByMarketplace)) {
const enabledCount = count(plugins, p => {
const pluginId = `${p.name}@${name}`;
return mergedSettings?.enabledPlugins?.[pluginId] !== false;
});
const disabledCount = plugins.length - enabledCount;
marketplaceInfos.push({
name,
installedPlugins: plugins,
enabledCount,
disabledCount
});
}
// Sort marketplaces: claude-plugin-directory first, then alphabetically
marketplaceInfos.sort((a, b) => {
if (a.name === 'claude-plugin-directory') return -1;
if (b.name === 'claude-plugin-directory') return 1;
return a.name.localeCompare(b.name);
});
setMarketplaces(marketplaceInfos);
// Build flat list of all plugin states
const allStates: PluginState[] = [];
for (const marketplace of marketplaceInfos) {
for (const plugin of marketplace.installedPlugins) {
const pluginId = `${plugin.name}@${marketplace.name}`;
// Built-in plugins don't have V2 install entries — skip the lookup.
const scope = plugin.isBuiltin ? 'builtin' : getPluginInstallationFromV2(pluginId).scope;
allStates.push({
plugin,
marketplace: marketplace.name,
scope,
pendingEnable: undefined,
pendingUpdate: false
});
}
}
setPluginStates(allStates);
setSelectedIndex(0);
} finally {
setLoading(false);
}
}
void loadInstalledPlugins();
}, []);
// Auto-navigate to target plugin if specified (once only)
useEffect(() => {
if (hasAutoNavigated.current) return;
if (targetPlugin && marketplaces.length > 0 && !loading) {
// targetPlugin may be `name` or `name@marketplace` (parseArgs passes the
// raw arg through). Parse it so p.name matching works either way.
const {
name: targetName,
marketplace: targetMktFromId
} = parsePluginIdentifier(targetPlugin);
const effectiveTargetMarketplace = targetMarketplace ?? targetMktFromId;
// Use targetMarketplace if provided, otherwise search all
const marketplacesToSearch = effectiveTargetMarketplace ? marketplaces.filter(m => m.name === effectiveTargetMarketplace) : marketplaces;
// First check successfully loaded plugins
for (const marketplace_2 of marketplacesToSearch) {
const plugin = marketplace_2.installedPlugins.find(p_0 => p_0.name === targetName);
if (plugin) {
// Get scope from V2 data for proper operation handling
const pluginId_2 = `${plugin.name}@${marketplace_2.name}`;
const {
scope: scope_4
} = getPluginInstallationFromV2(pluginId_2);
const pluginState: PluginState = {
plugin,
marketplace: marketplace_2.name,
scope: scope_4,
pendingEnable: undefined,
pendingUpdate: false
};
setSelectedPlugin(pluginState);
setViewState('plugin-details');
pendingAutoActionRef.current = action;
hasAutoNavigated.current = true;
return;
}
}
// Fall back to failed plugins (those with errors but not loaded)
const failedItem = unifiedItems.find(item_6 => item_6.type === 'failed-plugin' && item_6.name === targetName);
if (failedItem && failedItem.type === 'failed-plugin') {
setViewState({
type: 'failed-plugin-details',
plugin: {
id: failedItem.id,
name: failedItem.name,
marketplace: failedItem.marketplace,
errors: failedItem.errors,
scope: failedItem.scope
}
});
hasAutoNavigated.current = true;
}
// No match in loaded OR failed plugins — close the dialog with a
// message rather than silently landing on the plugin list. Only do
// this when an action was requested (e.g. /plugin uninstall X);
// plain navigation (/plugin manage) should still just show the list.
if (!hasAutoNavigated.current && action) {
hasAutoNavigated.current = true;
setResult(`Plugin "${targetPlugin}" is not installed in this project`);
}
}
}, [targetPlugin, targetMarketplace, marketplaces, loading, unifiedItems, action, setResult]);
// Handle single plugin operations from details view
const handleSingleOperation = async (operation: 'enable' | 'disable' | 'update' | 'uninstall') => {
if (!selectedPlugin) return;
const pluginScope = selectedPlugin.scope || 'user';