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