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