Open History to see the last commit
1import type { EnvironmentId, ProviderInteractionMode, ServerProvider } from "@t3tools/contracts";
2import {
3 detectComposerTrigger,
4 replaceTextRange,
5 serializeComposerFileLink,
6} from "@t3tools/shared/composerTrigger";
7import {
8 insertRankedSearchResult,
9 normalizeSearchQuery,
10 scoreQueryMatch,
11} from "@t3tools/shared/searchRanking";
12import { useCallback, useEffect, useMemo, useState } from "react";
13
14import type { ComposerEditorSelection } from "../../components/ComposerEditor";
15import { useComposerPathSearch } from "../../state/use-composer-path-search";
16import type { ComposerCommandItem } from "./ComposerCommandPopover";
17import { matchesSlashSkillQuery } from "./composerSlashSkillSearch";
18
19/** Shared autocomplete for thread composers and unsent new-task drafts. */
20export function useComposerCommandMenu({
21 draftMessage,
22 environmentId,
23 projectCwd,
24 selectedProviderStatus,
25 hasThread,
26 enabled = true,
27 onChangeDraftMessage,
28 onUpdateInteractionMode,
29}: {
30 readonly draftMessage: string;
31 readonly environmentId: EnvironmentId | null;
32 readonly projectCwd: string | null;
33 readonly selectedProviderStatus: ServerProvider | null;
34 readonly hasThread: boolean;
35 readonly enabled?: boolean;
36 readonly onChangeDraftMessage: (value: string) => void;
37 readonly onUpdateInteractionMode?: (mode: ProviderInteractionMode) => void;
38}) {
39 const [selection, setSelection] = useState(() => ({
40 start: draftMessage.length,
41 end: draftMessage.length,
42 }));
43 const onSelectionChange = useCallback((nextSelection: ComposerEditorSelection) => {
44 setSelection(nextSelection);
45 }, []);
46 useEffect(() => {
47 const end = draftMessage.length;
48 setSelection((current) => {
49 const start = Math.min(current.start, end);
50 const selectionEnd = Math.min(current.end, end);
51 if (start === current.start && selectionEnd === current.end) {
52 return current;
53 }
54 return { start, end: selectionEnd };
55 });
56 }, [draftMessage.length]);
57
58 const trigger = useMemo(() => {
59 if (!enabled || selection.start !== selection.end) {
60 return null;
61 }
62 return detectComposerTrigger(draftMessage, selection.end);
63 }, [draftMessage, enabled, selection]);
64 const pathSearch = useComposerPathSearch({
65 environmentId,
66 cwd: trigger?.kind === "path" ? projectCwd : null,
67 query: trigger?.kind === "path" ? trigger.query : null,
68 });
69
70 const items = useMemo<ComposerCommandItem[]>(() => {
71 if (!trigger) return [];
72
73 if (trigger.kind === "slash-command") {
74 const q = trigger.query.toLowerCase();
75 const allBuiltIn = [
76 {
77 id: "cmd:model",
78 type: "slash-command" as const,
79 command: "model",
80 label: "/model",
81 description: "Switch model",
82 },
83 {
84 id: "cmd:plan",
85 type: "slash-command" as const,
86 command: "plan",
87 label: "/plan",
88 description: "Switch to plan mode",
89 },
90 {
91 id: "cmd:default",
92 type: "slash-command" as const,
93 command: "default",
94 label: "/default",
95 description: "Switch to default mode",
96 },
97 ];
98 const builtIn = allBuiltIn.filter(
99 (item) =>
100 item.command.includes(q) &&
101 (item.command === "model" || onUpdateInteractionMode !== undefined),
102 );
103
104 const providerCommands: ComposerCommandItem[] = [];
105 for (const command of selectedProviderStatus?.slashCommands ?? []) {
106 if (!command.name.toLowerCase().includes(q)) continue;
107 // Codex feedback uploads an existing thread's session and logs.
108 if (
109 !hasThread &&
110 selectedProviderStatus?.driver === "codex" &&
111 command.name === "feedback"
112 ) {
113 continue;
114 }
115 providerCommands.push({
116 id: `pcmd:${command.name}`,
117 type: "provider-slash-command",
118 command,
119 label: `/${command.name}`,
120 description: command.description ?? "",
121 });
122 }
123
124 const skillItems = (selectedProviderStatus?.skills ?? [])
125 .filter((skill) => matchesSlashSkillQuery(skill, q))
126 .map((skill) => ({
127 id: `skill:${skill.name}`,
128 type: "skill" as const,
129 skill,
130 label: `skill:${skill.name}`,
131 description: skill.shortDescription ?? skill.description ?? "",
132 }));
133
134 return [...builtIn, ...providerCommands, ...skillItems];
135 }
136
137 if (trigger.kind === "skill") {
138 const enabledSkills = (selectedProviderStatus?.skills ?? []).filter((skill) => skill.enabled);
139 const normalizedQuery = normalizeSearchQuery(trigger.query, {
140 trimLeadingPattern: /^\$+/,
141 });
142
143 if (!normalizedQuery) {
144 return enabledSkills.slice(0, 20).map((skill) => ({
145 id: `skill:${skill.name}`,
146 type: "skill" as const,
147 skill,
148 label: skill.displayName ?? skill.name,
149 description: skill.shortDescription ?? skill.description ?? "",
150 }));
151 }
152
153 const ranked: Array<{
154 item: (typeof enabledSkills)[number];
155 score: number;
156 tieBreaker: string;
157 }> = [];
158 for (const skill of enabledSkills) {
159 const displayLabel = (skill.displayName ?? skill.name).toLowerCase();
160 const scores = [
161 scoreQueryMatch({
162 value: skill.name.toLowerCase(),
163 query: normalizedQuery,
164 exactBase: 0,
165 prefixBase: 2,
166 boundaryBase: 4,
167 includesBase: 6,
168 fuzzyBase: 100,
169 boundaryMarkers: ["-", "_", "/"],
170 }),
171 scoreQueryMatch({
172 value: displayLabel,
173 query: normalizedQuery,
174 exactBase: 1,
175 prefixBase: 3,
176 boundaryBase: 5,
177 includesBase: 7,
178 fuzzyBase: 110,
179 }),
180 scoreQueryMatch({
181 value: skill.shortDescription?.toLowerCase() ?? "",
182 query: normalizedQuery,
183 exactBase: 20,
184 prefixBase: 22,
185 boundaryBase: 24,
186 includesBase: 26,
187 }),
188 scoreQueryMatch({
189 value: skill.description?.toLowerCase() ?? "",
190 query: normalizedQuery,
191 exactBase: 30,
192 prefixBase: 32,
193 boundaryBase: 34,
194 includesBase: 36,
195 }),
196 ].filter((score): score is number => score !== null);
197
198 if (scores.length > 0) {
199 insertRankedSearchResult(
200 ranked,
201 {
202 item: skill,
203 score: Math.min(...scores),
204 tieBreaker: `${displayLabel}\u0000${skill.name}`,
205 },
206 20,
207 );
208 }
209 }
210
211 return ranked.map(({ item: skill }) => ({
212 id: `skill:${skill.name}`,
213 type: "skill" as const,
214 skill,
215 label: skill.displayName ?? skill.name,
216 description: skill.shortDescription ?? skill.description ?? "",
217 }));
218 }
219
220 if (trigger.kind === "path") {
221 return pathSearch.entries.map((entry) => {
222 const parts = entry.path.split("/");
223 return {
224 id: `path:${entry.path}`,
225 type: "path" as const,
226 path: entry.path,
227 kind: entry.kind,
228 label: parts[parts.length - 1] ?? entry.path,
229 description: parts.length > 1 ? parts.slice(0, -1).join("/") : "",
230 };
231 });
232 }
233
234 return [];
235 }, [hasThread, onUpdateInteractionMode, pathSearch.entries, selectedProviderStatus, trigger]);
236
237 const onSelect = useCallback(
238 (item: ComposerCommandItem) => {
239 if (!trigger) return;
240
241 if (
242 item.type === "slash-command" &&
243 (item.command === "plan" || item.command === "default")
244 ) {
245 const result = replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, "");
246 setSelection({ start: result.cursor, end: result.cursor });
247 onChangeDraftMessage(result.text);
248 onUpdateInteractionMode?.(item.command);
249 return;
250 }
251
252 let replacement = "";
253 if (item.type === "path") {
254 replacement = `${serializeComposerFileLink(item.path)} `;
255 } else if (item.type === "skill") {
256 replacement = `$${item.skill.name} `;
257 } else if (item.type === "slash-command") {
258 replacement = `/${item.command} `;
259 } else if (item.type === "provider-slash-command") {
260 replacement = `/${item.command.name} `;
261 }
262
263 const result = replaceTextRange(
264 draftMessage,
265 trigger.rangeStart,
266 trigger.rangeEnd,
267 replacement,
268 );
269 setSelection({ start: result.cursor, end: result.cursor });
270 onChangeDraftMessage(result.text);
271 },
272 [draftMessage, onChangeDraftMessage, onUpdateInteractionMode, trigger],
273 );
274
275 return {
276 selection,
277 onSelectionChange,
278 trigger,
279 items,
280 isLoading: pathSearch.isPending,
281 onSelect,
282 };
283}