Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

use-composer-command-menu.ts

292 lines9.2 KB

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