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

use-composer-command-menu.ts

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