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

use-composer-command-menu.ts

431 lines13.7 KB

1import type { EnvironmentId, ProviderInteractionMode, ServerProvider } from "@t3tools/contracts";
2import {
3 detectComposerTrigger,
4 replaceTextRange,
5 serializeComposerFileLink,
6 type ComposerTrigger,
7} from "@t3tools/shared/composerTrigger";
8import {
9 insertRankedSearchResult,
10 normalizeSearchQuery,
11 scoreQueryMatch,
12} from "@t3tools/shared/searchRanking";
13import {
14 dedupeProviderSkillsByName,
15 getProviderSkillsForSlashMenu,
16 isProviderSkillUserInvocable,
17 resolveProviderSkillsForCwd,
18} from "@t3tools/client-runtime/providerSkills";
19import { useCallback, useEffect, useMemo, useRef, useState } from "react";
20​
21import type { ComposerEditorSelection } from "../../components/ComposerEditor";
22import { serverEnvironment } from "../../state/server";
23import { useAtomCommand } from "../../state/use-atom-command";
24import { useComposerPathSearch } from "../../state/queries";
25import type { ComposerCommandItem } from "./ComposerCommandPopover";
26import { matchesSlashSkillQuery } from "./composerSlashSkillSearch";
27​
28const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000;
29​
30function composerSelectionAtEnd(draftMessage: string): ComposerEditorSelection {
31 return { start: draftMessage.length, end: draftMessage.length };
33​
34export function buildComposerSlashCommandItems(input: {
35 readonly query: string;
36 readonly atMessageStart: boolean;
37 readonly hasThread: boolean;
38 readonly hasCompactableConversation?: boolean;
39 readonly allowInteractionMode: boolean;
40 readonly selectedProviderStatus: Pick<
41 ServerProvider,
42 "driver" | "slashCommands" | "showInteractionModeToggle"
43 > | null;
44}): ComposerCommandItem[] {
45 const query = input.query.toLowerCase();
46 const allowInteractionMode =
47 input.allowInteractionMode && input.selectedProviderStatus?.showInteractionModeToggle !== false;
48 const builtIn = [
49 {
50 id: "cmd:model",
51 type: "slash-command",
52 command: "model",
53 label: "/model",
54 description: "Switch model",
55 },
56 {
57 id: "cmd:plan",
58 type: "slash-command",
59 command: "plan",
60 label: "/plan",
61 description: "Switch to plan mode",
62 },
63 {
64 id: "cmd:default",
65 type: "slash-command",
66 command: "default",
67 label: "/default",
68 description: "Switch to default mode",
69 },
70 ] satisfies ComposerCommandItem[];
71 const items: ComposerCommandItem[] = builtIn.filter(
72 (item) => item.command.includes(query) && (item.command === "model" || allowInteractionMode),
73 );
74​
75 // Providers expand commands only at the start of a message. T3 commands
76 // change local state and do not have this restriction.
77 if (!input.atMessageStart) return items;
78 for (const command of input.selectedProviderStatus?.slashCommands ?? []) {
79 if (!command.name.toLowerCase().includes(query)) continue;
80 if (command.name === "compact" && !input.hasCompactableConversation) continue;
81 if (
82 !input.hasThread &&
83 input.selectedProviderStatus?.driver === "codex" &&
84 command.name === "feedback"
85 ) {
86 continue;
87 }
88 items.push({
89 id: `pcmd:${command.name}`,
90 type: "provider-slash-command",
91 command,
92 label: `/${command.name}`,
93 description: command.description ?? "",
94 });
95 }
96 return items;
98​
99export function resolveComposerCommandSelection(input: {
100 readonly draftMessage: string;
101 readonly trigger: Pick<ComposerTrigger, "rangeStart" | "rangeEnd">;
102 readonly item: ComposerCommandItem;
103 readonly allowInteractionMode: boolean;
104}): {
105 readonly text: string;
106 readonly cursor: number;
107 readonly interactionMode: ProviderInteractionMode | null;
108} {
109 const { draftMessage, trigger, item } = input;
110 if (
111 input.allowInteractionMode &&
112 item.type === "slash-command" &&
113 (item.command === "plan" || item.command === "default")
114 ) {
115 return {
116 ...replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, ""),
117 interactionMode: item.command,
118 };
119 }
120​
121 let replacement = "";
122 if (item.type === "path") {
123 replacement = `${serializeComposerFileLink(item.path)} `;
124 } else if (item.type === "skill") {
125 replacement = `$${item.skill.name} `;
126 } else if (item.type === "slash-command") {
127 replacement = `/${item.command} `;
128 } else if (item.type === "provider-slash-command") {
129 replacement = `/${item.command.name} `;
130 }
131 return {
132 ...replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, replacement),
133 interactionMode: null,
134 };
136​
137/** Shared autocomplete for thread composers and unsent new-task drafts. */
138export function useComposerCommandMenu({
139 draftMessage,
140 ownerKey,
141 environmentId,
142 projectCwd,
143 selectedProviderStatus,
144 hasThread,
145 hasCompactableConversation,
146 enabled = true,
147 onChangeDraftMessage,
148 onUpdateInteractionMode,
149}: {
150 readonly draftMessage: string;
151 readonly ownerKey: string | null;
152 readonly environmentId: EnvironmentId | null;
153 readonly projectCwd: string | null;
154 readonly selectedProviderStatus: ServerProvider | null;
155 readonly hasThread: boolean;
156 readonly hasCompactableConversation: boolean;
157 readonly enabled?: boolean;
158 readonly onChangeDraftMessage: (value: string) => void;
159 readonly onUpdateInteractionMode?: (mode: ProviderInteractionMode) => void;
160}) {
161 const [selection, setSelection] = useState(() => composerSelectionAtEnd(draftMessage));
162 const previousOwnerKeyRef = useRef(ownerKey);
163 const onSelectionChange = useCallback((nextSelection: ComposerEditorSelection) => {
164 setSelection(nextSelection);
165 }, []);
166 useEffect(() => {
167 const end = draftMessage.length;
168 setSelection((current) => {
169 const start = Math.min(current.start, end);
170 const selectionEnd = Math.min(current.end, end);
171 if (start === current.start && selectionEnd === current.end) {
172 return current;
173 }
174 return { start, end: selectionEnd };
175 });
176 }, [draftMessage.length]);
177 useEffect(() => {
178 if (previousOwnerKeyRef.current === ownerKey) return;
179 previousOwnerKeyRef.current = ownerKey;
180 setSelection(composerSelectionAtEnd(draftMessage));
181 }, [draftMessage, ownerKey]);
182​
183 const skills = useMemo(
184 () =>
185 selectedProviderStatus ? resolveProviderSkillsForCwd(selectedProviderStatus, projectCwd) : [],
186 [projectCwd, selectedProviderStatus],
187 );
188 const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
189 reportFailure: false,
190 });
191 const selectedProviderInstanceId = selectedProviderStatus?.instanceId;
192 const hasWorkspaceSnapshot = Boolean(
193 projectCwd &&
194 selectedProviderStatus?.workspaceSnapshots?.some((snapshot) => snapshot.cwd === projectCwd),
195 );
196 const workspaceRefreshKeyRef = useRef<string | null>(null);
197 const workspaceRefreshRetryRef = useRef<{ key: string; notBefore: number } | null>(null);
198 const hadWorkspaceSnapshotRef = useRef(false);
199 useEffect(() => {
200 if (hadWorkspaceSnapshotRef.current && !hasWorkspaceSnapshot) {
201 workspaceRefreshKeyRef.current = null;
202 workspaceRefreshRetryRef.current = null;
203 }
204 hadWorkspaceSnapshotRef.current = hasWorkspaceSnapshot;
205 }, [hasWorkspaceSnapshot]);
206 useEffect(() => {
207 if (!environmentId || !projectCwd || !selectedProviderInstanceId) return;
208 const key = `${environmentId}:${selectedProviderInstanceId}:${projectCwd}`;
209 if (workspaceRefreshKeyRef.current === key) return;
210 if (hasWorkspaceSnapshot) {
211 workspaceRefreshKeyRef.current = key;
212 workspaceRefreshRetryRef.current = null;
213 return;
214 }
215 const retry = workspaceRefreshRetryRef.current;
216 if (retry?.key === key && Date.now() < retry.notBefore) return;
217 workspaceRefreshKeyRef.current = key;
218 const retryLater = () => {
219 if (workspaceRefreshKeyRef.current !== key) return;
220 workspaceRefreshKeyRef.current = null;
221 workspaceRefreshRetryRef.current = {
222 key,
223 notBefore: Date.now() + WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS,
224 };
225 };
226 void refreshProviders({
227 environmentId,
228 input: { instanceId: selectedProviderInstanceId, cwd: projectCwd },
229 }).then((result) => {
230 const refreshed =
231 result._tag === "Success" &&
232 result.value.providers
233 .find((provider) => provider.instanceId === selectedProviderInstanceId)
234 ?.workspaceSnapshots?.some((snapshot) => snapshot.cwd === projectCwd);
235 if (!refreshed && workspaceRefreshKeyRef.current === key) {
236 retryLater();
237 }
238 }, retryLater);
239 }, [
240 draftMessage,
241 environmentId,
242 hasWorkspaceSnapshot,
243 projectCwd,
244 refreshProviders,
245 selectedProviderInstanceId,
246 ]);
247​
248 const trigger = useMemo(() => {
249 if (!enabled || selection.start !== selection.end) {
250 return null;
251 }
252 return detectComposerTrigger(draftMessage, selection.end);
253 }, [draftMessage, enabled, selection]);
254 const pathSearch = useComposerPathSearch({
255 environmentId,
256 cwd: trigger?.kind === "path" ? projectCwd : null,
257 query: trigger?.kind === "path" ? trigger.query : null,
258 });
259​
260 const items = useMemo<ComposerCommandItem[]>(() => {
261 if (!trigger) return [];
262​
263 if (trigger.kind === "slash-command") {
264 const q = trigger.query.toLowerCase();
265 const commandItems = buildComposerSlashCommandItems({
266 query: q,
267 atMessageStart: trigger.rangeStart === 0,
268 hasThread,
269 hasCompactableConversation,
270 allowInteractionMode: onUpdateInteractionMode !== undefined,
271 selectedProviderStatus,
272 });
273​
274 const skillItems = getProviderSkillsForSlashMenu(skills, true)
275 .filter((skill) => matchesSlashSkillQuery(skill, q))
276 .map((skill) => ({
277 id: `skill:${skill.name}`,
278 type: "skill" as const,
279 skill,
280 label: `skill:${skill.name}`,
281 description: skill.shortDescription ?? skill.description ?? "",
282 }));
283​
284 return [...commandItems, ...skillItems];
285 }
286​
287 if (trigger.kind === "skill") {
288 const enabledSkills = dedupeProviderSkillsByName(skills.filter(isProviderSkillUserInvocable));
289 const normalizedQuery = normalizeSearchQuery(trigger.query, {
290 trimLeadingPattern: /^\$+/,
291 });
292​
293 if (!normalizedQuery) {
294 return enabledSkills.slice(0, 20).map((skill) => ({
295 id: `skill:${skill.name}`,
296 type: "skill" as const,
297 skill,
298 label: skill.displayName ?? skill.name,
299 description: skill.shortDescription ?? skill.description ?? "",
300 }));
301 }
302​
303 const ranked: Array<{
304 item: (typeof enabledSkills)[number];
305 score: number;
306 tieBreaker: string;
307 }> = [];
308 for (const skill of enabledSkills) {
309 const displayLabel = (skill.displayName ?? skill.name).toLowerCase();
310 const scores = [
311 scoreQueryMatch({
312 value: skill.name.toLowerCase(),
313 query: normalizedQuery,
314 exactBase: 0,
315 prefixBase: 2,
316 boundaryBase: 4,
317 includesBase: 6,
318 fuzzyBase: 100,
319 boundaryMarkers: ["-", "_", "/"],
320 }),
321 scoreQueryMatch({
322 value: displayLabel,
323 query: normalizedQuery,
324 exactBase: 1,
325 prefixBase: 3,
326 boundaryBase: 5,
327 includesBase: 7,
328 fuzzyBase: 110,
329 }),
330 scoreQueryMatch({
331 value: skill.shortDescription?.toLowerCase() ?? "",
332 query: normalizedQuery,
333 exactBase: 20,
334 prefixBase: 22,
335 boundaryBase: 24,
336 includesBase: 26,
337 }),
338 scoreQueryMatch({
339 value: skill.description?.toLowerCase() ?? "",
340 query: normalizedQuery,
341 exactBase: 30,
342 prefixBase: 32,
343 boundaryBase: 34,
344 includesBase: 36,
345 }),
346 ].filter((score): score is number => score !== null);
347​
348 if (scores.length > 0) {
349 insertRankedSearchResult(
350 ranked,
351 {
352 item: skill,
353 score: Math.min(...scores),
354 tieBreaker: `${displayLabel}\u0000${skill.name}`,
355 },
356 20,
357 );
358 }
359 }
360​
361 return ranked.map(({ item: skill }) => ({
362 id: `skill:${skill.name}`,
363 type: "skill" as const,
364 skill,
365 label: skill.displayName ?? skill.name,
366 description: skill.shortDescription ?? skill.description ?? "",
367 }));
368 }
369​
370 if (trigger.kind === "path") {
371 return pathSearch.entries.map((entry) => {
372 const parts = entry.path.split("/");
373 return {
374 id: `path:${entry.path}`,
375 type: "path" as const,
376 path: entry.path,
377 kind: entry.kind,
378 label: parts[parts.length - 1] ?? entry.path,
379 description: parts.length > 1 ? parts.slice(0, -1).join("/") : "",
380 };
381 });
382 }
383​
384 return [];
385 }, [
386 hasThread,
387 hasCompactableConversation,
388 onUpdateInteractionMode,
389 pathSearch.entries,
390 selectedProviderStatus,
391 skills,
392 trigger,
393 ]);
394​
395 const onSelect = useCallback(
396 (item: ComposerCommandItem) => {
397 if (!trigger) return;
398​
399 const result = resolveComposerCommandSelection({
400 draftMessage,
401 trigger,
402 item,
403 allowInteractionMode:
404 onUpdateInteractionMode !== undefined &&
405 selectedProviderStatus?.showInteractionModeToggle !== false,
406 });
407 setSelection({ start: result.cursor, end: result.cursor });
408 onChangeDraftMessage(result.text);
409 if (result.interactionMode !== null) {
410 onUpdateInteractionMode?.(result.interactionMode);
411 }
412 },
413 [
414 draftMessage,
415 onChangeDraftMessage,
416 onUpdateInteractionMode,
417 selectedProviderStatus?.showInteractionModeToggle,
418 trigger,
419 ],
420 );
421​
422 return {
423 selection,
424 onSelectionChange,
425 trigger,
426 items,
427 skills,
428 isLoading: pathSearch.isPending,
429 onSelect,
430 };