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

use-composer-command-menu.ts

574 lines19.0 KB

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