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

use-composer-command-menu.ts

629 lines21.1 KB

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