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