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