forked from op7418/CodePilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseSlashCommands.ts
More file actions
262 lines (236 loc) · 9.13 KB
/
useSlashCommands.ts
File metadata and controls
262 lines (236 loc) · 9.13 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
import { useCallback, useMemo } from 'react';
import type { PopoverItem, PopoverMode, SkillKind } from '@/types';
import { detectPopoverTrigger, resolveItemSelection } from '@/lib/message-input-logic';
import { BUILT_IN_COMMANDS, COMMAND_PROMPTS } from '@/lib/constants/commands';
import { COMMAND_ICONS } from '@/lib/constants/command-icons';
// Re-export for backward compatibility
export { BUILT_IN_COMMANDS, COMMAND_PROMPTS };
export interface UseSlashCommandsReturn {
fetchFiles: (filter: string) => Promise<PopoverItem[]>;
fetchSkills: () => Promise<PopoverItem[]>;
insertItem: (item: PopoverItem) => void;
handleInputChange: (val: string) => Promise<void>;
handleInsertSlash: () => void;
}
export function useSlashCommands(opts: {
sessionId?: string;
workingDirectory?: string;
sdkInitMeta?: { tools?: unknown; slash_commands?: unknown; skills?: unknown } | null;
textareaRef: React.RefObject<HTMLTextAreaElement | null>;
inputValue: string;
setInputValue: (value: string) => void;
popoverMode: PopoverMode;
popoverFilter: string;
triggerPos: number | null;
setPopoverMode: (mode: PopoverMode) => void;
setPopoverFilter: (filter: string) => void;
setPopoverItems: (items: PopoverItem[]) => void;
setSelectedIndex: React.Dispatch<React.SetStateAction<number>>;
setTriggerPos: (pos: number | null) => void;
closePopover: () => void;
onCommand?: (command: string) => void;
setBadge: (badge: { command: string; label: string; description: string; kind: SkillKind; installedSource?: "agents" | "claude" } | null) => void;
}): UseSlashCommandsReturn {
const {
sessionId,
workingDirectory,
sdkInitMeta,
textareaRef,
inputValue,
setInputValue,
popoverMode,
popoverFilter,
triggerPos,
setPopoverMode,
setPopoverFilter,
setPopoverItems,
setSelectedIndex,
setTriggerPos,
closePopover,
onCommand,
setBadge,
} = opts;
// Enrich built-in commands with icons (presentation layer enrichment)
const enrichedBuiltIns = useMemo(
() => BUILT_IN_COMMANDS.map(cmd => ({ ...cmd, icon: COMMAND_ICONS[cmd.value] })),
[],
);
// Fetch files for @ mention
const fetchFiles = useCallback(async (filter: string) => {
try {
const params = new URLSearchParams();
if (sessionId) params.set('session_id', sessionId);
if (filter) params.set('q', filter);
const res = await fetch(`/api/files?${params.toString()}`);
if (!res.ok) return [];
const data = await res.json();
const tree = data.tree || [];
const items: PopoverItem[] = [];
function flattenTree(nodes: Array<{ name: string; path: string; type: string; children?: unknown[] }>) {
for (const node of nodes) {
items.push({ label: node.name, value: node.path });
if (node.children) flattenTree(node.children as typeof nodes);
}
}
flattenTree(tree);
return items.slice(0, 20);
} catch {
return [];
}
}, [sessionId]);
// Fetch skills for / command (built-in + API)
const fetchSkills = useCallback(async () => {
let apiSkills: PopoverItem[] = [];
try {
const params = new URLSearchParams();
if (workingDirectory) params.set('cwd', workingDirectory);
if (sessionId) params.set('sessionId', sessionId);
const qs = params.toString();
const res = await fetch(`/api/skills${qs ? `?${qs}` : ''}`);
if (res.ok) {
const data = await res.json();
const skills = data.skills || [];
apiSkills = skills
.filter((s: { source?: string; loaded?: boolean }) => {
// Exclude plugin-source skills that are not loaded in the current session
if (s.source === 'plugin' && s.loaded === false) return false;
return true;
})
.map((s: { name: string; description: string; source?: "global" | "project" | "plugin" | "installed" | "sdk"; kind?: SkillKind; installedSource?: "agents" | "claude" }) => ({
label: s.name,
value: `/${s.name}`,
description: s.description || "",
builtIn: false,
installedSource: s.installedSource,
source: s.source,
kind: s.kind || 'slash_command',
}));
}
} catch {
// API not available - just use built-in commands
}
// When SDK init metadata is available, use it as the truth source
if (sdkInitMeta) {
const rawCmds = sdkInitMeta.slash_commands;
const rawSkills = sdkInitMeta.skills;
const sdkCommandNames = new Set(
Array.isArray(rawCmds) ? rawCmds.map(c => typeof c === 'string' ? c : (c as { name?: string })?.name).filter(Boolean) as string[] : []
);
const sdkSkillNames = new Set(
Array.isArray(rawSkills) ? rawSkills.map(s => typeof s === 'string' ? s : (s as { name?: string })?.name).filter(Boolean) as string[] : []
);
// Only filter if SDK actually reported capabilities (non-empty arrays)
if (sdkCommandNames.size > 0 || sdkSkillNames.size > 0) {
apiSkills = apiSkills.filter(item => {
if (item.kind === 'agent_skill') return sdkSkillNames.has(item.label);
return sdkCommandNames.has(item.label);
});
}
const existingNames = new Set(apiSkills.map(s => s.label));
// Add SDK-reported commands not found in filesystem scan
for (const cmdName of sdkCommandNames) {
if (!existingNames.has(cmdName)) {
apiSkills.push({
label: cmdName,
value: `/${cmdName}`,
description: `SDK command: /${cmdName}`,
builtIn: false,
source: 'sdk',
kind: 'sdk_command',
});
}
}
// Add SDK-reported skills not found in filesystem scan
for (const skillName of sdkSkillNames) {
if (!existingNames.has(skillName)) {
apiSkills.push({
label: skillName,
value: `/${skillName}`,
description: `Skill: /${skillName}`,
builtIn: false,
kind: 'agent_skill',
});
}
}
}
// Deduplicate: remove API skills that share a name with built-in commands
const builtInNames = new Set(enrichedBuiltIns.map(c => c.label));
const uniqueSkills = apiSkills.filter(s => !builtInNames.has(s.label));
return [...enrichedBuiltIns, ...uniqueSkills];
}, [sessionId, workingDirectory, sdkInitMeta, enrichedBuiltIns]);
// Insert selected item
const insertItem = useCallback((item: PopoverItem) => {
if (triggerPos === null) return;
const result = resolveItemSelection(item, popoverMode, triggerPos, inputValue, popoverFilter);
switch (result.action) {
case 'immediate_command':
if (onCommand) {
setInputValue('');
closePopover();
onCommand(result.commandValue!);
}
return;
case 'set_badge':
setBadge(result.badge!);
setInputValue('');
closePopover();
setTimeout(() => textareaRef.current?.focus(), 0);
return;
case 'insert_file_mention':
setInputValue(result.newInputValue!);
closePopover();
setTimeout(() => textareaRef.current?.focus(), 0);
return;
}
}, [triggerPos, popoverMode, closePopover, onCommand, inputValue, popoverFilter, textareaRef, setInputValue, setBadge]);
// Handle input changes to detect @ and /
const handleInputChange = useCallback(async (val: string) => {
setInputValue(val);
const textarea = textareaRef.current;
if (!textarea) return;
const cursorPos = textarea.selectionStart;
const trigger = detectPopoverTrigger(val, cursorPos);
if (trigger) {
setPopoverMode(trigger.mode!);
setPopoverFilter(trigger.filter);
setTriggerPos(trigger.triggerPos);
setSelectedIndex(0);
if (trigger.mode === 'file') {
const items = await fetchFiles(trigger.filter);
setPopoverItems(items);
} else {
const items = await fetchSkills();
setPopoverItems(items);
}
return;
}
// Only auto-close text-triggered popovers (file/skill); CLI is button-triggered
if (popoverMode && popoverMode !== 'cli') {
closePopover();
}
}, [fetchFiles, fetchSkills, popoverMode, closePopover, textareaRef, setInputValue, setPopoverMode, setPopoverFilter, setTriggerPos, setSelectedIndex, setPopoverItems]);
// Insert `/` into textarea to trigger slash command popover
const handleInsertSlash = useCallback(() => {
const textarea = textareaRef.current;
if (!textarea) return;
const cursorPos = textarea.selectionStart;
const before = inputValue.slice(0, cursorPos);
const after = inputValue.slice(cursorPos);
const newValue = before + '/' + after;
const newCursorPos = cursorPos + 1;
setInputValue(newValue);
// Set cursor position first so handleInputChange reads correct selectionStart
textarea.value = newValue;
textarea.selectionStart = newCursorPos;
textarea.selectionEnd = newCursorPos;
textarea.focus();
handleInputChange(newValue);
}, [inputValue, handleInputChange, textareaRef, setInputValue]);
return {
fetchFiles,
fetchSkills,
insertItem,
handleInputChange,
handleInsertSlash,
};
}