Open History to see the last commit
1import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";
2import type { ComposerPathSearchTarget } from "@t3tools/client-runtime/state/threads";
3import {
4 resolveProviderSkillSourceKind,
5 type ProviderSkillSourceKind,
6} from "@t3tools/client-runtime/providerSkills";
7import {
8 type EnvironmentId,
9 type EnvironmentMachineKind,
10 type ProjectEntry,
11 type ProviderDriverKind,
12 type ProviderInstanceId,
13 type PullRequestContextMetadata,
14 type ScopedThreadRef,
15 type ServerProviderSkill,
16 type ServerProviderSlashCommand,
17} from "@t3tools/contracts";
18import {
19 BlocksIcon,
20 FolderIcon,
21 MessagesSquareIcon,
22 PackageIcon,
23 SettingsIcon,
24 UserRoundIcon,
25 type LucideIcon,
26} from "lucide-react";
27import { msg, useGT, useMessages, type Msg } from "gt-react";
28import { memo, useEffect, useLayoutEffect, useRef, useState } from "react";
29
30import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic";
31import { cn } from "~/lib/utils";
32import { Badge } from "../ui/badge";
33import { Command, CommandGroup, CommandItem, CommandList } from "../ui/command";
34import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
35import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
36import { PierreEntryIcon } from "./PierreEntryIcon";
37import { ProviderInstanceIcon } from "./ProviderInstanceIcon";
38import { ComposerBanner } from "./ComposerBanner";
39import { resolvePullRequestState } from "../pullRequest/pullRequestPresentation";
40
41export type ComposerCommandItem =
42 | {
43 id: string;
44 type: "path";
45 path: string;
46 pathKind: ProjectEntry["kind"];
47 searchTarget: ComposerPathSearchTarget;
48 label: string;
49 description: string;
50 }
51 | {
52 id: string;
53 type: "slash-command";
54 command: ComposerSlashCommand;
55 label: string;
56 description: string;
57 }
58 | {
59 id: string;
60 type: "provider-slash-command";
61 provider: ProviderDriverKind;
62 command: ServerProviderSlashCommand;
63 label: string;
64 description: string;
65 }
66 | {
67 id: string;
68 type: "skill";
69 provider: ProviderDriverKind;
70 skill: ServerProviderSkill;
71 label: string;
72 description: string;
73 }
74 | {
75 id: string;
76 type: "pull-request";
77 pullRequest: PullRequestContextMetadata;
78 label: string;
79 description: string;
80 }
81 | {
82 id: string;
83 type: "thread";
84 thread: ScopedThreadRef;
85 label: string;
86 description: string;
87 }
88 | {
89 id: string;
90 type: "environment";
91 environmentId: EnvironmentId;
92 machine: EnvironmentMachineKind;
93 label: string;
94 description: string;
95 }
96 | {
97 id: string;
98 type: "model";
99 instanceId: ProviderInstanceId;
100 model: string;
101 driverKind: ProviderDriverKind;
102 providerDisplayName: string;
103 acpRegistryAgentId: string | undefined;
104 acpRegistryIconUrl: string | undefined;
105 label: string;
106 description: string;
107 };
108
109const HIDDEN_BY_MODAL = '[aria-hidden="true"], [inert]';
110
111function isOwnFocusTarget(list: HTMLElement, listId: string, node: EventTarget | null) {
112 return (
113 node instanceof Element &&
114 (list.contains(node) || node.closest(`[aria-controls="${CSS.escape(listId)}"]`) !== null)
115 );
116}
117
118export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
119 listId: string;
120 items: ComposerCommandItem[];
121 resolvedTheme: "light" | "dark";
122 isLoading: boolean;
123 triggerKind: ComposerTriggerKind | null;
124 emptyStateText?: string;
125 activeItemId: string | null;
126 onHighlightedItemChange: (itemId: string | null) => void;
127 onSelect: (item: ComposerCommandItem) => void;
128}) {
129 const gt = useGT();
130 const m = useMessages();
131 const listRef = useRef<HTMLDivElement>(null);
132 const highlightScrollTopRef = useRef<number | null>(null);
133 const previousActiveItemIdRef = useRef(props.activeItemId);
134 const [descriptionDismissed, setDescriptionDismissed] = useState(false);
135 const [highlightedItemId, setHighlightedItemId] = useState(props.activeItemId);
136 if (highlightedItemId !== props.activeItemId) {
137 setHighlightedItemId(props.activeItemId);
138 setDescriptionDismissed(false);
139 }
140
141 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the highlighted menu item's DOM node into view
142 useLayoutEffect(() => {
143 if (!props.activeItemId || !listRef.current) return;
144 const el = listRef.current.querySelector<HTMLElement>(
145 `[data-composer-item-id="${CSS.escape(props.activeItemId)}"]`,
146 );
147 el?.scrollIntoView({ block: "nearest" });
148 highlightScrollTopRef.current =
149 el?.closest('[data-slot="scroll-area-viewport"]')?.scrollTop ?? null;
150 }, [props.activeItemId]);
151
152 // Passive so the editor has published aria-controls for the new highlight in its own layout effect.
153 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a highlight that arrives while focus is elsewhere keeps its tooltip closed
154 useEffect(() => {
155 const list = listRef.current;
156 const arrived = previousActiveItemIdRef.current === null;
157 previousActiveItemIdRef.current = props.activeItemId;
158 if (!arrived || !props.activeItemId || !list) return;
159 if (!isOwnFocusTarget(list, props.listId, list.ownerDocument.activeElement)) {
160 setDescriptionDismissed(true);
161 }
162 }, [props.activeItemId, props.listId]);
163
164 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a modal or outside focus must close the portaled tooltip too
165 useEffect(() => {
166 const list = listRef.current;
167 if (!list) return;
168 const doc = list.ownerDocument;
169 const isOwn = (node: EventTarget | null) => isOwnFocusTarget(list, props.listId, node);
170 const ac = new AbortController();
171 const onFocusIn = (event: FocusEvent) => {
172 if (!isOwn(event.target) || list.closest(HIDDEN_BY_MODAL)) return;
173 const vp = list.querySelector<HTMLElement>('[data-slot="scroll-area-viewport"]');
174 if (!vp || vp.scrollTop === highlightScrollTopRef.current) setDescriptionDismissed(false);
175 };
176 const onFocusOut = (event: FocusEvent) => {
177 if (isOwn(event.target) && !isOwn(event.relatedTarget)) setDescriptionDismissed(true);
178 };
179 const observer = new MutationObserver(() => {
180 if (list.closest(HIDDEN_BY_MODAL)) setDescriptionDismissed(true);
181 });
182 observer.observe(doc.body, {
183 subtree: true,
184 attributes: true,
185 attributeFilter: ["aria-hidden", "inert"],
186 });
187 doc.addEventListener("focusin", onFocusIn, { capture: true, signal: ac.signal });
188 doc.addEventListener("focusout", onFocusOut, { capture: true, signal: ac.signal });
189 return () => {
190 observer.disconnect();
191 ac.abort();
192 };
193 }, [props.listId]);
194
195 return (
196 <Command
197 autoHighlight={false}
198 mode="none"
199 onItemHighlighted={(highlightedValue) => {
200 props.onHighlightedItemChange(
201 typeof highlightedValue === "string" ? highlightedValue : null,
202 );
203 }}
204 >
205 <ComposerBanner.Surface
206 ref={listRef}
207 className="flex min-h-0 w-full flex-col overflow-hidden pb-(--chat-composer-attachment-overlap) **:data-[slot=scroll-area-scrollbar]:data-[orientation=vertical]:my-4"
208 data-composer-command-drawer="true"
209 onScrollCapture={(event) => {
210 // Keeping the highlighted row in view must not close the tooltip it just opened.
211 if (
212 event.target instanceof HTMLElement &&
213 event.target.scrollTop === highlightScrollTopRef.current
214 ) {
215 return;
216 }
217 setDescriptionDismissed(true);
218 }}
219 >
220 {props.items.length > 0 ? (
221 <CommandList
222 id={props.listId}
223 aria-label={
224 props.triggerKind ? m(LISTBOX_LABEL_BY_TRIGGER[props.triggerKind]) : undefined
225 }
226 className="min-h-0 scroll-pb-6"
227 scrollAreaClassName="max-h-72"
228 >
229 <CommandGroup>
230 {props.items.map((item) => (
231 <ComposerCommandMenuItem
232 key={item.id}
233 optionId={composerSuggestionOptionId(props.listId, item.id)}
234 item={item}
235 triggerKind={props.triggerKind}
236 resolvedTheme={props.resolvedTheme}
237 isActive={props.activeItemId === item.id}
238 descriptionDismissed={props.activeItemId === item.id && descriptionDismissed}
239 onDescriptionDismissedChange={setDescriptionDismissed}
240 onHighlight={props.onHighlightedItemChange}
241 onSelect={props.onSelect}
242 />
243 ))}
244 </CommandGroup>
245 </CommandList>
246 ) : (
247 <div className="px-5 pt-3.5 pb-7">
248 <p className="text-secondary-label text-xs">
249 {props.isLoading
250 ? props.triggerKind === "skill" || props.triggerKind === "slash-command"
251 ? gt`Searching workspace skills...`
252 : props.triggerKind === "pull-request"
253 ? gt`Finding pull request...`
254 : gt`Searching workspace files...`
255 : (props.emptyStateText ??
256 (props.triggerKind === "skill"
257 ? gt`No skills found. Try / to browse provider commands.`
258 : props.triggerKind === "path"
259 ? gt`No matching files or folders.`
260 : gt`No matching command.`))}
261 </p>
262 </div>
263 )}
264 </ComposerBanner.Surface>
265 </Command>
266 );
267});
268
269const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
270 optionId: string;
271 item: ComposerCommandItem;
272 triggerKind: ComposerTriggerKind | null;
273 resolvedTheme: "light" | "dark";
274 isActive: boolean;
275 descriptionDismissed: boolean;
276 onDescriptionDismissedChange: (dismissed: boolean) => void;
277 onHighlight: (itemId: string | null) => void;
278 onSelect: (item: ComposerCommandItem) => void;
279}) {
280 const m = useMessages();
281 const skillSourceKind =
282 props.item.type === "skill" ? resolveProviderSkillSourceKind(props.item.skill) : null;
283 const isSlashSkill =
284 props.triggerKind === "slash-command" && props.item.type === "skill" ? props.item.skill : null;
285 const pullRequestPresentation =
286 props.item.type === "pull-request" ? resolvePullRequestState(props.item.pullRequest, m) : null;
287 const descriptionRef = useRef<HTMLSpanElement>(null);
288 const [descriptionTruncated, setDescriptionTruncated] = useState(false);
289 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the rendered description so only cut-off text gets a tooltip
290 useLayoutEffect(() => {
291 const description = descriptionRef.current;
292 setDescriptionTruncated(
293 props.isActive && !!description && description.scrollWidth > description.clientWidth,
294 );
295 }, [props.isActive]);
296
297 return (
298 <CommandItem
299 render={<div id={props.optionId} />}
300 aria-selected={props.isActive}
301 value={props.item.id}
302 data-composer-item-id={props.item.id}
303 active={props.isActive}
304 onMouseMove={() => {
305 if (!props.isActive) props.onHighlight(props.item.id);
306 }}
307 onMouseEnter={() => {
308 if (props.isActive) props.onDescriptionDismissedChange(false);
309 }}
310 onMouseLeave={() => {
311 if (props.isActive) props.onDescriptionDismissedChange(true);
312 }}
313 onMouseDown={(event) => {
314 event.preventDefault();
315 }}
316 onClick={() => {
317 props.onSelect(props.item);
318 }}
319 >
320 {props.item.type === "path" ? (
321 <PierreEntryIcon
322 pathValue={props.item.path}
323 kind={props.item.pathKind}
324 theme={props.resolvedTheme}
325 />
326 ) : null}
327 {props.item.type === "thread" ? (
328 <MessagesSquareIcon aria-hidden="true" className="size-4 shrink-0 text-secondary-label" />
329 ) : null}
330 {props.item.type === "environment" ? (
331 <EnvironmentMachineIcon
332 kind={props.item.machine}
333 aria-hidden="true"
334 className="size-4 shrink-0 text-secondary-label"
335 />
336 ) : null}
337 {props.item.type === "model" ? (
338 <ProviderInstanceIcon
339 driverKind={props.item.driverKind}
340 displayName={props.item.providerDisplayName}
341 acpRegistryAgentId={props.item.acpRegistryAgentId}
342 acpRegistryIconUrl={props.item.acpRegistryIconUrl}
343 className="size-4 shrink-0"
344 iconClassName="size-4"
345 />
346 ) : null}
347 {pullRequestPresentation ? (
348 <pullRequestPresentation.Icon
349 role="img"
350 aria-label={pullRequestPresentation.label}
351 className={cn("size-4 shrink-0", pullRequestPresentation.toneClassName)}
352 />
353 ) : null}
354 <span className="flex min-w-0 flex-1 items-center gap-2">
355 <span className="min-w-0 max-w-[45%] shrink-0 truncate font-sans text-xs font-medium">
356 {isSlashSkill ? (
357 <>
358 <span className="text-secondary-label">/skill:</span>
359 {formatProviderSkillDisplayName(isSlashSkill)}
360 </>
361 ) : (
362 props.item.label
363 )}
364 </span>
365 <Tooltip open={descriptionTruncated && !props.descriptionDismissed}>
366 <TooltipTrigger
367 tabIndex={-1}
368 render={
369 <span
370 ref={descriptionRef}
371 className="min-w-0 flex-1 truncate text-left text-secondary-label text-xs"
372 />
373 }
374 >
375 {props.item.description}
376 </TooltipTrigger>
377 <TooltipPopup>{props.item.description}</TooltipPopup>
378 </Tooltip>
379 {skillSourceKind ? (
380 <SkillSourceBadge
381 kind={skillSourceKind}
382 showSkillSuffix={props.triggerKind === "skill"}
383 />
384 ) : null}
385 </span>
386 </CommandItem>
387 );
388});
389
390export function composerSuggestionOptionId(listId: string, itemId: string): string {
391 // JSON escapes lone UTF-16 surrogates before URI encoding without losing identity.
392 return `${listId}-${encodeURIComponent(JSON.stringify(itemId))}`;
393}
394
395const LISTBOX_LABEL_BY_TRIGGER: Record<ComposerTriggerKind, string> = {
396 path: msg("Files and folders"),
397 "pull-request": msg("Pull requests"),
398 "slash-command": msg("Commands"),
399 skill: msg("Skills"),
400};
401
402const SKILL_SOURCE_ICON_BY_KIND: Record<ProviderSkillSourceKind, LucideIcon> = {
403 app: BlocksIcon,
404 repo: FolderIcon,
405 project: FolderIcon,
406 personal: UserRoundIcon,
407 system: SettingsIcon,
408 other: PackageIcon,
409};
410
411const SKILL_SOURCE_LABEL_BY_KIND: Record<
412 ProviderSkillSourceKind,
413 { readonly label: string | Msg; readonly skillLabel: string }
414> = {
415 app: {
416 label: msg({ context: "skill source badge" })`App`,
417 skillLabel: msg("App Skill"),
418 },
419 repo: {
420 label: msg({ context: "skill source badge" })`Repo`,
421 skillLabel: msg("Repo Skill"),
422 },
423 project: {
424 label: msg({ context: "skill source badge" })`Project`,
425 skillLabel: msg("Project Skill"),
426 },
427 personal: {
428 label: msg({ context: "skill source badge" })`Personal`,
429 skillLabel: msg("Personal Skill"),
430 },
431 system: {
432 label: msg({ context: "skill source badge" })`System`,
433 skillLabel: msg("System Skill"),
434 },
435 other: {
436 label: msg({ context: "skill source badge" })`Provider`,
437 skillLabel: msg("Provider Skill"),
438 },
439};
440
441function SkillSourceBadge(props: { kind: ProviderSkillSourceKind; showSkillSuffix: boolean }) {
442 const m = useMessages();
443 const Icon = SKILL_SOURCE_ICON_BY_KIND[props.kind];
444 const labels = SKILL_SOURCE_LABEL_BY_KIND[props.kind];
445 return (
446 <Badge className="ms-auto" variant="secondary">
447 <Icon aria-hidden="true" className="text-current" />
448 {m(props.showSkillSuffix ? labels.skillLabel : labels.label)}
449 </Badge>
450 );
451}