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