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

use-composer-command-menu.ts

729 lines24.9 KB

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