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

useComposerMenuItems.ts

433 lines16.8 KB

1import {
2 legacyThreadPullRequestKey,
3 threadPullRequestKeyOf,
4} from "@t3tools/client-runtime/thread-pull-requests";
5import {
6 matchComposerEnvironmentItems,
7 matchComposerThreadItems,
8} from "@t3tools/client-runtime/composerThreadItems";
9import { useAtomValue } from "@effect/atom-react";
10import { useState } from "react";
11import type {
12 EnvironmentId,
13 ProjectId,
14 ProviderDriverKind,
15 ProviderInstanceId,
16 PullRequestListInput,
17 ServerProvider,
18 ThreadId,
19 ThreadPullRequestLink,
20} from "@t3tools/contracts";
21import {
22 composerPullRequestsFromLinks,
23 filterComposerPullRequestMatches,
24 withLinkedComposerPullRequestsFirst,
25} from "@t3tools/shared/composerPullRequestMatches";
26import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";
27​
28import type { ComposerTrigger } from "../../composer-logic";
29import type { DraftId } from "../../composerDraftStore";
30import { basenameOfPath } from "../../pierre-icons";
31import {
32 getProviderSkillsForSlashMenu,
33 getProviderSlashCommandsForSlashMenu,
34} from "@t3tools/client-runtime/providerSkills";
35import { searchProviderSkills } from "../../providerSkillSearch";
36import { useVisibleThreadShells } from "~/state/entities";
37import { useEnvironmentIdentities, useEnvironmentMachines } from "~/state/environments";
38import { offersLinkedEnvironmentsAtom } from "~/state/peerLinks";
39import {
40 pullRequestEnvironment,
41 usePullRequestList,
42 type EnvironmentQueryTarget,
43} from "~/state/pullRequests";
44import { useEnvironmentQuery } from "~/state/query";
45import { useComposerPathSearch, useDebouncedValue, useThreadSearch } from "~/state/queries";
46import {
47 matchesPullRequestQuery,
48 rankPullRequestMatches,
49} from "../pullRequest/pullRequestList.logic";
50import type { ComposerCommandItem } from "./ComposerCommandMenu";
51import { matchComposerModelItems } from "./composerModelMentions";
52import type { ModelEsque } from "./providerIconUtils";
53import type { ProviderInstanceEntry } from "../../providerInstances";
54import {
55 searchSlashCommandItems,
56 slashCommandItemsForPromptPosition,
57} from "./composerSlashCommandSearch";
58​
59const COMPOSER_PULL_REQUEST_LIST_LIMIT = 99;
60const COMPOSER_PULL_REQUEST_RESULT_LIMIT = 12;
61const EMPTY_PULL_REQUEST_LIST_TARGETS: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>> =
62 [];
63​
64/** Builds the @, /, $ and # suggestion lists, running the searches each trigger needs. */
65export function useComposerMenuItems({
66 composerTrigger,
67 environmentId,
68 linkedEnvironments,
69 gitCwd,
70 activeThreadId,
71 pullRequestProjectId,
72 pullRequestRepository,
73 threadPullRequests,
74 sideChatAvailable,
75 sideChatDisabledReason,
76 freshSessionAvailable,
77 compactSlashCommandAvailable,
78 selectedProvider,
79 selectedProviderSkills,
80 selectedProviderSlashCommands,
81 showSkillsInSlashMenu,
82 workspaceSkillsScanning,
83 questionAttachmentTarget,
84 modelMentions,
85}: {
86 readonly composerTrigger: ComposerTrigger | null;
87 readonly environmentId: EnvironmentId;
88 readonly linkedEnvironments: ReadonlyMap<EnvironmentId, string>;
89 readonly gitCwd: string | null;
90 readonly activeThreadId: ThreadId | null;
91 readonly pullRequestProjectId: ProjectId | null;
92 readonly pullRequestRepository: string | null;
93 readonly threadPullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined;
94 readonly sideChatAvailable: boolean;
95 readonly sideChatDisabledReason: string | null;
96 readonly freshSessionAvailable: boolean;
97 readonly compactSlashCommandAvailable: boolean;
98 readonly selectedProvider: ProviderDriverKind;
99 readonly selectedProviderSkills: ServerProvider["skills"];
100 readonly selectedProviderSlashCommands: ServerProvider["slashCommands"];
101 readonly showSkillsInSlashMenu: boolean;
102 readonly workspaceSkillsScanning: boolean;
103 readonly questionAttachmentTarget: DraftId | null;
104 readonly modelMentions: {
105 readonly instanceEntries: ReadonlyArray<ProviderInstanceEntry>;
106 readonly modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>;
107 };
108}) {
109 // Thread mentions rank by recency as of when the composer mounted.
110 const [now] = useState(() => Date.now());
111 const composerTriggerKind = composerTrigger?.kind ?? null;
112 const pathTriggerQuery = composerTrigger?.kind === "path" ? composerTrigger.query : "";
113 const pullRequestTriggerQuery =
114 composerTrigger?.kind === "pull-request" ? composerTrigger.query : "";
115 const pullRequestTextQuery =
116 composerTriggerKind === "pull-request" &&
117 pullRequestTriggerQuery.length > 0 &&
118 !/^\d+$/u.test(pullRequestTriggerQuery)
119 ? pullRequestTriggerQuery
120 : null;
121 const debouncedPullRequestTextQuery = useDebouncedValue(pullRequestTextQuery, 180);
122 const settledPullRequestTextQuery =
123 pullRequestTextQuery === debouncedPullRequestTextQuery ? pullRequestTextQuery : null;
124 const isPathTrigger = composerTriggerKind === "path";
125 const environmentThreadShells = useVisibleThreadShells(isPathTrigger);
126 // Mounts older settled threads matching the mention, which shells may leave out.
127 useThreadSearch(isPathTrigger ? [environmentId] : [], pathTriggerQuery, { titlesOnly: true });
128 // The user's machines feed `@` machine matches; the catalog summary is cheap and stable.
129 const environmentIdentities = useEnvironmentIdentities();
130 const environmentMachines = useEnvironmentMachines();
131 const offersMachines = useAtomValue(offersLinkedEnvironmentsAtom(environmentId));
132 const mentionableEnvironments = environmentIdentities.map((identity) => ({
133 ...identity,
134 machine: environmentMachines.get(identity.environmentId) ?? ("server" as const),
135 }));
136 const workspaceEntries = useComposerPathSearch({
137 environmentId,
138 cwd: isPathTrigger ? gitCwd : null,
139 query: isPathTrigger ? pathTriggerQuery : null,
140 });
141​
142 const pullRequestListTargets =
143 composerTriggerKind !== "pull-request" ||
144 pullRequestProjectId === null ||
145 (pullRequestTextQuery !== null && settledPullRequestTextQuery === null)
146 ? EMPTY_PULL_REQUEST_LIST_TARGETS
147 : [
148 {
149 environmentId,
150 input: {
151 state: "all" as const,
152 projectId: pullRequestProjectId,
153 limit: COMPOSER_PULL_REQUEST_LIST_LIMIT,
154 ...(settledPullRequestTextQuery === null
155 ? {}
156 : { query: settledPullRequestTextQuery }),
157 },
158 },
159 ];
160 const pullRequestLookup = usePullRequestList(pullRequestListTargets);
161 const pullRequestTriggerNumber = (() => {
162 if (composerTrigger?.kind !== "pull-request" || composerTrigger.query.length === 0) {
163 return null;
164 }
165 const number = Number(composerTrigger.query);
166 return Number.isSafeInteger(number) && number > 0 ? number : null;
167 })();
168 const debouncedPullRequestNumber = useDebouncedValue(pullRequestTriggerNumber, 180);
169 const settledPullRequestNumber =
170 pullRequestTriggerNumber === debouncedPullRequestNumber ? pullRequestTriggerNumber : null;
171 const recentHasExactPullRequest =
172 settledPullRequestNumber !== null &&
173 pullRequestLookup.data?.entries.some(
174 (entry) =>
175 entry.projectId === pullRequestProjectId &&
176 entry.repository.trim().toLowerCase() === pullRequestRepository?.trim().toLowerCase() &&
177 entry.number === settledPullRequestNumber,
178 ) === true;
179 const exactPullRequestLookup = useEnvironmentQuery(
180 settledPullRequestNumber === null ||
181 pullRequestProjectId === null ||
182 pullRequestRepository === null ||
183 recentHasExactPullRequest
184 ? null
185 : pullRequestEnvironment.detail({
186 environmentId,
187 input: {
188 projectId: pullRequestProjectId,
189 repository: pullRequestRepository,
190 number: settledPullRequestNumber,
191 },
192 }),
193 );
194​
195 const linkedPullRequests =
196 pullRequestProjectId === null
197 ? []
198 : composerPullRequestsFromLinks(threadPullRequests ?? [], pullRequestProjectId);
199​
200 const items = ((): ComposerCommandItem[] => {
201 if (!composerTrigger) return [];
202 if (composerTrigger.kind === "path") {
203 return [
204 ...matchComposerThreadItems({
205 shells: environmentThreadShells,
206 environmentId,
207 linkedEnvironments,
208 excludeThreadId: activeThreadId,
209 query: composerTrigger.query,
210 now,
211 }),
212 // An answer to an agent's question carries thread links, not machines.
213 ...(questionAttachmentTarget === null && offersMachines
214 ? matchComposerEnvironmentItems({
215 environments: mentionableEnvironments,
216 environmentId,
217 query: composerTrigger.query,
218 })
219 : []),
220 ...matchComposerModelItems({
221 instanceEntries: modelMentions.instanceEntries,
222 modelOptionsByInstance: modelMentions.modelOptionsByInstance,
223 query: composerTrigger.query,
224 }),
225 ...workspaceEntries.entries.map((entry) => ({
226 id: `path:${entry.kind}:${entry.path}`,
227 type: "path" as const,
228 path: entry.path,
229 pathKind: entry.kind,
230 searchTarget: workspaceEntries.searchedTarget,
231 label: basenameOfPath(entry.path),
232 description: entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))),
233 })),
234 ];
235 }
236 if (composerTrigger.kind === "slash-command") {
237 const builtInSlashCommandItems = [
238 {
239 id: "slash:model",
240 type: "slash-command",
241 command: "model",
242 label: "/model",
243 description: "Switch response model for this thread",
244 },
245 ...(sideChatAvailable
246 ? ([
247 {
248 id: "slash:side",
249 type: "slash-command",
250 command: "side",
251 label: "/side",
252 description: sideChatDisabledReason ?? "Ask a side question in a new side chat",
253 },
254 {
255 id: "slash:btw",
256 type: "slash-command",
257 command: "btw",
258 label: "/btw",
259 description: sideChatDisabledReason ?? "Same as /side",
260 },
261 ] as const)
262 : []),
263 ...(freshSessionAvailable
264 ? ([
265 {
266 id: "slash:clear",
267 type: "slash-command",
268 command: "clear",
269 label: "/clear",
270 description: "Start a fresh session; earlier messages stay visible",
271 },
272 ] as const)
273 : []),
274 ] satisfies ReadonlyArray<Extract<ComposerCommandItem, { type: "slash-command" }>>;
275 const slashMenuSkills = getProviderSkillsForSlashMenu(
276 selectedProviderSkills,
277 showSkillsInSlashMenu,
278 );
279 const providerSlashCommandItems = getProviderSlashCommandsForSlashMenu(
280 selectedProviderSlashCommands,
281 slashMenuSkills,
282 ).map((command) => ({
283 id: `provider-slash-command:${selectedProvider}:${command.name}`,
284 type: "provider-slash-command" as const,
285 provider: selectedProvider,
286 command,
287 label: `/${command.name}`,
288 description: command.description ?? command.input?.hint ?? "Run provider command",
289 }));
290 const query = composerTrigger.query.trim().toLowerCase();
291 const skillItems = slashMenuSkills.map((skill) => ({
292 id: `skill:${selectedProvider}:${skill.name}`,
293 type: "skill" as const,
294 provider: selectedProvider,
295 skill,
296 label: `/skill:${skill.name}`,
297 description:
298 skill.shortDescription ??
299 skill.description ??
300 (skill.scope ? `${skill.scope} skill` : ""),
301 }));
302 // T3's `/clear` replaces the provider's, which would clear a session T3 still treats as live.
303 const visibleProviderSlashCommandItems = providerSlashCommandItems.filter(
304 (item) =>
305 (item.command.name !== "compact" || compactSlashCommandAvailable) &&
306 (item.command.name !== "clear" || !freshSessionAvailable),
307 );
308 const slashCommandItems = slashCommandItemsForPromptPosition(
309 [...builtInSlashCommandItems, ...visibleProviderSlashCommandItems, ...skillItems],
310 composerTrigger.rangeStart === 0,
311 );
312 return searchSlashCommandItems(slashCommandItems, query);
313 }
314 if (composerTrigger.kind === "skill") {
315 return searchProviderSkills(selectedProviderSkills, composerTrigger.query).map((skill) => ({
316 id: `skill:${selectedProvider}:${skill.name}`,
317 type: "skill" as const,
318 provider: selectedProvider,
319 skill,
320 label: formatProviderSkillDisplayName(skill),
321 description:
322 skill.shortDescription ??
323 skill.description ??
324 (skill.scope ? `${skill.scope} skill` : "Run provider skill"),
325 }));
326 }
327 if (
328 composerTrigger.kind === "pull-request" &&
329 pullRequestProjectId !== null &&
330 pullRequestRepository !== null
331 ) {
332 const exactPullRequest =
333 exactPullRequestLookup.data?.number === pullRequestTriggerNumber
334 ? [
335 {
336 ...exactPullRequestLookup.data,
337 // Only the host: the URL's full repository path would not match the project's selector.
338 host: legacyThreadPullRequestKey(exactPullRequestLookup.data).host,
339 },
340 ]
341 : [];
342 const matches = /^\d*$/u.test(composerTrigger.query)
343 ? filterComposerPullRequestMatches({
344 keyOf: threadPullRequestKeyOf,
345 entries: [...exactPullRequest, ...(pullRequestLookup.data?.entries ?? [])],
346 linked: linkedPullRequests,
347 projectId: pullRequestProjectId,
348 repository: pullRequestRepository,
349 query: composerTrigger.query,
350 limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT,
351 })
352 : withLinkedComposerPullRequestsFirst({
353 keyOf: threadPullRequestKeyOf,
354 matches: rankPullRequestMatches(
355 (pullRequestLookup.data?.entries ?? []).filter((entry) => {
356 if (
357 entry.projectId !== pullRequestProjectId ||
358 entry.repository.trim().toLowerCase() !==
359 pullRequestRepository.trim().toLowerCase()
360 ) {
361 return false;
362 }
363 const provider = pullRequestLookup.data?.providers.find(
364 (candidate) => candidate.host === entry.host,
365 );
366 return (
367 provider?.searchesOnHost === true ||
368 matchesPullRequestQuery(entry, composerTrigger.query)
369 );
370 }),
371 composerTrigger.query,
372 ),
373 linked: linkedPullRequests,
374 query: composerTrigger.query,
375 limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT,
376 });
377 return matches.map((pullRequest) => ({
378 id: `pull-request:${pullRequest.projectId}:${threadPullRequestKeyOf(pullRequest)}`,
379 type: "pull-request",
380 pullRequest: {
381 number: pullRequest.number,
382 title: pullRequest.title,
383 url: pullRequest.url,
384 headBranch: pullRequest.headBranch,
385 baseBranch: pullRequest.baseBranch,
386 state: pullRequest.state,
387 isDraft: pullRequest.isDraft,
388 },
389 label: `#${pullRequest.number}`,
390 description:
391 pullRequest.repository.trim().toLowerCase() === pullRequestRepository.trim().toLowerCase()
392 ? pullRequest.title
393 : `${pullRequest.repository} · ${pullRequest.title}`,
394 }));
395 }
396 return [];
397 })();
398 const isLoading =
399 (composerTriggerKind === "path" && pathTriggerQuery.length > 0 && workspaceEntries.isPending) ||
400 ((composerTriggerKind === "skill" || composerTriggerKind === "slash-command") &&
401 workspaceSkillsScanning) ||
402 (composerTriggerKind === "pull-request" &&
403 pullRequestProjectId !== null &&
404 pullRequestRepository !== null &&
405 (pullRequestLookup.isPending ||
406 pullRequestTextQuery !== debouncedPullRequestTextQuery ||
407 pullRequestTriggerNumber !== debouncedPullRequestNumber ||
408 exactPullRequestLookup.isPending));
409 const emptyState = (() => {
410 if (composerTriggerKind === "skill") {
411 return "No skills found. Try / to browse provider commands.";
412 }
413 if (composerTriggerKind === "pull-request") {
414 if (pullRequestProjectId === null || pullRequestRepository === null) {
415 return "Pull requests are not available for this project.";
416 }
417 if (
418 pullRequestLookup.error !== null ||
419 pullRequestLookup.data?.errors.some((error) => error.projectId === pullRequestProjectId)
420 ) {
421 return "Pull requests could not be read for this project.";
422 }
423 return composerTrigger?.query
424 ? `No pull request matches ${composerTrigger.query}.`
425 : "No pull requests found in this repository.";
426 }
427 return composerTriggerKind === "path"
428 ? "No matching files or folders."
429 : "No matching command.";
430 })();
431​
432 return { items, isLoading, emptyState };