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

use-composer-command-menu.ts

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