Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useComposerMenuItems.ts

438 lines16.8 KB

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