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

use-composer-command-menu.ts

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