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