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

use-composer-command-menu.ts

556 lines18.3 KB

1import type {
2 EnvironmentId,
3 ProjectId,
4 ProviderInteractionMode,
5 ServerProvider,
6} from "@t3tools/contracts";
7import { COMPOSER_CONTEXT_MAX_RECORDS } from "@t3tools/contracts";
8import { Alert } from "react-native";
9import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences";
10import { pullRequestComposerContext } from "../../lib/composerContext";
11import { uuidv4 } from "../../lib/uuid";
12import {
13 getComposerDraftSnapshot,
14 readComposerDraftSelection,
15 setComposerDraftContext,
16} from "../../state/use-composer-drafts";
17import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits";
18import {
19 detectComposerTrigger,
20 replaceTextRange,
21 serializeComposerFileLink,
22 type ComposerTrigger,
23} from "@t3tools/shared/composerTrigger";
24import {
25 insertRankedSearchResult,
26 normalizeSearchQuery,
27 scoreQueryMatch,
28} from "@t3tools/shared/searchRanking";
29import {
30 dedupeProviderSkillsByName,
31 getProviderSkillsForSlashMenu,
32 isProviderSkillUserInvocable,
33 resolveProviderSkillsForCwd,
34} from "@t3tools/client-runtime/providerSkills";
35import { useCallback, useEffect, useMemo, useRef, useState } from "react";
36​
37import type { ComposerEditorSelection } from "../../components/ComposerEditor";
38import { serverEnvironment } from "../../state/server";
39import { useAtomCommand } from "../../state/use-atom-command";
40import { useComposerPathSearch, useComposerPullRequestSearch } from "../../state/queries";
41import type { ComposerCommandItem } from "./ComposerCommandPopover";
42import { matchesSlashSkillQuery } from "./composerSlashSkillSearch";
43​
44const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000;
45​
46function composerSelectionAtEnd(draftMessage: string): ComposerEditorSelection {
47 return { start: draftMessage.length, end: draftMessage.length };
49​
50export function buildComposerSlashCommandItems(input: {
51 readonly query: string;
52 readonly atMessageStart: boolean;
53 readonly hasThread: boolean;
54 readonly hasCompactableConversation?: boolean;
55 /** Whether T3 itself offers /usage-limits for the selected provider. */
56 readonly offersUsageLimits?: boolean;
57 readonly allowInteractionMode: boolean;
58 readonly selectedProviderStatus: Pick<
59 ServerProvider,
60 "driver" | "slashCommands" | "showInteractionModeToggle"
61 > | null;
62}): ComposerCommandItem[] {
63 const query = input.query.toLowerCase();
64 const allowInteractionMode =
65 input.allowInteractionMode && input.selectedProviderStatus?.showInteractionModeToggle !== false;
66 const builtIn = [
67 {
68 id: "cmd:model",
69 type: "slash-command",
70 command: "model",
71 label: "/model",
72 description: "Switch model",
73 },
74 {
75 id: "cmd:plan",
76 type: "slash-command",
77 command: "plan",
78 label: "/plan",
79 description: "Switch to plan mode",
80 },
81 {
82 id: "cmd:default",
83 type: "slash-command",
84 command: "default",
85 label: "/default",
86 description: "Switch to default mode",
87 },
88 ] satisfies ComposerCommandItem[];
89 const items: ComposerCommandItem[] = builtIn.filter(
90 (item) => item.command.includes(query) && (item.command === "model" || allowInteractionMode),
91 );
92​
93 // Providers expand commands only at the start of a message. T3 commands
94 // change local state and do not have this restriction.
95 if (!input.atMessageStart) return items;
96 for (const command of input.selectedProviderStatus?.slashCommands ?? []) {
97 if (!command.name.toLowerCase().includes(query)) continue;
98 if (command.name === "compact" && !input.hasCompactableConversation) continue;
99 // T3's own limits command is answered by the thread composer; New Task has
100 // nowhere to show it. A provider's same-named command is left alone.
101 if (command.name === USAGE_LIMITS_COMMAND.name && input.offersUsageLimits && !input.hasThread) {
102 continue;
103 }
104 if (
105 !input.hasThread &&
106 input.selectedProviderStatus?.driver === "codex" &&
107 command.name === "feedback"
108 ) {
109 continue;
110 }
111 items.push({
112 id: `pcmd:${command.name}`,
113 type: "provider-slash-command",
114 command,
115 label: `/${command.name}`,
116 description: command.description ?? "",
117 });
118 }
119 return items;
121​
122export function resolveComposerCommandSelection(input: {
123 readonly draftMessage: string;
124 readonly trigger: Pick<ComposerTrigger, "rangeStart" | "rangeEnd">;
125 readonly item: ComposerCommandItem;
126 readonly allowInteractionMode: boolean;
127}): {
128 readonly text: string;
129 readonly cursor: number;
130 readonly interactionMode: ProviderInteractionMode | null;
131} {
132 const { draftMessage, trigger, item } = input;
133 if (
134 input.allowInteractionMode &&
135 item.type === "slash-command" &&
136 (item.command === "plan" || item.command === "default")
137 ) {
138 return {
139 ...replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, ""),
140 interactionMode: item.command,
141 };
142 }
143​
144 let replacement = "";
145 if (item.type === "path") {
146 replacement = `${serializeComposerFileLink(item.path)} `;
147 } else if (item.type === "skill") {
148 replacement = `$${item.skill.name} `;
149 } else if (item.type === "slash-command") {
150 replacement = `/${item.command} `;
151 } else if (item.type === "provider-slash-command") {
152 replacement = `/${item.command.name} `;
153 }
154 return {
155 ...replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, replacement),
156 interactionMode: null,
157 };
159​
160/** Shared autocomplete for thread composers and unsent new-task drafts. */
161export function useComposerCommandMenu({
162 draftMessage,
163 ownerKey,
164 environmentId,
165 projectCwd,
166 pullRequestProjectId = null,
167 pullRequestRepository = null,
168 selectedProviderStatus,
169 hasThread,
170 hasCompactableConversation,
171 offersUsageLimits = false,
172 enabled = true,
173 onChangeDraftMessage,
174 onUpdateInteractionMode,
175 onUsageLimits,
176}: {
177 readonly draftMessage: string;
178 readonly ownerKey: string | null;
179 readonly environmentId: EnvironmentId | null;
180 readonly projectCwd: string | null;
181 readonly pullRequestProjectId?: ProjectId | null;
182 readonly pullRequestRepository?: string | null;
183 readonly selectedProviderStatus: ServerProvider | null;
184 readonly hasThread: boolean;
185 readonly hasCompactableConversation: boolean;
186 /** Whether T3 itself offers /usage-limits for the selected provider. */
187 readonly offersUsageLimits?: boolean;
188 readonly enabled?: boolean;
189 readonly onChangeDraftMessage: (value: string) => void;
190 readonly onUpdateInteractionMode?: (mode: ProviderInteractionMode) => void;
191 /** Picking /usage-limits is the action itself; the draft keeps nothing of it. */
192 readonly onUsageLimits?: () => void;
193}) {
194 const [selection, setSelection] = useState(() => composerSelectionAtEnd(draftMessage));
195 const previousOwnerKeyRef = useRef(ownerKey);
196 const onSelectionChange = useCallback((nextSelection: ComposerEditorSelection) => {
197 setSelection(nextSelection);
198 }, []);
199 useEffect(() => {
200 // An insert (attachment, terminal capture, review comment) rewrites the draft and records
201 // the caret that belongs after the new chip. Clamping alone would keep the old offset,
202 // which sits before it.
203 const inserted = ownerKey ? readComposerDraftSelection(ownerKey, draftMessage) : null;
204 if (inserted) {
205 setSelection((current) =>
206 current.start === inserted.start && current.end === inserted.end ? current : inserted,
207 );
208 return;
209 }
210 const end = draftMessage.length;
211 setSelection((current) => {
212 const start = Math.min(current.start, end);
213 const selectionEnd = Math.min(current.end, end);
214 if (start === current.start && selectionEnd === current.end) {
215 return current;
216 }
217 return { start, end: selectionEnd };
218 });
219 }, [draftMessage, ownerKey]);
220 useEffect(() => {
221 if (previousOwnerKeyRef.current === ownerKey) return;
222 previousOwnerKeyRef.current = ownerKey;
223 setSelection(composerSelectionAtEnd(draftMessage));
224 }, [draftMessage, ownerKey]);
225​
226 const skills = useMemo(
227 () =>
228 selectedProviderStatus ? resolveProviderSkillsForCwd(selectedProviderStatus, projectCwd) : [],
229 [projectCwd, selectedProviderStatus],
230 );
231 const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
232 reportFailure: false,
233 });
234 const selectedProviderInstanceId = selectedProviderStatus?.instanceId;
235 const hasWorkspaceSnapshot = Boolean(
236 projectCwd &&
237 selectedProviderStatus?.workspaceSnapshots?.some((snapshot) => snapshot.cwd === projectCwd),
238 );
239 const workspaceRefreshKeyRef = useRef<string | null>(null);
240 const workspaceRefreshRetryRef = useRef<{ key: string; notBefore: number } | null>(null);
241 const hadWorkspaceSnapshotRef = useRef(false);
242 useEffect(() => {
243 if (hadWorkspaceSnapshotRef.current && !hasWorkspaceSnapshot) {
244 workspaceRefreshKeyRef.current = null;
245 workspaceRefreshRetryRef.current = null;
246 }
247 hadWorkspaceSnapshotRef.current = hasWorkspaceSnapshot;
248 }, [hasWorkspaceSnapshot]);
249 useEffect(() => {
250 if (!environmentId || !projectCwd || !selectedProviderInstanceId) return;
251 const key = `${environmentId}:${selectedProviderInstanceId}:${projectCwd}`;
252 if (workspaceRefreshKeyRef.current === key) return;
253 if (hasWorkspaceSnapshot) {
254 workspaceRefreshKeyRef.current = key;
255 workspaceRefreshRetryRef.current = null;
256 return;
257 }
258 const retry = workspaceRefreshRetryRef.current;
259 if (retry?.key === key && Date.now() < retry.notBefore) return;
260 workspaceRefreshKeyRef.current = key;
261 const retryLater = () => {
262 if (workspaceRefreshKeyRef.current !== key) return;
263 workspaceRefreshKeyRef.current = null;
264 workspaceRefreshRetryRef.current = {
265 key,
266 notBefore: Date.now() + WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS,
267 };
268 };
269 void refreshProviders({
270 environmentId,
271 input: { instanceId: selectedProviderInstanceId, cwd: projectCwd },
272 }).then((result) => {
273 const refreshed =
274 result._tag === "Success" &&
275 result.value.providers
276 .find((provider) => provider.instanceId === selectedProviderInstanceId)
277 ?.workspaceSnapshots?.some((snapshot) => snapshot.cwd === projectCwd);
278 if (!refreshed && workspaceRefreshKeyRef.current === key) {
279 retryLater();
280 }
281 }, retryLater);
282 }, [
283 draftMessage,
284 environmentId,
285 hasWorkspaceSnapshot,
286 projectCwd,
287 refreshProviders,
288 selectedProviderInstanceId,
289 ]);
290​
291 const trigger = useMemo(() => {
292 if (!enabled || selection.start !== selection.end) {
293 return null;
294 }
295 return detectComposerTrigger(draftMessage, selection.end);
296 }, [draftMessage, enabled, selection]);
297 const pathSearch = useComposerPathSearch({
298 environmentId,
299 cwd: trigger?.kind === "path" ? projectCwd : null,
300 query: trigger?.kind === "path" ? trigger.query : null,
301 });
302 const pullRequestSearch = useComposerPullRequestSearch({
303 environmentId,
304 projectId: pullRequestProjectId,
305 repository: pullRequestRepository,
306 query: trigger?.kind === "pull-request" ? trigger.query : null,
307 });
308​
309 const items = useMemo<ComposerCommandItem[]>(() => {
310 if (!trigger) return [];
311​
312 if (trigger.kind === "pull-request") {
313 return pullRequestSearch.entries.map((entry) => ({
314 id: `pr:${entry.projectId}:${entry.repository}:${entry.number}`,
315 type: "pull-request",
316 pullRequest: {
317 number: entry.number,
318 title: entry.title,
319 url: entry.url,
320 headBranch: entry.headBranch,
321 baseBranch: entry.baseBranch,
322 state: entry.state,
323 isDraft: entry.isDraft,
324 },
325 label: `#${entry.number}`,
326 description: `${entry.isDraft ? "Draft" : entry.state} · ${entry.title}`,
327 }));
328 }
329​
330 if (trigger.kind === "slash-command") {
331 const q = trigger.query.toLowerCase();
332 const commandItems = buildComposerSlashCommandItems({
333 query: q,
334 atMessageStart: trigger.rangeStart === 0,
335 hasThread,
336 hasCompactableConversation,
337 offersUsageLimits,
338 allowInteractionMode: onUpdateInteractionMode !== undefined,
339 selectedProviderStatus,
340 });
341​
342 const skillItems = getProviderSkillsForSlashMenu(skills, true)
343 .filter((skill) => matchesSlashSkillQuery(skill, q))
344 .map((skill) => ({
345 id: `skill:${skill.name}`,
346 type: "skill" as const,
347 skill,
348 label: `skill:${skill.name}`,
349 description: skill.shortDescription ?? skill.description ?? "",
350 }));
351​
352 return [...commandItems, ...skillItems];
353 }
354​
355 if (trigger.kind === "skill") {
356 const enabledSkills = dedupeProviderSkillsByName(skills.filter(isProviderSkillUserInvocable));
357 const normalizedQuery = normalizeSearchQuery(trigger.query, {
358 trimLeadingPattern: /^\$+/,
359 });
360​
361 if (!normalizedQuery) {
362 return enabledSkills.slice(0, 20).map((skill) => ({
363 id: `skill:${skill.name}`,
364 type: "skill" as const,
365 skill,
366 label: skill.displayName ?? skill.name,
367 description: skill.shortDescription ?? skill.description ?? "",
368 }));
369 }
370​
371 const ranked: Array<{
372 item: (typeof enabledSkills)[number];
373 score: number;
374 tieBreaker: string;
375 }> = [];
376 for (const skill of enabledSkills) {
377 const displayLabel = (skill.displayName ?? skill.name).toLowerCase();
378 const scores = [
379 scoreQueryMatch({
380 value: skill.name.toLowerCase(),
381 query: normalizedQuery,
382 exactBase: 0,
383 prefixBase: 2,
384 boundaryBase: 4,
385 includesBase: 6,
386 fuzzyBase: 100,
387 boundaryMarkers: ["-", "_", "/"],
388 }),
389 scoreQueryMatch({
390 value: displayLabel,
391 query: normalizedQuery,
392 exactBase: 1,
393 prefixBase: 3,
394 boundaryBase: 5,
395 includesBase: 7,
396 fuzzyBase: 110,
397 }),
398 scoreQueryMatch({
399 value: skill.shortDescription?.toLowerCase() ?? "",
400 query: normalizedQuery,
401 exactBase: 20,
402 prefixBase: 22,
403 boundaryBase: 24,
404 includesBase: 26,
405 }),
406 scoreQueryMatch({
407 value: skill.description?.toLowerCase() ?? "",
408 query: normalizedQuery,
409 exactBase: 30,
410 prefixBase: 32,
411 boundaryBase: 34,
412 includesBase: 36,
413 }),
414 ].filter((score): score is number => score !== null);
415​
416 if (scores.length > 0) {
417 insertRankedSearchResult(
418 ranked,
419 {
420 item: skill,
421 score: Math.min(...scores),
422 tieBreaker: `${displayLabel}\u0000${skill.name}`,
423 },
424 20,
425 );
426 }
427 }
428​
429 return ranked.map(({ item: skill }) => ({
430 id: `skill:${skill.name}`,
431 type: "skill" as const,
432 skill,
433 label: skill.displayName ?? skill.name,
434 description: skill.shortDescription ?? skill.description ?? "",
435 }));
436 }
437​
438 if (trigger.kind === "path") {
439 return pathSearch.entries.map((entry) => {
440 const parts = entry.path.split("/");
441 return {
442 id: `path:${entry.path}`,
443 type: "path" as const,
444 path: entry.path,
445 kind: entry.kind,
446 label: parts[parts.length - 1] ?? entry.path,
447 description: parts.length > 1 ? parts.slice(0, -1).join("/") : "",
448 };
449 });
450 }
451​
452 return [];
453 }, [
454 hasThread,
455 hasCompactableConversation,
456 onUpdateInteractionMode,
457 pathSearch.entries,
458 pullRequestSearch.entries,
459 selectedProviderStatus,
460 skills,
461 trigger,
462 offersUsageLimits,
463 ]);
464​
465 const onSelect = useCallback(
466 (item: ComposerCommandItem) => {
467 if (!trigger) return;
468 if (item.type === "pull-request") {
469 if (
470 !ownerKey ||
471 trigger.kind !== "pull-request" ||
472 !items.some((candidate) => candidate.id === item.id)
473 )
474 return;
475 const record = pullRequestComposerContext(item.pullRequest, uuidv4());
476 if (
477 (getComposerDraftSnapshot(ownerKey).context?.records.length ?? 0) >=
478 COMPOSER_CONTEXT_MAX_RECORDS
479 ) {
480 Alert.alert(
481 "Too many context items",
482 "Remove some context from the draft and try again.",
483 );
484 return;
485 }
486 const result = replaceTextRange(
487 draftMessage,
488 trigger.rangeStart,
489 trigger.rangeEnd,
490 `${formatComposerContextReference(record)} `,
491 );
492 onChangeDraftMessage(result.text);
493 const draft = getComposerDraftSnapshot(ownerKey);
494 setComposerDraftContext(ownerKey, {
495 version: 1,
496 records: [...(draft.context?.records ?? []), record],
497 });
498 setSelection({ start: result.cursor, end: result.cursor });
499 return;
500 }
501​
502 if (
503 item.type === "provider-slash-command" &&
504 item.command.name === USAGE_LIMITS_COMMAND.name &&
505 onUsageLimits
506 ) {
507 const cleared = replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, "");
508 setSelection({ start: cleared.cursor, end: cleared.cursor });
509 onChangeDraftMessage(cleared.text);
510 onUsageLimits();
511 return;
512 }
513​
514 const result = resolveComposerCommandSelection({
515 draftMessage,
516 trigger,
517 item,
518 allowInteractionMode:
519 onUpdateInteractionMode !== undefined &&
520 selectedProviderStatus?.showInteractionModeToggle !== false,
521 });
522 setSelection({ start: result.cursor, end: result.cursor });
523 onChangeDraftMessage(result.text);
524 if (result.interactionMode !== null) {
525 onUpdateInteractionMode?.(result.interactionMode);
526 }
527 },
528 [
529 draftMessage,
530 ownerKey,
531 items,
532 onChangeDraftMessage,
533 onUpdateInteractionMode,
534 onUsageLimits,
535 selectedProviderStatus?.showInteractionModeToggle,
536 trigger,
537 ],
538 );
539​
540 return {
541 selection,
542 onSelectionChange,
543 trigger,
544 items,
545 skills,
546 isLoading:
547 trigger?.kind === "pull-request" ? pullRequestSearch.isPending : pathSearch.isPending,
548 error:
549 trigger?.kind === "pull-request"
550 ? pullRequestProjectId === null || pullRequestRepository === null
551 ? "Pull requests are unavailable for this project."
552 : pullRequestSearch.error
553 : null,
554 onSelect,
555 };