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

useComposerMenuItems.ts

385 lines14.8 KB

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