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