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