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