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

use-composer-command-menu.ts

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