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 // Record client request time to enforce TTL even when the client clock runs ahead of the server.
250 const workspaceRefreshKeyRef = useRef<{ key: string; requestedAt: number } | null>(null);
251 const [workspaceRefreshRetry, setWorkspaceRefreshRetry] = useState<{
252 key: string;
253 notBefore: number;
254 } | null>(null);
255 const workspaceRefreshScopeKey =
256 environmentId && projectCwd && selectedProviderInstanceId
257 ? `${environmentId}:${selectedProviderInstanceId}:${projectCwd}`
258 : null;
259 const workspaceSlashCommandsPending =
260 selectedProviderStatus?.workspaceSnapshots?.some(
261 (snapshot) => snapshot.cwd === projectCwd && snapshot.slashCommandsPending === true,
262 ) ?? false;
263 useEffect(() => {
264 if (
265 !workspaceSlashCommandsPending ||
266 !workspaceRefreshRetry ||
267 workspaceRefreshRetry.key !== workspaceRefreshScopeKey
268 )
269 return;
270 const timeout = setTimeout(
271 () => {
272 setWorkspaceRefreshRetry((current) => (current === workspaceRefreshRetry ? null : current));
273 },
274 Math.max(0, workspaceRefreshRetry.notBefore - Date.now()),
275 );
276 return () => clearTimeout(timeout);
277 }, [workspaceRefreshRetry, workspaceRefreshScopeKey, workspaceSlashCommandsPending]);
278 const hadWorkspaceSnapshotRef = useRef(false);
279 useEffect(() => {
280 if (hadWorkspaceSnapshotRef.current && !hasWorkspaceSnapshot) {
281 workspaceRefreshKeyRef.current = null;
282 setWorkspaceRefreshRetry(null);
283 }
284 hadWorkspaceSnapshotRef.current = hasWorkspaceSnapshot;
285 }, [hasWorkspaceSnapshot]);
286 useEffect(() => {
287 if (!environmentId || !projectCwd || !selectedProviderInstanceId) return;
288 const key = `${environmentId}:${selectedProviderInstanceId}:${projectCwd}`;
289 const now = Date.now();
290 const lastRequest = workspaceRefreshKeyRef.current;
291 if (
292 lastRequest?.key === key &&
293 now - lastRequest.requestedAt < PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS
294 )
295 return;
296 if (hasCurrentProviderWorkspaceSnapshot(selectedProviderStatus, projectCwd, now)) {
297 setWorkspaceRefreshRetry(null);
298 return;
299 }
300 const retry = workspaceRefreshRetry;
301 if (retry?.key === key && now < retry.notBefore) return;
302 const request = { key, requestedAt: now };
303 workspaceRefreshKeyRef.current = request;
304 const retryLater = () => {
305 if (workspaceRefreshKeyRef.current !== request) return;
306 workspaceRefreshKeyRef.current = null;
307 setWorkspaceRefreshRetry({
308 key,
309 notBefore: Date.now() + WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS,
310 });
311 };
312 void refreshProviders({
313 environmentId,
314 input: { instanceId: selectedProviderInstanceId, cwd: projectCwd },
315 }).then((result) => {
316 const refreshed =
317 result._tag === "Success" &&
318 hasCompleteProviderWorkspaceSnapshot(
319 result.value.providers.find(
320 (provider) => provider.instanceId === selectedProviderInstanceId,
321 ),
322 projectCwd,
323 );
324 if (!refreshed) retryLater();
325 }, retryLater);
326 }, [
327 draftMessage,
328 environmentId,
329 projectCwd,
330 refreshProviders,
331 selectedProviderInstanceId,
332 selectedProviderStatus,
333 workspaceRefreshRetry,
334 ]);
335
336 const trigger = (() => {
337 if (!enabled || selection.start !== selection.end) {
338 return null;
339 }
340 return detectComposerTrigger(draftMessage, selection.end);
341 })();
342 const pathSearch = useComposerPathSearch({
343 environmentId,
344 cwd: trigger?.kind === "path" ? projectCwd : null,
345 query: trigger?.kind === "path" ? trigger.query : null,
346 });
347 const pullRequestSearch = useComposerPullRequestSearch({
348 environmentId,
349 projectId: pullRequestProjectId,
350 repository: pullRequestRepository,
351 threadPullRequests,
352 query: trigger?.kind === "pull-request" ? trigger.query : null,
353 });
354
355 const items = ((): ComposerCommandItem[] => {
356 if (!trigger) return [];
357
358 if (trigger.kind === "pull-request") {
359 return pullRequestSearch.entries.map((entry) => ({
360 id: `pr:${entry.projectId}:${entry.repository}:${entry.number}`,
361 type: "pull-request",
362 pullRequest: {
363 number: entry.number,
364 title: entry.title,
365 url: entry.url,
366 headBranch: entry.headBranch,
367 baseBranch: entry.baseBranch,
368 state: entry.state,
369 isDraft: entry.isDraft,
370 },
371 label: `#${entry.number}`,
372 description: `${entry.isDraft ? "Draft" : entry.state} · ${
373 entry.repository.toLowerCase() === pullRequestRepository?.toLowerCase()
374 ? ""
375 : `${entry.repository} · `
376 }${entry.title}`,
377 }));
378 }
379
380 if (trigger.kind === "slash-command") {
381 const q = trigger.query.toLowerCase();
382 const visibleSkills = getProviderSkillsForSlashMenu(skills, true);
383 const commandItems = buildComposerSlashCommandItems({
384 query: q,
385 atMessageStart: trigger.rangeStart === 0,
386 hasThread,
387 hasCompactableConversation,
388 offersUsageLimits,
389 allowInteractionMode: onUpdateInteractionMode !== undefined,
390 selectedProviderStatus: selectedProviderStatus
391 ? {
392 ...selectedProviderStatus,
393 slashCommands: getProviderSlashCommandsForSlashMenu(
394 resolveProviderSlashCommandsForCwd(selectedProviderStatus, projectCwd),
395 visibleSkills,
396 ),
397 }
398 : null,
399 });
400
401 const skillItems = visibleSkills
402 .filter((skill) => matchesSlashSkillQuery(skill, q))
403 .map((skill) => ({
404 id: `skill:${skill.name}`,
405 type: "skill" as const,
406 skill,
407 label: `skill:${skill.name}`,
408 description: skill.shortDescription ?? skill.description ?? "",
409 }));
410
411 return [...commandItems, ...skillItems];
412 }
413
414 if (trigger.kind === "skill") {
415 const enabledSkills = dedupeProviderSkillsByName(skills.filter(isProviderSkillUserInvocable));
416 const normalizedQuery = normalizeSearchQuery(trigger.query, {
417 trimLeadingPattern: /^\p{Sc}+/u,
418 });
419
420 if (!normalizedQuery) {
421 return enabledSkills.slice(0, 20).map((skill) => ({
422 id: `skill:${skill.name}`,
423 type: "skill" as const,
424 skill,
425 label: skill.displayName ?? skill.name,
426 description: skill.shortDescription ?? skill.description ?? "",
427 }));
428 }
429
430 const ranked: Array<{
431 item: (typeof enabledSkills)[number];
432 score: number;
433 tieBreaker: string;
434 }> = [];
435 for (const skill of enabledSkills) {
436 const displayLabel = (skill.displayName ?? skill.name).toLowerCase();
437 const scores = [
438 scoreQueryMatch({
439 value: skill.name.toLowerCase(),
440 query: normalizedQuery,
441 exactBase: 0,
442 prefixBase: 2,
443 boundaryBase: 4,
444 includesBase: 6,
445 fuzzyBase: 100,
446 boundaryMarkers: ["-", "_", "/"],
447 }),
448 scoreQueryMatch({
449 value: displayLabel,
450 query: normalizedQuery,
451 exactBase: 1,
452 prefixBase: 3,
453 boundaryBase: 5,
454 includesBase: 7,
455 fuzzyBase: 110,
456 }),
457 scoreQueryMatch({
458 value: skill.shortDescription?.toLowerCase() ?? "",
459 query: normalizedQuery,
460 exactBase: 20,
461 prefixBase: 22,
462 boundaryBase: 24,
463 includesBase: 26,
464 }),
465 scoreQueryMatch({
466 value: skill.description?.toLowerCase() ?? "",
467 query: normalizedQuery,
468 exactBase: 30,
469 prefixBase: 32,
470 boundaryBase: 34,
471 includesBase: 36,
472 }),
473 ].filter((score): score is number => score !== null);
474
475 if (scores.length > 0) {
476 insertRankedSearchResult(
477 ranked,
478 {
479 item: skill,
480 score: Math.min(...scores),
481 tieBreaker: `${displayLabel}\u0000${skill.name}`,
482 },
483 20,
484 );
485 }
486 }
487
488 return ranked.map(({ item: skill }) => ({
489 id: `skill:${skill.name}`,
490 type: "skill" as const,
491 skill,
492 label: skill.displayName ?? skill.name,
493 description: skill.shortDescription ?? skill.description ?? "",
494 }));
495 }
496
497 if (trigger.kind === "path") {
498 const threadItems = environmentId
499 ? matchComposerThreadItems({
500 shells: threadShells,
501 environmentId,
502 excludeThreadId: currentThreadId,
503 query: trigger.query,
504 now,
505 })
506 : [];
507 return [
508 ...threadItems,
509 ...pathSearch.entries.map((entry) => {
510 const parts = entry.path.split("/");
511 return {
512 id: `path:${entry.path}`,
513 type: "path" as const,
514 path: entry.path,
515 kind: entry.kind,
516 label: parts[parts.length - 1] ?? entry.path,
517 description: parts.length > 1 ? parts.slice(0, -1).join("/") : "",
518 };
519 }),
520 ];
521 }
522
523 return [];
524 })();
525
526 const onSelect = (item: ComposerCommandItem) => {
527 if (!trigger) return;
528 if (item.type === "thread") {
529 if (!ownerKey || trigger.kind !== "path") return;
530 const shell = threadShells.find(
531 (candidate) =>
532 candidate.environmentId === item.thread.environmentId &&
533 candidate.id === item.thread.threadId,
534 );
535 if (!shell) return;
536 const record = threadComposerContext(item.thread, shell.title);
537 const existing = getComposerDraftSnapshot(ownerKey).context?.records ?? [];
538 const alreadyAttached = existing.some((entry) => entry.contextId === record.contextId);
539 if (!alreadyAttached && existing.length >= COMPOSER_CONTEXT_MAX_RECORDS) {
540 Dialog.alert("Too many context items", "Remove some context from the draft and try again.");
541 return;
542 }
543 const result = replaceTextRange(
544 draftMessage,
545 trigger.rangeStart,
546 trigger.rangeEnd,
547 `${formatComposerContextReference(record)} `,
548 );
549 onChangeDraftMessage(result.text);
550 if (!alreadyAttached) {
551 const draft = getComposerDraftSnapshot(ownerKey);
552 setComposerDraftContext(ownerKey, {
553 version: 1,
554 records: [...(draft.context?.records ?? []), record],
555 });
556 }
557 setSelection({ start: result.cursor, end: result.cursor });
558 return;
559 }
560 if (item.type === "pull-request") {
561 if (
562 !ownerKey ||
563 trigger.kind !== "pull-request" ||
564 !items.some((candidate) => candidate.id === item.id)
565 )
566 return;
567 const record = pullRequestComposerContext(item.pullRequest, uuidv4());
568 if (
569 (getComposerDraftSnapshot(ownerKey).context?.records.length ?? 0) >=
570 COMPOSER_CONTEXT_MAX_RECORDS
571 ) {
572 Dialog.alert("Too many context items", "Remove some context from the draft and try again.");
573 return;
574 }
575 const result = replaceTextRange(
576 draftMessage,
577 trigger.rangeStart,
578 trigger.rangeEnd,
579 `${formatComposerContextReference(record)} `,
580 );
581 onChangeDraftMessage(result.text);
582 const draft = getComposerDraftSnapshot(ownerKey);
583 setComposerDraftContext(ownerKey, {
584 version: 1,
585 records: [...(draft.context?.records ?? []), record],
586 });
587 setSelection({ start: result.cursor, end: result.cursor });
588 return;
589 }
590
591 if (
592 item.type === "provider-slash-command" &&
593 item.command.name === USAGE_LIMITS_COMMAND.name &&
594 onUsageLimits
595 ) {
596 const cleared = replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, "");
597 setSelection({ start: cleared.cursor, end: cleared.cursor });
598 onChangeDraftMessage(cleared.text);
599 onUsageLimits();
600 return;
601 }
602
603 const result = resolveComposerCommandSelection({
604 draftMessage,
605 trigger,
606 item,
607 allowInteractionMode:
608 onUpdateInteractionMode !== undefined &&
609 selectedProviderStatus?.showInteractionModeToggle !== false,
610 });
611 setSelection({ start: result.cursor, end: result.cursor });
612 onChangeDraftMessage(result.text);
613 if (result.interactionMode !== null) {
614 onUpdateInteractionMode?.(result.interactionMode);
615 }
616 };
617
618 return {
619 selection,
620 onSelectionChange,
621 trigger,
622 items,
623 skills,
624 isLoading:
625 trigger?.kind === "pull-request" ? pullRequestSearch.isPending : pathSearch.isPending,
626 error:
627 trigger?.kind === "pull-request"
628 ? pullRequestProjectId === null || pullRequestRepository === null
629 ? "Pull requests are unavailable for this project."
630 : pullRequestSearch.error
631 : null,
632 onSelect,
633 };
634}