@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 450 lines 17.2 KB
Raw
1 import { useGT, useMessages } from "gt-react";
2 import {
3 legacyThreadPullRequestKey,
4 threadPullRequestKeyOf,
5 } from "@t3tools/client-runtime/thread-pull-requests";
6 import {
7 matchComposerEnvironmentItems,
8 matchComposerThreadItems,
9 } from "@t3tools/client-runtime/composerThreadItems";
10 import { useAtomValue } from "@effect/atom-react";
11 import { useState } from "react";
12 import type {
13 EnvironmentId,
14 ProjectId,
15 ProviderDriverKind,
16 ProviderInstanceId,
17 PullRequestListInput,
18 ServerProvider,
19 ThreadId,
20 ThreadPullRequestLink,
21 } from "@t3tools/contracts";
22 import {
23 composerPullRequestsFromLinks,
24 filterComposerPullRequestMatches,
25 withLinkedComposerPullRequestsFirst,
26 } from "@t3tools/shared/composerPullRequestMatches";
27 import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";
28
29 import type { ComposerTrigger } from "../../composer-logic";
30 import type { DraftId } from "../../composerDraftStore";
31 import { basenameOfPath } from "../../pierre-icons";
32 import {
33 getProviderSkillsForSlashMenu,
34 getProviderSlashCommandsForSlashMenu,
35 } from "@t3tools/client-runtime/providerSkills";
36 import { searchProviderSkills } from "../../providerSkillSearch";
37 import { useVisibleThreadShells } from "~/state/entities";
38 import { useEnvironmentIdentities, useEnvironmentMachines } from "~/state/environments";
39 import { offersLinkedEnvironmentsAtom } from "~/state/peerLinks";
40 import {
41 pullRequestEnvironment,
42 usePullRequestList,
43 type EnvironmentQueryTarget,
44 } from "~/state/pullRequests";
45 import { useEnvironmentQuery } from "~/state/query";
46 import { useComposerPathSearch, useDebouncedValue, useThreadSearch } from "~/state/queries";
47 import {
48 matchesPullRequestQuery,
49 rankPullRequestMatches,
50 } from "../pullRequest/pullRequestList.logic";
51 import type { ComposerCommandItem } from "./ComposerCommandMenu";
52 import { matchComposerModelItems } from "./composerModelMentions";
53 import type { ModelEsque } from "./providerIconUtils";
54 import type { ProviderInstanceEntry } from "../../providerInstances";
55 import {
56 searchSlashCommandItems,
57 slashCommandItemsForPromptPosition,
58 } from "./composerSlashCommandSearch";
59
60 const COMPOSER_PULL_REQUEST_LIST_LIMIT = 99;
61 const COMPOSER_PULL_REQUEST_RESULT_LIMIT = 12;
62 const EMPTY_PULL_REQUEST_LIST_TARGETS: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>> =
63 [];
64
65 /** Builds the @, /, $ and # suggestion lists, running the searches each trigger needs. */
66 export 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 environmentId,
232 query: composerTrigger.query,
233 },
234 messages,
235 )
236 : []),
237 ...matchComposerModelItems({
238 instanceEntries: modelMentions.instanceEntries,
239 modelOptionsByInstance: modelMentions.modelOptionsByInstance,
240 query: composerTrigger.query,
241 }),
242 ...workspaceEntries.entries.map((entry) => ({
243 id: `path:${entry.kind}:${entry.path}`,
244 type: "path" as const,
245 path: entry.path,
246 pathKind: entry.kind,
247 searchTarget: workspaceEntries.searchedTarget,
248 label: basenameOfPath(entry.path),
249 description: entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))),
250 })),
251 ];
252 }
253 if (composerTrigger.kind === "slash-command") {
254 const builtInSlashCommandItems = [
255 {
256 id: "slash:model",
257 type: "slash-command",
258 command: "model",
259 label: "/model",
260 description: gt("Switch response model for this thread"),
261 },
262 ...(sideChatAvailable
263 ? ([
264 {
265 id: "slash:side",
266 type: "slash-command",
267 command: "side",
268 label: "/side",
269 description: sideChatDisabledReason ?? gt("Ask a side question in a new side chat"),
270 },
271 {
272 id: "slash:btw",
273 type: "slash-command",
274 command: "btw",
275 label: "/btw",
276 description: sideChatDisabledReason ?? gt("Same as /side"),
277 },
278 ] as const)
279 : []),
280 ...(freshSessionAvailable
281 ? ([
282 {
283 id: "slash:clear",
284 type: "slash-command",
285 command: "clear",
286 label: "/clear",
287 description: gt("Start a fresh session; earlier messages stay visible"),
288 },
289 ] as const)
290 : []),
291 ] satisfies ReadonlyArray<Extract<ComposerCommandItem, { type: "slash-command" }>>;
292 const slashMenuSkills = getProviderSkillsForSlashMenu(
293 selectedProviderSkills,
294 showSkillsInSlashMenu,
295 );
296 const providerSlashCommandItems = getProviderSlashCommandsForSlashMenu(
297 selectedProviderSlashCommands,
298 slashMenuSkills,
299 ).map((command) => ({
300 id: `provider-slash-command:${selectedProvider}:${command.name}`,
301 type: "provider-slash-command" as const,
302 provider: selectedProvider,
303 command,
304 label: `/${command.name}`,
305 description: command.description ?? command.input?.hint ?? gt("Run provider command"),
306 }));
307 const query = composerTrigger.query.trim().toLowerCase();
308 const skillItems = slashMenuSkills.map((skill) => ({
309 id: `skill:${selectedProvider}:${skill.name}`,
310 type: "skill" as const,
311 provider: selectedProvider,
312 skill,
313 label: `/skill:${skill.name}`,
314 description:
315 skill.shortDescription ??
316 skill.description ??
317 (skill.scope ? gt("{scope} skill", { scope: skill.scope }) : ""),
318 }));
319 // T3's `/clear` replaces the provider's, which would clear a session T3 still treats as live.
320 const visibleProviderSlashCommandItems = providerSlashCommandItems.filter(
321 (item) =>
322 (item.command.name !== "compact" || compactSlashCommandAvailable) &&
323 (item.command.name !== "clear" || !freshSessionAvailable),
324 );
325 const slashCommandItems = slashCommandItemsForPromptPosition(
326 [...builtInSlashCommandItems, ...visibleProviderSlashCommandItems, ...skillItems],
327 composerTrigger.rangeStart === 0,
328 );
329 return searchSlashCommandItems(slashCommandItems, query);
330 }
331 if (composerTrigger.kind === "skill") {
332 return searchProviderSkills(selectedProviderSkills, composerTrigger.query).map((skill) => ({
333 id: `skill:${selectedProvider}:${skill.name}`,
334 type: "skill" as const,
335 provider: selectedProvider,
336 skill,
337 label: formatProviderSkillDisplayName(skill),
338 description:
339 skill.shortDescription ??
340 skill.description ??
341 (skill.scope ? gt("{scope} skill", { scope: skill.scope }) : gt("Run provider skill")),
342 }));
343 }
344 if (
345 composerTrigger.kind === "pull-request" &&
346 pullRequestProjectId !== null &&
347 pullRequestRepository !== null
348 ) {
349 const exactPullRequest =
350 exactPullRequestLookup.data?.number === pullRequestTriggerNumber
351 ? [
352 {
353 ...exactPullRequestLookup.data,
354 // Only the host: the URL's full repository path would not match the project's selector.
355 host: legacyThreadPullRequestKey(exactPullRequestLookup.data).host,
356 },
357 ]
358 : [];
359 const matches = /^\d*$/u.test(composerTrigger.query)
360 ? filterComposerPullRequestMatches({
361 keyOf: threadPullRequestKeyOf,
362 entries: [...exactPullRequest, ...(pullRequestLookup.data?.entries ?? [])],
363 linked: linkedPullRequests,
364 projectId: pullRequestProjectId,
365 repository: pullRequestRepository,
366 query: composerTrigger.query,
367 limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT,
368 })
369 : withLinkedComposerPullRequestsFirst({
370 keyOf: threadPullRequestKeyOf,
371 matches: rankPullRequestMatches(
372 (pullRequestLookup.data?.entries ?? []).filter((entry) => {
373 if (
374 entry.projectId !== pullRequestProjectId ||
375 entry.repository.trim().toLowerCase() !==
376 pullRequestRepository.trim().toLowerCase()
377 ) {
378 return false;
379 }
380 const provider = pullRequestLookup.data?.providers.find(
381 (candidate) => candidate.host === entry.host,
382 );
383 return (
384 provider?.searchesOnHost === true ||
385 matchesPullRequestQuery(entry, composerTrigger.query)
386 );
387 }),
388 composerTrigger.query,
389 ),
390 linked: linkedPullRequests,
391 query: composerTrigger.query,
392 limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT,
393 });
394 return matches.map((pullRequest) => ({
395 id: `pull-request:${pullRequest.projectId}:${threadPullRequestKeyOf(pullRequest)}`,
396 type: "pull-request",
397 pullRequest: {
398 number: pullRequest.number,
399 title: pullRequest.title,
400 url: pullRequest.url,
401 headBranch: pullRequest.headBranch,
402 baseBranch: pullRequest.baseBranch,
403 state: pullRequest.state,
404 isDraft: pullRequest.isDraft,
405 },
406 label: `#${pullRequest.number}`,
407 description:
408 pullRequest.repository.trim().toLowerCase() === pullRequestRepository.trim().toLowerCase()
409 ? pullRequest.title
410 : `${pullRequest.repository} · ${pullRequest.title}`,
411 }));
412 }
413 return [];
414 })();
415 const isLoading =
416 (composerTriggerKind === "path" && workspaceEntries.isPending) ||
417 ((composerTriggerKind === "skill" || composerTriggerKind === "slash-command") &&
418 workspaceSkillsScanning) ||
419 (composerTriggerKind === "pull-request" &&
420 pullRequestProjectId !== null &&
421 pullRequestRepository !== null &&
422 (pullRequestLookup.isPending ||
423 pullRequestTextQuery !== debouncedPullRequestTextQuery ||
424 pullRequestTriggerNumber !== debouncedPullRequestNumber ||
425 exactPullRequestLookup.isPending));
426 const emptyState = (() => {
427 if (composerTriggerKind === "skill") {
428 return gt("No skills found. Try / to browse provider commands.");
429 }
430 if (composerTriggerKind === "pull-request") {
431 if (pullRequestProjectId === null || pullRequestRepository === null) {
432 return gt("Pull requests are not available for this project.");
433 }
434 if (
435 pullRequestLookup.error !== null ||
436 pullRequestLookup.data?.errors.some((error) => error.projectId === pullRequestProjectId)
437 ) {
438 return gt("Pull requests could not be read for this project.");
439 }
440 return composerTrigger?.query
441 ? gt("No pull request matches {query}.", { query: composerTrigger.query })
442 : gt("No pull requests found in this repository.");
443 }
444 return composerTriggerKind === "path"
445 ? gt("No matching files or folders.")
446 : gt("No matching command.");
447 })();
448
449 return { items, isLoading, emptyState };
450 }