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

use-composer-command-menu.ts

669 lines22.9 KB

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