Open History to see the last commit
1import { threadPullRequestKeyOf } from "@t3tools/client-runtime/thread-pull-requests";
2import * as Dialog from "../../components/ui/Dialog";
3import type {
4 EnvironmentId,
5 ProjectId,
6 ServerProvider,
7 ThreadId,
8 ThreadPullRequestLink,
9} from "@t3tools/contracts";
10import {
11 type ComposerEnvironmentCandidate,
12 matchComposerEnvironmentItems,
13 matchComposerThreadItems,
14} from "@t3tools/client-runtime/composerThreadItems";
15import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models";
16
17const EMPTY_THREAD_SHELLS: ReadonlyArray<EnvironmentThreadShell> = [];
18const EMPTY_ENVIRONMENTS: ReadonlyArray<ComposerEnvironmentCandidate> = [];
19const NO_LINKED_ENVIRONMENTS: ReadonlyMap<EnvironmentId, string> = new Map();
20import { COMPOSER_CONTEXT_MAX_RECORDS } from "@t3tools/contracts";
21import {
22 formatComposerContextReference,
23 threadContextRecord,
24} from "@t3tools/shared/composerContextReferences";
25import { environmentComposerContext, pullRequestComposerContext } from "../../lib/composerContext";
26import { uuidv4 } from "../../lib/uuid";
27import {
28 getComposerDraftSnapshot,
29 setComposerDraftContext,
30 useComposerDraftSelection,
31} from "../../state/use-composer-drafts";
32import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits";
33import {
34 detectComposerTrigger,
35 replaceTextRange,
36 serializeComposerFileLink,
37 type ComposerTrigger,
38} from "@t3tools/shared/composerTrigger";
39import {
40 insertRankedSearchResult,
41 normalizeSearchQuery,
42 scoreQueryMatch,
43} from "@t3tools/shared/searchRanking";
44import {
45 dedupeProviderSkillsByName,
46 getProviderSkillsForSlashMenu,
47 getProviderSlashCommandsForSlashMenu,
48 isProviderSkillUserInvocable,
49 resolveProviderSkillsForCwd,
50 resolveProviderSlashCommandsForCwd,
51} from "@t3tools/client-runtime/providerSkills";
52import {
53 formatComposerModelMention,
54 rankComposerModelMentions,
55} from "@t3tools/client-runtime/composer-model-mentions";
56import { useAtomRefresh } from "@effect/atom-react";
57import { Atom } from "effect/reactivity";
58import { msg, useGT, useMessages } from "gt-react-native";
59import { useEffect, useState } from "react";
60
61import type { ComposerEditorSelection } from "../../components/ComposerEditor";
62import { providerWorkspaceSnapshotRefresh } from "../../state/provider-workspace-snapshot-refresh";
63import {
64 useComposerPathSearch,
65 useComposerPullRequestSearch,
66 useThreadSearch,
67} from "../../state/queries";
68import type { ModelOption } from "../../lib/modelOptions";
69import { m, type MessageResolver } from "../../i18n/messages";
70import type { ComposerCommandItem } from "./ComposerCommandPopover";
71import { scoreSlashSkillQuery } from "./composerSlashSkillSearch";
72
73const idleWorkspaceSnapshotRefreshAtom: Atom.Atom<unknown> = Atom.make<void>(undefined).pipe(
74 Atom.withLabel("mobile:provider-workspace-snapshot-refresh:idle"),
75);
76
77function composerSelectionAtEnd(draftMessage: string): ComposerEditorSelection {
78 return { start: draftMessage.length, end: draftMessage.length };
79}
80
81/**
82 * A caret placed by an insertion (chips, pasted context) wins while the draft
83 * still has the text it was placed in. Otherwise the composer's own caret is
84 * clamped to the draft, and a caret from another owner starts at the end.
85 */
86export function resolveComposerMenuSelection(input: {
87 readonly draftMessage: string;
88 readonly ownerKey: string | null;
89 readonly inserted: ComposerEditorSelection | null;
90 readonly local: {
91 readonly ownerKey: string | null;
92 readonly start: number;
93 readonly end: number;
94 };
95}): ComposerEditorSelection {
96 if (input.inserted) return input.inserted;
97 if (input.local.ownerKey !== input.ownerKey) return composerSelectionAtEnd(input.draftMessage);
98 const length = input.draftMessage.length;
99 return { start: Math.min(input.local.start, length), end: Math.min(input.local.end, length) };
100}
101
102const PULL_REQUEST_STATE_LABELS = {
103 open: msg("open", { $context: "pull request state" }),
104 closed: msg("closed", { $context: "pull request state" }),
105 merged: msg("merged", { $context: "pull request state" }),
106} as const;
107
108export function buildComposerSlashCommandItems(
109 input: {
110 readonly query: string;
111 readonly atMessageStart: boolean;
112 readonly hasThread: boolean;
113 readonly hasCompactableConversation?: boolean;
114 readonly offersUsageLimits?: boolean;
115 /** T3's `/clear` replaces the provider's, which would clear a session T3 still treats as live. */
116 readonly offersFreshSession?: boolean;
117 readonly offersSideChat?: boolean;
118 readonly selectedProviderStatus: Pick<ServerProvider, "driver" | "slashCommands"> | null;
119 },
120 resolve: MessageResolver = m,
121): ComposerCommandItem[] {
122 const query = input.query.toLowerCase();
123 const items: ComposerCommandItem[] = "model".includes(query)
124 ? [
125 {
126 id: "cmd:model",
127 type: "slash-command",
128 command: "model",
129 label: "/model",
130 description: resolve(msg("Switch model")),
131 },
132 ]
133 : [];
134
135 // Providers expand commands only at the start of a message. T3 commands
136 // change local state and do not have this restriction, except `/clear`.
137 if (!input.atMessageStart) return items;
138 if (input.offersSideChat) {
139 for (const [command, description] of [
140 ["side", resolve(msg("Ask a side question in a new side chat"))],
141 ["btw", resolve(msg("Same as /side"))],
142 ] as const) {
143 if (!command.includes(query)) continue;
144 items.push({
145 id: `cmd:${command}`,
146 type: "slash-command",
147 command,
148 label: `/${command}`,
149 description,
150 });
151 }
152 }
153 if (input.offersFreshSession && "clear".includes(query)) {
154 items.push({
155 id: "cmd:clear",
156 type: "slash-command",
157 command: "clear",
158 label: "/clear",
159 description: resolve(msg("Start a fresh session")),
160 });
161 }
162 for (const command of input.selectedProviderStatus?.slashCommands ?? []) {
163 if (!command.name.toLowerCase().includes(query)) continue;
164 if (command.name === "clear" && input.offersFreshSession) continue;
165 if (command.name === "compact" && !input.hasCompactableConversation) continue;
166 if (command.name === USAGE_LIMITS_COMMAND.name && input.offersUsageLimits && !input.hasThread) {
167 continue;
168 }
169 if (
170 !input.hasThread &&
171 input.selectedProviderStatus?.driver === "codex" &&
172 command.name === "feedback"
173 ) {
174 continue;
175 }
176 items.push({
177 id: `pcmd:${command.name}`,
178 type: "provider-slash-command",
179 command,
180 label: `/${command.name}`,
181 description: command.description ?? "",
182 });
183 }
184 return items;
185}
186
187export function buildComposerModelItems(
188 modelOptions: ReadonlyArray<ModelOption>,
189 query: string,
190 providers: ReadonlyArray<ServerProvider>,
191): ComposerCommandItem[] {
192 // The picker retains saved selections even when their provider is no longer usable.
193 const readyProviderIds = new Set(
194 providers
195 .filter(
196 (provider) =>
197 provider.installed &&
198 provider.status === "ready" &&
199 provider.auth.status !== "unauthenticated" &&
200 provider.availability !== "unavailable",
201 )
202 .map((provider) => provider.instanceId),
203 );
204 return rankComposerModelMentions(
205 modelOptions.filter(
206 (option) =>
207 readyProviderIds.has(option.selection.instanceId) &&
208 !option.isUnavailable &&
209 !option.isHidden &&
210 !option.isLegacy,
211 ),
212 query,
213 (option) => ({
214 name: option.label,
215 ...(option.subtitle ? { subProvider: option.subtitle } : {}),
216 driverKind: option.providerDriver,
217 providerDisplayName: option.providerLabel,
218 }),
219 ).map((option) => ({
220 id: `model:${option.key}`,
221 type: "model",
222 option,
223 label: option.label,
224 description: option.subtitle
225 ? `${option.providerLabel} · ${option.subtitle}`
226 : option.providerLabel,
227 }));
228}
229
230export function resolveComposerCommandSelection(input: {
231 readonly draftMessage: string;
232 readonly trigger: Pick<ComposerTrigger, "rangeStart" | "rangeEnd">;
233 readonly item: ComposerCommandItem;
234}): { readonly text: string; readonly cursor: number } {
235 const { draftMessage, trigger, item } = input;
236 let replacement = "";
237 if (item.type === "path") {
238 replacement = `${serializeComposerFileLink(item.path)} `;
239 } else if (item.type === "skill") {
240 replacement = `$${item.skill.name} `;
241 } else if (item.type === "slash-command") {
242 replacement = `/${item.command} `;
243 } else if (item.type === "provider-slash-command") {
244 replacement = `/${item.command.name} `;
245 } else if (item.type === "model") {
246 replacement = `${formatComposerModelMention(item.option.selection.instanceId, item.option.selection.model)} `;
247 }
248 return replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, replacement);
249}
250
251export function useComposerCommandMenu({
252 draftMessage,
253 ownerKey,
254 environmentId,
255 threadShells = EMPTY_THREAD_SHELLS,
256 environments = EMPTY_ENVIRONMENTS,
257 linkedEnvironments = NO_LINKED_ENVIRONMENTS,
258 currentThreadId = null,
259 projectCwd,
260 pullRequestProjectId = null,
261 pullRequestRepository = null,
262 threadPullRequests,
263 selectedProviderStatus,
264 hasThread,
265 hasCompactableConversation,
266 offersUsageLimits = false,
267 enabled = true,
268 onChangeDraftMessage,
269 onUsageLimits,
270 onOpenModelPicker,
271 modelOptions,
272 modelProviders,
273 onFreshSession,
274 offersSideChat = false,
275}: {
276 readonly draftMessage: string;
277 readonly ownerKey: string | null;
278 readonly environmentId: EnvironmentId | null;
279 readonly threadShells?: ReadonlyArray<EnvironmentThreadShell>;
280 readonly environments?: ReadonlyArray<ComposerEnvironmentCandidate>;
281 /** The machines `environmentId` links to, by name, whose threads the picker also offers. */
282 readonly linkedEnvironments?: ReadonlyMap<EnvironmentId, string>;
283 readonly currentThreadId?: ThreadId | null;
284 readonly projectCwd: string | null;
285 readonly pullRequestProjectId?: ProjectId | null;
286 readonly pullRequestRepository?: string | null;
287 readonly threadPullRequests?: ReadonlyArray<ThreadPullRequestLink>;
288 readonly selectedProviderStatus: ServerProvider | null;
289 readonly hasThread: boolean;
290 readonly hasCompactableConversation: boolean;
291 readonly offersUsageLimits?: boolean;
292 readonly enabled?: boolean;
293 readonly onChangeDraftMessage: (value: string) => void;
294 readonly onUsageLimits?: () => void;
295 /** `/model` opens this picker instead of inserting text. */
296 readonly onOpenModelPicker: () => void;
297 readonly modelOptions?: ReadonlyArray<ModelOption>;
298 readonly modelProviders?: ReadonlyArray<ServerProvider>;
299 /** Arms a fresh session for the next message; absent where `/clear` is unavailable. */
300 readonly onFreshSession?: () => void;
301 readonly offersSideChat?: boolean;
302}) {
303 const gt = useGT();
304 const messages = useMessages();
305 const [localSelection, setLocalSelection] = useState(() => ({
306 ownerKey,
307 ...composerSelectionAtEnd(draftMessage),
308 }));
309 // Thread mentions rank by recency as of when the composer mounted.
310 const [now] = useState(() => Date.now());
311 const insertedSelection = useComposerDraftSelection(ownerKey, draftMessage);
312 const selection = resolveComposerMenuSelection({
313 draftMessage,
314 ownerKey,
315 inserted: insertedSelection,
316 local: localSelection,
317 });
318 const setSelection = (next: ComposerEditorSelection) =>
319 setLocalSelection({ ownerKey, start: next.start, end: next.end });
320
321 const skills = selectedProviderStatus
322 ? resolveProviderSkillsForCwd(selectedProviderStatus, projectCwd)
323 : [];
324 const selectedProviderInstanceId = selectedProviderStatus?.instanceId;
325 const refreshWorkspaceSnapshot = useAtomRefresh(
326 environmentId && projectCwd && selectedProviderInstanceId
327 ? providerWorkspaceSnapshotRefresh({
328 environmentId,
329 instanceId: selectedProviderInstanceId,
330 cwd: projectCwd,
331 })
332 : idleWorkspaceSnapshotRefreshAtom,
333 );
334 // Every draft change rechecks a stale snapshot, including drafts written by
335 // another surface (a prompt link) that never move the editor selection.
336 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes the provider workspace snapshot atom whenever the draft text changes from any surface
337 useEffect(() => {
338 refreshWorkspaceSnapshot();
339 }, [
340 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Draft changes are the recheck signal.
341 draftMessage,
342 refreshWorkspaceSnapshot,
343 ]);
344 const onSelectionChange = (nextSelection: ComposerEditorSelection) => {
345 setSelection(nextSelection);
346 };
347
348 const trigger = (() => {
349 if (!enabled || selection.start !== selection.end) {
350 return null;
351 }
352 return detectComposerTrigger(draftMessage, selection.end);
353 })();
354 const pathSearch = useComposerPathSearch({
355 environmentId,
356 cwd: trigger?.kind === "path" ? projectCwd : null,
357 query: trigger?.kind === "path" ? trigger.query : null,
358 });
359 // Mounts older settled threads matching the mention, here and on linked machines, which shells
360 // may leave out.
361 useThreadSearch(
362 trigger?.kind === "path" && environmentId ? [environmentId, ...linkedEnvironments.keys()] : [],
363 trigger?.kind === "path" ? trigger.query : "",
364 { titlesOnly: true },
365 );
366 const pullRequestSearch = useComposerPullRequestSearch({
367 environmentId,
368 projectId: pullRequestProjectId,
369 repository: pullRequestRepository,
370 threadPullRequests,
371 query: trigger?.kind === "pull-request" ? trigger.query : null,
372 });
373
374 const items = ((): ComposerCommandItem[] => {
375 if (!trigger) return [];
376
377 if (trigger.kind === "pull-request") {
378 return pullRequestSearch.entries.map((entry) => ({
379 id: `pr:${entry.projectId}:${threadPullRequestKeyOf(entry)}`,
380 type: "pull-request",
381 pullRequest: {
382 number: entry.number,
383 title: entry.title,
384 url: entry.url,
385 headBranch: entry.headBranch,
386 baseBranch: entry.baseBranch,
387 state: entry.state,
388 isDraft: entry.isDraft,
389 },
390 label: `#${entry.number}`,
391 description: `${entry.isDraft ? gt("Draft", { $context: "pull request state" }) : messages(PULL_REQUEST_STATE_LABELS[entry.state])} · ${
392 entry.repository.toLowerCase() === pullRequestRepository?.toLowerCase()
393 ? ""
394 : `${entry.repository} · `
395 }${entry.title}`,
396 }));
397 }
398
399 if (trigger.kind === "slash-command") {
400 const q = trigger.query.toLowerCase();
401 const visibleSkills = getProviderSkillsForSlashMenu(skills, true);
402 const commandItems = buildComposerSlashCommandItems(
403 {
404 query: q,
405 atMessageStart: trigger.rangeStart === 0,
406 hasThread,
407 hasCompactableConversation,
408 offersUsageLimits,
409 offersFreshSession: onFreshSession !== undefined,
410 offersSideChat,
411 selectedProviderStatus: selectedProviderStatus
412 ? {
413 ...selectedProviderStatus,
414 slashCommands: getProviderSlashCommandsForSlashMenu(
415 resolveProviderSlashCommandsForCwd(selectedProviderStatus, projectCwd),
416 visibleSkills,
417 ),
418 }
419 : null,
420 },
421 messages,
422 );
423
424 const skillItems = visibleSkills
425 .flatMap((skill) => {
426 const score = scoreSlashSkillQuery(skill, q);
427 return score === null ? [] : [{ skill, score }];
428 })
429 .sort((left, right) => left.score - right.score)
430 .map(({ skill }) => ({
431 id: `skill:${skill.name}`,
432 type: "skill" as const,
433 skill,
434 label: `skill:${skill.name}`,
435 description: skill.shortDescription ?? skill.description ?? "",
436 }));
437
438 return [...commandItems, ...skillItems];
439 }
440
441 if (trigger.kind === "skill") {
442 const enabledSkills = dedupeProviderSkillsByName(skills.filter(isProviderSkillUserInvocable));
443 const normalizedQuery = normalizeSearchQuery(trigger.query, {
444 trimLeadingPattern: /^\p{Sc}+/u,
445 });
446
447 if (!normalizedQuery) {
448 return enabledSkills.slice(0, 20).map((skill) => ({
449 id: `skill:${skill.name}`,
450 type: "skill" as const,
451 skill,
452 label: skill.displayName ?? skill.name,
453 description: skill.shortDescription ?? skill.description ?? "",
454 }));
455 }
456
457 const ranked: Array<{
458 item: (typeof enabledSkills)[number];
459 score: number;
460 tieBreaker: string;
461 }> = [];
462 for (const skill of enabledSkills) {
463 const displayLabel = (skill.displayName ?? skill.name).toLowerCase();
464 const scores = [
465 scoreQueryMatch({
466 value: skill.name.toLowerCase(),
467 query: normalizedQuery,
468 exactBase: 0,
469 prefixBase: 2,
470 boundaryBase: 4,
471 includesBase: 6,
472 fuzzyBase: 100,
473 boundaryMarkers: ["-", "_", "/"],
474 }),
475 scoreQueryMatch({
476 value: displayLabel,
477 query: normalizedQuery,
478 exactBase: 1,
479 prefixBase: 3,
480 boundaryBase: 5,
481 includesBase: 7,
482 fuzzyBase: 110,
483 }),
484 scoreQueryMatch({
485 value: skill.shortDescription?.toLowerCase() ?? "",
486 query: normalizedQuery,
487 exactBase: 20,
488 prefixBase: 22,
489 boundaryBase: 24,
490 includesBase: 26,
491 }),
492 scoreQueryMatch({
493 value: skill.description?.toLowerCase() ?? "",
494 query: normalizedQuery,
495 exactBase: 30,
496 prefixBase: 32,
497 boundaryBase: 34,
498 includesBase: 36,
499 }),
500 ].filter((score): score is number => score !== null);
501
502 if (scores.length > 0) {
503 insertRankedSearchResult(
504 ranked,
505 {
506 item: skill,
507 score: Math.min(...scores),
508 tieBreaker: `${displayLabel}\u0000${skill.name}`,
509 },
510 20,
511 );
512 }
513 }
514
515 return ranked.map(({ item: skill }) => ({
516 id: `skill:${skill.name}`,
517 type: "skill" as const,
518 skill,
519 label: skill.displayName ?? skill.name,
520 description: skill.shortDescription ?? skill.description ?? "",
521 }));
522 }
523
524 if (trigger.kind === "path") {
525 const threadItems = environmentId
526 ? matchComposerThreadItems(
527 {
528 shells: threadShells,
529 environmentId,
530 linkedEnvironments,
531 excludeThreadId: currentThreadId,
532 query: trigger.query,
533 now,
534 },
535 messages,
536 )
537 : [];
538 const environmentItems = environmentId
539 ? matchComposerEnvironmentItems(
540 { environments, linkedEnvironments, environmentId, query: trigger.query },
541 messages,
542 )
543 : [];
544 const modelItems =
545 modelOptions && modelProviders
546 ? buildComposerModelItems(modelOptions, trigger.query, modelProviders)
547 : [];
548 return [
549 ...threadItems,
550 ...environmentItems,
551 ...modelItems,
552 ...pathSearch.entries.map((entry) => {
553 const parts = entry.path.normalize("NFC").split("/");
554 return {
555 id: `path:${entry.path}`,
556 type: "path" as const,
557 path: entry.path,
558 kind: entry.kind,
559 label: parts[parts.length - 1] ?? entry.path,
560 description: parts.length > 1 ? parts.slice(0, -1).join("/") : "",
561 };
562 }),
563 ];
564 }
565
566 return [];
567 })();
568
569 const onSelect = (item: ComposerCommandItem) => {
570 if (!trigger) return;
571 if (item.type === "environment") {
572 if (!ownerKey || trigger.kind !== "path") return;
573 const record = environmentComposerContext(item.environmentId, item.label);
574 const existing = getComposerDraftSnapshot(ownerKey).context?.records ?? [];
575 const alreadyAttached = existing.some((entry) => entry.contextId === record.contextId);
576 if (!alreadyAttached && existing.length >= COMPOSER_CONTEXT_MAX_RECORDS) {
577 Dialog.alert(
578 gt("Too many context items"),
579 gt("Remove some context from the draft and try again."),
580 );
581 return;
582 }
583 const result = replaceTextRange(
584 draftMessage,
585 trigger.rangeStart,
586 trigger.rangeEnd,
587 `${formatComposerContextReference(record)} `,
588 );
589 onChangeDraftMessage(result.text);
590 if (!alreadyAttached) {
591 const draft = getComposerDraftSnapshot(ownerKey);
592 setComposerDraftContext(ownerKey, {
593 version: 1,
594 records: [...(draft.context?.records ?? []), record],
595 });
596 }
597 setSelection({ start: result.cursor, end: result.cursor });
598 return;
599 }
600 if (item.type === "thread") {
601 if (!ownerKey || trigger.kind !== "path") return;
602 const shell = threadShells.find(
603 (candidate) =>
604 candidate.environmentId === item.thread.environmentId &&
605 candidate.id === item.thread.threadId,
606 );
607 if (!shell) return;
608 const record = threadContextRecord(item.thread, shell.title);
609 const existing = getComposerDraftSnapshot(ownerKey).context?.records ?? [];
610 const alreadyAttached = existing.some((entry) => entry.contextId === record.contextId);
611 if (!alreadyAttached && existing.length >= COMPOSER_CONTEXT_MAX_RECORDS) {
612 Dialog.alert(
613 gt("Too many context items"),
614 gt("Remove some context from the draft and try again."),
615 );
616 return;
617 }
618 const result = replaceTextRange(
619 draftMessage,
620 trigger.rangeStart,
621 trigger.rangeEnd,
622 `${formatComposerContextReference(record)} `,
623 );
624 onChangeDraftMessage(result.text);
625 if (!alreadyAttached) {
626 const draft = getComposerDraftSnapshot(ownerKey);
627 setComposerDraftContext(ownerKey, {
628 version: 1,
629 records: [...(draft.context?.records ?? []), record],
630 });
631 }
632 setSelection({ start: result.cursor, end: result.cursor });
633 return;
634 }
635 if (item.type === "pull-request") {
636 if (
637 !ownerKey ||
638 trigger.kind !== "pull-request" ||
639 !items.some((candidate) => candidate.id === item.id)
640 )
641 return;
642 const record = pullRequestComposerContext(item.pullRequest, uuidv4());
643 if (
644 (getComposerDraftSnapshot(ownerKey).context?.records.length ?? 0) >=
645 COMPOSER_CONTEXT_MAX_RECORDS
646 ) {
647 Dialog.alert(
648 gt("Too many context items"),
649 gt("Remove some context from the draft and try again."),
650 );
651 return;
652 }
653 const result = replaceTextRange(
654 draftMessage,
655 trigger.rangeStart,
656 trigger.rangeEnd,
657 `${formatComposerContextReference(record)} `,
658 );
659 onChangeDraftMessage(result.text);
660 const draft = getComposerDraftSnapshot(ownerKey);
661 setComposerDraftContext(ownerKey, {
662 version: 1,
663 records: [...(draft.context?.records ?? []), record],
664 });
665 setSelection({ start: result.cursor, end: result.cursor });
666 return;
667 }
668
669 const clearTriggerThen = (action: () => void) => {
670 const cleared = replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, "");
671 setSelection({ start: cleared.cursor, end: cleared.cursor });
672 onChangeDraftMessage(cleared.text);
673 action();
674 };
675 if (item.type === "slash-command" && item.command === "model") {
676 clearTriggerThen(onOpenModelPicker);
677 return;
678 }
679 if (item.type === "slash-command" && item.command === "clear" && onFreshSession) {
680 clearTriggerThen(onFreshSession);
681 return;
682 }
683 if (
684 item.type === "provider-slash-command" &&
685 item.command.name === USAGE_LIMITS_COMMAND.name &&
686 onUsageLimits
687 ) {
688 clearTriggerThen(onUsageLimits);
689 return;
690 }
691
692 const result = resolveComposerCommandSelection({ draftMessage, trigger, item });
693 setSelection({ start: result.cursor, end: result.cursor });
694 onChangeDraftMessage(result.text);
695 };
696
697 return {
698 selection,
699 onSelectionChange,
700 trigger,
701 items,
702 skills,
703 isLoading:
704 trigger?.kind === "pull-request" ? pullRequestSearch.isPending : pathSearch.isPending,
705 error:
706 trigger?.kind === "pull-request"
707 ? pullRequestProjectId === null || pullRequestRepository === null
708 ? gt("Pull requests are unavailable for this project.")
709 : pullRequestSearch.error
710 : null,
711 onSelect,
712 };
713}