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

ComposerCommandMenu.tsx

390 lines13.0 KB

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 } from "gt-react";
28import { memo, 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​
109export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
110 listId: string;
111 items: ComposerCommandItem[];
112 resolvedTheme: "light" | "dark";
113 isLoading: boolean;
114 triggerKind: ComposerTriggerKind | null;
115 emptyStateText?: string;
116 activeItemId: string | null;
117 onHighlightedItemChange: (itemId: string | null) => void;
118 onSelect: (item: ComposerCommandItem) => void;
119}) {
120 const gt = useGT();
121 const m = useMessages();
122 const listRef = useRef<HTMLDivElement>(null);
123 const highlightScrollTopRef = useRef<number | null>(null);
124 const [descriptionDismissed, setDescriptionDismissed] = useState(false);
125 const [highlightedItemId, setHighlightedItemId] = useState(props.activeItemId);
126 if (highlightedItemId !== props.activeItemId) {
127 setHighlightedItemId(props.activeItemId);
128 setDescriptionDismissed(false);
129 }
130​
131 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the highlighted menu item's DOM node into view
132 useLayoutEffect(() => {
133 if (!props.activeItemId || !listRef.current) return;
134 const el = listRef.current.querySelector<HTMLElement>(
135 `[data-composer-item-id="${CSS.escape(props.activeItemId)}"]`,
136 );
137 el?.scrollIntoView({ block: "nearest" });
138 highlightScrollTopRef.current =
139 el?.closest('[data-slot="scroll-area-viewport"]')?.scrollTop ?? null;
140 }, [props.activeItemId]);
141​
142 return (
143 <Command
144 autoHighlight={false}
145 mode="none"
146 onItemHighlighted={(highlightedValue) => {
147 props.onHighlightedItemChange(
148 typeof highlightedValue === "string" ? highlightedValue : null,
149 );
150 }}
151 >
152 <ComposerBanner.Surface
153 ref={listRef}
154 className="flex min-h-0 w-full flex-col overflow-hidden pb-(--chat-composer-attachment-overlap) **:data-[slot=command-item]:rounded-lg **:data-[slot=scroll-area-scrollbar]:data-[orientation=vertical]:my-4"
155 data-composer-command-drawer="true"
156 onScrollCapture={(event) => {
157 // Keeping the highlighted row in view must not close the tooltip it just opened.
158 if (
159 event.target instanceof HTMLElement &&
160 event.target.scrollTop === highlightScrollTopRef.current
161 ) {
162 return;
163 }
164 setDescriptionDismissed(true);
165 }}
166 >
167 {props.items.length > 0 ? (
168 <CommandList
169 id={props.listId}
170 aria-label={
171 props.triggerKind ? m(LISTBOX_LABEL_BY_TRIGGER[props.triggerKind]) : undefined
172 }
173 className="min-h-0 scroll-pb-6"
174 scrollAreaClassName="max-h-72"
175 >
176 <CommandGroup>
177 {props.items.map((item) => (
178 <ComposerCommandMenuItem
179 key={item.id}
180 optionId={composerSuggestionOptionId(props.listId, item.id)}
181 item={item}
182 triggerKind={props.triggerKind}
183 resolvedTheme={props.resolvedTheme}
184 isActive={props.activeItemId === item.id}
185 descriptionDismissed={props.activeItemId === item.id && descriptionDismissed}
186 onHighlight={props.onHighlightedItemChange}
187 onSelect={props.onSelect}
188 />
189 ))}
190 </CommandGroup>
191 </CommandList>
192 ) : (
193 <div className="px-5 pt-3.5 pb-7">
194 <p className="text-secondary-label text-xs">
195 {props.isLoading
196 ? props.triggerKind === "skill" || props.triggerKind === "slash-command"
197 ? gt("Searching workspace skills...")
198 : props.triggerKind === "pull-request"
199 ? gt("Finding pull request...")
200 : gt("Searching workspace files...")
201 : (props.emptyStateText ??
202 (props.triggerKind === "skill"
203 ? gt("No skills found. Try / to browse provider commands.")
204 : props.triggerKind === "path"
205 ? gt("No matching files or folders.")
206 : gt("No matching command.")))}
207 </p>
208 </div>
209 )}
210 </ComposerBanner.Surface>
211 </Command>
212 );
213});
214​
215const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
216 optionId: string;
217 item: ComposerCommandItem;
218 triggerKind: ComposerTriggerKind | null;
219 resolvedTheme: "light" | "dark";
220 isActive: boolean;
221 descriptionDismissed: boolean;
222 onHighlight: (itemId: string | null) => void;
223 onSelect: (item: ComposerCommandItem) => void;
224}) {
225 const m = useMessages();
226 const skillSourceKind =
227 props.item.type === "skill" ? resolveProviderSkillSourceKind(props.item.skill) : null;
228 const isSlashSkill =
229 props.triggerKind === "slash-command" && props.item.type === "skill" ? props.item.skill : null;
230 const pullRequestPresentation =
231 props.item.type === "pull-request" ? resolvePullRequestState(props.item.pullRequest, m) : null;
232 const descriptionRef = useRef<HTMLSpanElement>(null);
233 const [descriptionTruncated, setDescriptionTruncated] = useState(false);
234 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the rendered description so only cut-off text gets a tooltip
235 useLayoutEffect(() => {
236 const description = descriptionRef.current;
237 setDescriptionTruncated(
238 props.isActive && !!description && description.scrollWidth > description.clientWidth,
239 );
240 }, [props.isActive]);
241​
242 return (
243 <CommandItem
244 render={<div id={props.optionId} />}
245 aria-selected={props.isActive}
246 value={props.item.id}
247 data-composer-item-id={props.item.id}
248 active={props.isActive}
249 onMouseMove={() => {
250 if (!props.isActive) props.onHighlight(props.item.id);
251 }}
252 onMouseDown={(event) => {
253 event.preventDefault();
254 }}
255 onClick={() => {
256 props.onSelect(props.item);
257 }}
258 >
259 {props.item.type === "path" ? (
260 <PierreEntryIcon
261 pathValue={props.item.path}
262 kind={props.item.pathKind}
263 theme={props.resolvedTheme}
264 />
265 ) : null}
266 {props.item.type === "thread" ? (
267 <MessagesSquareIcon aria-hidden="true" className="size-4 shrink-0 text-secondary-label" />
268 ) : null}
269 {props.item.type === "environment" ? (
270 <EnvironmentMachineIcon
271 kind={props.item.machine}
272 aria-hidden="true"
273 className="size-4 shrink-0 text-secondary-label"
274 />
275 ) : null}
276 {props.item.type === "model" ? (
277 <ProviderInstanceIcon
278 driverKind={props.item.driverKind}
279 displayName={props.item.providerDisplayName}
280 acpRegistryAgentId={props.item.acpRegistryAgentId}
281 acpRegistryIconUrl={props.item.acpRegistryIconUrl}
282 className="size-4 shrink-0"
283 iconClassName="size-4"
284 />
285 ) : null}
286 {pullRequestPresentation ? (
287 <pullRequestPresentation.Icon
288 role="img"
289 aria-label={pullRequestPresentation.label}
290 className={cn("size-4 shrink-0", pullRequestPresentation.toneClassName)}
291 />
292 ) : null}
293 <span className="flex min-w-0 flex-1 items-center gap-2">
294 <span className="min-w-0 max-w-[45%] shrink-0 truncate font-sans text-xs font-medium">
295 {isSlashSkill ? (
296 <>
297 <span className="text-secondary-label">/skill:</span>
298 {formatProviderSkillDisplayName(isSlashSkill)}
299 </>
300 ) : (
301 props.item.label
302 )}
303 </span>
304 <Tooltip open={descriptionTruncated && !props.descriptionDismissed}>
305 <TooltipTrigger
306 tabIndex={-1}
307 render={
308 <span
309 ref={descriptionRef}
310 className="min-w-0 flex-1 truncate text-left text-secondary-label text-xs"
311 />
312 }
313 >
314 {props.item.description}
315 </TooltipTrigger>
316 <TooltipPopup>{props.item.description}</TooltipPopup>
317 </Tooltip>
318 {skillSourceKind ? (
319 <SkillSourceBadge
320 kind={skillSourceKind}
321 showSkillSuffix={props.triggerKind === "skill"}
322 />
323 ) : null}
324 </span>
325 </CommandItem>
326 );
327});
328​
329export function composerSuggestionOptionId(listId: string, itemId: string): string {
330 // JSON escapes lone UTF-16 surrogates before URI encoding without losing identity.
331 return `${listId}-${encodeURIComponent(JSON.stringify(itemId))}`;
333​
334const LISTBOX_LABEL_BY_TRIGGER: Record<ComposerTriggerKind, string> = {
335 path: msg("Files and folders"),
336 "pull-request": msg("Pull requests"),
337 "slash-command": msg("Commands"),
338 skill: msg("Skills"),
339};
340​
341const SKILL_SOURCE_ICON_BY_KIND: Record<ProviderSkillSourceKind, LucideIcon> = {
342 app: BlocksIcon,
343 repo: FolderIcon,
344 project: FolderIcon,
345 personal: UserRoundIcon,
346 system: SettingsIcon,
347 other: PackageIcon,
348};
349​
350const SKILL_SOURCE_LABEL_BY_KIND: Record<
351 ProviderSkillSourceKind,
352 { readonly label: string; readonly skillLabel: string }
353> = {
354 app: {
355 label: msg("App", { $context: "skill source badge" }),
356 skillLabel: msg("App Skill"),
357 },
358 repo: {
359 label: msg("Repo", { $context: "skill source badge" }),
360 skillLabel: msg("Repo Skill"),
361 },
362 project: {
363 label: msg("Project", { $context: "skill source badge" }),
364 skillLabel: msg("Project Skill"),
365 },
366 personal: {
367 label: msg("Personal", { $context: "skill source badge" }),
368 skillLabel: msg("Personal Skill"),
369 },
370 system: {
371 label: msg("System", { $context: "skill source badge" }),
372 skillLabel: msg("System Skill"),
373 },
374 other: {
375 label: msg("Provider", { $context: "skill source badge" }),
376 skillLabel: msg("Provider Skill"),
377 },
378};
379​
380function SkillSourceBadge(props: { kind: ProviderSkillSourceKind; showSkillSuffix: boolean }) {
381 const m = useMessages();
382 const Icon = SKILL_SOURCE_ICON_BY_KIND[props.kind];
383 const labels = SKILL_SOURCE_LABEL_BY_KIND[props.kind];
384 return (
385 <Badge className="ms-auto" variant="secondary">
386 <Icon aria-hidden="true" className="text-current" />
387 {m(props.showSkillSuffix ? labels.skillLabel : labels.label)}
388 </Badge>
389 );