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

use-composer-command-menu.ts

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