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