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