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

useComposerMenuItems.ts

411 lines15.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 { useVisibleThreadShells } 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 sideChatAvailable,
68 sideChatDisabledReason,
69 compactSlashCommandAvailable,
70 selectedProvider,
71 selectedProviderSkills,
72 selectedProviderSlashCommands,
73 showSkillsInSlashMenu,
74 workspaceSkillsScanning,
75 questionAttachmentTarget,
76}: {
77 readonly composerTrigger: ComposerTrigger | null;
78 readonly environmentId: EnvironmentId;
79 readonly linkedEnvironments: ReadonlyMap<EnvironmentId, string>;
80 readonly gitCwd: string | null;
81 readonly activeThreadId: ThreadId | null;
82 readonly pullRequestProjectId: ProjectId | null;
83 readonly pullRequestRepository: string | null;
84 readonly threadPullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined;
85 readonly planModeUiEnabled: boolean;
86 readonly sideChatAvailable: boolean;
87 readonly sideChatDisabledReason: string | null;
88 readonly compactSlashCommandAvailable: boolean;
89 readonly selectedProvider: ProviderDriverKind;
90 readonly selectedProviderSkills: ServerProvider["skills"];
91 readonly selectedProviderSlashCommands: ServerProvider["slashCommands"];
92 readonly showSkillsInSlashMenu: boolean;
93 readonly workspaceSkillsScanning: boolean;
94 readonly questionAttachmentTarget: DraftId | null;
95}) {
96 // Thread mentions rank by recency as of when the composer mounted.
97 const [now] = useState(() => Date.now());
98 const composerTriggerKind = composerTrigger?.kind ?? null;
99 const pathTriggerQuery = composerTrigger?.kind === "path" ? composerTrigger.query : "";
100 const pullRequestTriggerQuery =
101 composerTrigger?.kind === "pull-request" ? composerTrigger.query : "";
102 const pullRequestTextQuery =
103 composerTriggerKind === "pull-request" &&
104 pullRequestTriggerQuery.length > 0 &&
105 !/^\d+$/u.test(pullRequestTriggerQuery)
106 ? pullRequestTriggerQuery
107 : null;
108 const debouncedPullRequestTextQuery = useDebouncedValue(pullRequestTextQuery, 180);
109 const settledPullRequestTextQuery =
110 pullRequestTextQuery === debouncedPullRequestTextQuery ? pullRequestTextQuery : null;
111 const isPathTrigger = composerTriggerKind === "path";
112 const environmentThreadShells = useVisibleThreadShells(isPathTrigger);
113 // Mounts older settled threads matching the mention, which shells may leave out.
114 useThreadSearch(isPathTrigger ? [environmentId] : [], pathTriggerQuery, { titlesOnly: true });
115 // The user's machines feed `@` machine matches; the catalog summary is cheap and stable.
116 const environmentIdentities = useEnvironmentIdentities();
117 const environmentMachines = useEnvironmentMachines();
118 const offersMachines = useAtomValue(offersLinkedEnvironmentsAtom(environmentId));
119 const mentionableEnvironments = environmentIdentities.map((identity) => ({
120 ...identity,
121 machine: environmentMachines.get(identity.environmentId) ?? ("server" as const),
122 }));
123 const workspaceEntries = useComposerPathSearch({
124 environmentId,
125 cwd: isPathTrigger ? gitCwd : null,
126 query: isPathTrigger ? pathTriggerQuery : null,
127 });
128​
129 const pullRequestListTargets =
130 composerTriggerKind !== "pull-request" ||
131 pullRequestProjectId === null ||
132 (pullRequestTextQuery !== null && settledPullRequestTextQuery === null)
133 ? EMPTY_PULL_REQUEST_LIST_TARGETS
134 : [
135 {
136 environmentId,
137 input: {
138 state: "all" as const,
139 projectId: pullRequestProjectId,
140 limit: COMPOSER_PULL_REQUEST_LIST_LIMIT,
141 ...(settledPullRequestTextQuery === null
142 ? {}
143 : { query: settledPullRequestTextQuery }),
144 },
145 },
146 ];
147 const pullRequestLookup = usePullRequestList(pullRequestListTargets);
148 const pullRequestTriggerNumber = (() => {
149 if (composerTrigger?.kind !== "pull-request" || composerTrigger.query.length === 0) {
150 return null;
151 }
152 const number = Number(composerTrigger.query);
153 return Number.isSafeInteger(number) && number > 0 ? number : null;
154 })();
155 const debouncedPullRequestNumber = useDebouncedValue(pullRequestTriggerNumber, 180);
156 const settledPullRequestNumber =
157 pullRequestTriggerNumber === debouncedPullRequestNumber ? pullRequestTriggerNumber : null;
158 const recentHasExactPullRequest =
159 settledPullRequestNumber !== null &&
160 pullRequestLookup.data?.entries.some(
161 (entry) =>
162 entry.projectId === pullRequestProjectId &&
163 entry.repository.trim().toLowerCase() === pullRequestRepository?.trim().toLowerCase() &&
164 entry.number === settledPullRequestNumber,
165 ) === true;
166 const exactPullRequestLookup = useEnvironmentQuery(
167 settledPullRequestNumber === null ||
168 pullRequestProjectId === null ||
169 pullRequestRepository === null ||
170 recentHasExactPullRequest
171 ? null
172 : pullRequestEnvironment.detail({
173 environmentId,
174 input: {
175 projectId: pullRequestProjectId,
176 repository: pullRequestRepository,
177 number: settledPullRequestNumber,
178 },
179 }),
180 );
181​
182 const linkedPullRequests =
183 pullRequestProjectId === null
184 ? []
185 : composerPullRequestsFromLinks(threadPullRequests ?? [], pullRequestProjectId);
186​
187 const items = ((): ComposerCommandItem[] => {
188 if (!composerTrigger) return [];
189 if (composerTrigger.kind === "path") {
190 return [
191 ...matchComposerThreadItems({
192 shells: environmentThreadShells,
193 environmentId,
194 linkedEnvironments,
195 excludeThreadId: activeThreadId,
196 query: composerTrigger.query,
197 now,
198 }),
199 // An answer to an agent's question carries thread links, not machines.
200 ...(questionAttachmentTarget === null && offersMachines
201 ? matchComposerEnvironmentItems({
202 environments: mentionableEnvironments,
203 environmentId,
204 query: composerTrigger.query,
205 })
206 : []),
207 ...workspaceEntries.entries.map((entry) => ({
208 id: `path:${entry.kind}:${entry.path}`,
209 type: "path" as const,
210 path: entry.path,
211 pathKind: entry.kind,
212 searchTarget: workspaceEntries.searchedTarget,
213 label: basenameOfPath(entry.path),
214 description: entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))),
215 })),
216 ];
217 }
218 if (composerTrigger.kind === "slash-command") {
219 const builtInSlashCommandItems = [
220 {
221 id: "slash:model",
222 type: "slash-command",
223 command: "model",
224 label: "/model",
225 description: "Switch response model for this thread",
226 },
227 ...(planModeUiEnabled
228 ? ([
229 {
230 id: "slash:plan",
231 type: "slash-command",
232 command: "plan",
233 label: "/plan",
234 description: "Switch this thread into plan mode",
235 },
236 {
237 id: "slash:default",
238 type: "slash-command",
239 command: "default",
240 label: "/default",
241 description: "Switch this thread back to normal build mode",
242 },
243 ] as const)
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 ] satisfies ReadonlyArray<Extract<ComposerCommandItem, { type: "slash-command" }>>;
264 const slashMenuSkills = getProviderSkillsForSlashMenu(
265 selectedProviderSkills,
266 showSkillsInSlashMenu,
267 );
268 const providerSlashCommandItems = getProviderSlashCommandsForSlashMenu(
269 selectedProviderSlashCommands,
270 slashMenuSkills,
271 ).map((command) => ({
272 id: `provider-slash-command:${selectedProvider}:${command.name}`,
273 type: "provider-slash-command" as const,
274 provider: selectedProvider,
275 command,
276 label: `/${command.name}`,
277 description: command.description ?? command.input?.hint ?? "Run provider command",
278 }));
279 const query = composerTrigger.query.trim().toLowerCase();
280 const skillItems = slashMenuSkills.map((skill) => ({
281 id: `skill:${selectedProvider}:${skill.name}`,
282 type: "skill" as const,
283 provider: selectedProvider,
284 skill,
285 label: `/skill:${skill.name}`,
286 description:
287 skill.shortDescription ??
288 skill.description ??
289 (skill.scope ? `${skill.scope} skill` : ""),
290 }));
291 const visibleProviderSlashCommandItems = providerSlashCommandItems.filter(
292 (item) => item.command.name !== "compact" || compactSlashCommandAvailable,
293 );
294 const slashCommandItems = slashCommandItemsForPromptPosition(
295 [...builtInSlashCommandItems, ...visibleProviderSlashCommandItems, ...skillItems],
296 composerTrigger.rangeStart === 0,
297 );
298 return searchSlashCommandItems(slashCommandItems, query);
299 }
300 if (composerTrigger.kind === "skill") {
301 return searchProviderSkills(selectedProviderSkills, composerTrigger.query).map((skill) => ({
302 id: `skill:${selectedProvider}:${skill.name}`,
303 type: "skill" as const,
304 provider: selectedProvider,
305 skill,
306 label: formatProviderSkillDisplayName(skill),
307 description:
308 skill.shortDescription ??
309 skill.description ??
310 (skill.scope ? `${skill.scope} skill` : "Run provider skill"),
311 }));
312 }
313 if (
314 composerTrigger.kind === "pull-request" &&
315 pullRequestProjectId !== null &&
316 pullRequestRepository !== null
317 ) {
318 const exactPullRequest =
319 exactPullRequestLookup.data?.number === pullRequestTriggerNumber
320 ? [exactPullRequestLookup.data]
321 : [];
322 const matches = /^\d*$/u.test(composerTrigger.query)
323 ? filterComposerPullRequestMatches({
324 entries: [...exactPullRequest, ...(pullRequestLookup.data?.entries ?? [])],
325 linked: linkedPullRequests,
326 projectId: pullRequestProjectId,
327 repository: pullRequestRepository,
328 query: composerTrigger.query,
329 limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT,
330 })
331 : withLinkedComposerPullRequestsFirst({
332 matches: rankPullRequestMatches(
333 (pullRequestLookup.data?.entries ?? []).filter((entry) => {
334 if (
335 entry.projectId !== pullRequestProjectId ||
336 entry.repository.trim().toLowerCase() !==
337 pullRequestRepository.trim().toLowerCase()
338 ) {
339 return false;
340 }
341 const provider = pullRequestLookup.data?.providers.find(
342 (candidate) => candidate.host === entry.host,
343 );
344 return (
345 provider?.searchesOnHost === true ||
346 matchesPullRequestQuery(entry, composerTrigger.query)
347 );
348 }),
349 composerTrigger.query,
350 ),
351 linked: linkedPullRequests,
352 query: composerTrigger.query,
353 limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT,
354 });
355 return matches.map((pullRequest) => ({
356 id: `pull-request:${pullRequest.projectId}:${pullRequest.repository}:${pullRequest.number}`,
357 type: "pull-request",
358 pullRequest: {
359 number: pullRequest.number,
360 title: pullRequest.title,
361 url: pullRequest.url,
362 headBranch: pullRequest.headBranch,
363 baseBranch: pullRequest.baseBranch,
364 state: pullRequest.state,
365 isDraft: pullRequest.isDraft,
366 },
367 label: `#${pullRequest.number}`,
368 description:
369 pullRequest.repository.trim().toLowerCase() === pullRequestRepository.trim().toLowerCase()
370 ? pullRequest.title
371 : `${pullRequest.repository} · ${pullRequest.title}`,
372 }));
373 }
374 return [];
375 })();
376 const isLoading =
377 (composerTriggerKind === "path" && pathTriggerQuery.length > 0 && workspaceEntries.isPending) ||
378 ((composerTriggerKind === "skill" || composerTriggerKind === "slash-command") &&
379 workspaceSkillsScanning) ||
380 (composerTriggerKind === "pull-request" &&
381 pullRequestProjectId !== null &&
382 pullRequestRepository !== null &&
383 (pullRequestLookup.isPending ||
384 pullRequestTextQuery !== debouncedPullRequestTextQuery ||
385 pullRequestTriggerNumber !== debouncedPullRequestNumber ||
386 exactPullRequestLookup.isPending));
387 const emptyState = (() => {
388 if (composerTriggerKind === "skill") {
389 return "No skills found. Try / to browse provider commands.";
390 }
391 if (composerTriggerKind === "pull-request") {
392 if (pullRequestProjectId === null || pullRequestRepository === null) {
393 return "Pull requests are not available for this project.";
394 }
395 if (
396 pullRequestLookup.error !== null ||
397 pullRequestLookup.data?.errors.some((error) => error.projectId === pullRequestProjectId)
398 ) {
399 return "Pull requests could not be read for this project.";
400 }
401 return composerTrigger?.query
402 ? `No pull request matches ${composerTrigger.query}.`
403 : "No pull requests found in this repository.";
404 }
405 return composerTriggerKind === "path"
406 ? "No matching files or folders."
407 : "No matching command.";
408 })();
409​
410 return { items, isLoading, emptyState };