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
| 1 | import { threadPullRequestKeyOf } from "@t3tools/client-runtime/thread-pull-requests"; |
| 2 | import * as Dialog from "../../components/ui/Dialog"; |
| 3 | import type { |
| 4 | EnvironmentId, |
| 5 | ProjectId, |
| 6 | ServerProvider, |
| 7 | ThreadId, |
| 8 | ThreadPullRequestLink, |
| 9 | } from "@t3tools/contracts"; |
| 10 | import { |
| 11 | type ComposerEnvironmentCandidate, |
| 12 | matchComposerEnvironmentItems, |
| 13 | matchComposerThreadItems, |
| 14 | } from "@t3tools/client-runtime/composerThreadItems"; |
| 15 | import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; |
| 16 | |
| 17 | const EMPTY_THREAD_SHELLS: ReadonlyArray<EnvironmentThreadShell> = []; |
| 18 | const EMPTY_ENVIRONMENTS: ReadonlyArray<ComposerEnvironmentCandidate> = []; |
| 19 | const NO_LINKED_ENVIRONMENTS: ReadonlyMap<EnvironmentId, string> = new Map(); |
| 20 | import { COMPOSER_CONTEXT_MAX_RECORDS } from "@t3tools/contracts"; |
| 21 | import { |
| 22 | formatComposerContextReference, |
| 23 | threadContextRecord, |
| 24 | } from "@t3tools/shared/composerContextReferences"; |
| 25 | import { environmentComposerContext, pullRequestComposerContext } from "../../lib/composerContext"; |
| 26 | import { uuidv4 } from "../../lib/uuid"; |
| 27 | import { |
| 28 | getComposerDraftSnapshot, |
| 29 | setComposerDraftContext, |
| 30 | useComposerDraftSelection, |
| 31 | } from "../../state/use-composer-drafts"; |
| 32 | import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits"; |
| 33 | import { |
| 34 | detectComposerTrigger, |
| 35 | replaceTextRange, |
| 36 | serializeComposerFileLink, |
| 37 | type ComposerTrigger, |
| 38 | } from "@t3tools/shared/composerTrigger"; |
| 39 | import { |
| 40 | insertRankedSearchResult, |
| 41 | normalizeSearchQuery, |
| 42 | scoreQueryMatch, |
| 43 | } from "@t3tools/shared/searchRanking"; |
| 44 | import { |
| 45 | dedupeProviderSkillsByName, |
| 46 | getProviderSkillsForSlashMenu, |
| 47 | getProviderSlashCommandsForSlashMenu, |
| 48 | isProviderSkillUserInvocable, |
| 49 | resolveProviderSkillsForCwd, |
| 50 | resolveProviderSlashCommandsForCwd, |
| 51 | } from "@t3tools/client-runtime/providerSkills"; |
| 52 | import { |
| 53 | formatComposerModelMention, |
| 54 | rankComposerModelMentions, |
| 55 | } from "@t3tools/client-runtime/composer-model-mentions"; |
| 56 | import { useAtomRefresh } from "@effect/atom-react"; |
| 57 | import { Atom } from "effect/reactivity"; |
| 58 | import { msg, useGT, useMessages } from "gt-react-native"; |
| 59 | import { useEffect, useState } from "react"; |
| 60 | |
| 61 | import type { ComposerEditorSelection } from "../../components/ComposerEditor"; |
| 62 | import { providerWorkspaceSnapshotRefresh } from "../../state/provider-workspace-snapshot-refresh"; |
| 63 | import { |
| 64 | useComposerPathSearch, |
| 65 | useComposerPullRequestSearch, |
| 66 | useThreadSearch, |
| 67 | } from "../../state/queries"; |
| 68 | import type { ModelOption } from "../../lib/modelOptions"; |
| 69 | import { m, type MessageResolver } from "../../i18n/messages"; |
| 70 | import type { ComposerCommandItem } from "./ComposerCommandPopover"; |
| 71 | import { matchesSlashSkillQuery } from "./composerSlashSkillSearch"; |
| 72 | |
| 73 | const idleWorkspaceSnapshotRefreshAtom: Atom.Atom<unknown> = Atom.make<void>(undefined).pipe( |
| 74 | Atom.withLabel("mobile:provider-workspace-snapshot-refresh:idle"), |
| 75 | ); |
| 76 | |
| 77 | function composerSelectionAtEnd(draftMessage: string): ComposerEditorSelection { |
| 78 | return { start: draftMessage.length, end: draftMessage.length }; |
| 79 | } |
| 80 | |
| 81 | /** |
| 82 | * A caret placed by an insertion (chips, pasted context) wins while the draft |
| 83 | * still has the text it was placed in. Otherwise the composer's own caret is |
| 84 | * clamped to the draft, and a caret from another owner starts at the end. |
| 85 | */ |
| 86 | export function resolveComposerMenuSelection(input: { |
| 87 | readonly draftMessage: string; |
| 88 | readonly ownerKey: string | null; |
| 89 | readonly inserted: ComposerEditorSelection | null; |
| 90 | readonly local: { |
| 91 | readonly ownerKey: string | null; |
| 92 | readonly start: number; |
| 93 | readonly end: number; |
| 94 | }; |
| 95 | }): ComposerEditorSelection { |
| 96 | if (input.inserted) return input.inserted; |
| 97 | if (input.local.ownerKey !== input.ownerKey) return composerSelectionAtEnd(input.draftMessage); |
| 98 | const length = input.draftMessage.length; |
| 99 | return { start: Math.min(input.local.start, length), end: Math.min(input.local.end, length) }; |
| 100 | } |
| 101 | |
| 102 | const PULL_REQUEST_STATE_LABELS = { |
| 103 | open: msg("open", { $context: "pull request state" }), |
| 104 | closed: msg("closed", { $context: "pull request state" }), |
| 105 | merged: msg("merged", { $context: "pull request state" }), |
| 106 | } as const; |
| 107 | |
| 108 | export function buildComposerSlashCommandItems( |
| 109 | input: { |
| 110 | readonly query: string; |
| 111 | readonly atMessageStart: boolean; |
| 112 | readonly hasThread: boolean; |
| 113 | readonly hasCompactableConversation?: boolean; |
| 114 | readonly offersUsageLimits?: boolean; |
| 115 | /** T3's `/clear` replaces the provider's, which would clear a session T3 still treats as live. */ |
| 116 | readonly offersFreshSession?: boolean; |
| 117 | readonly offersSideChat?: boolean; |
| 118 | readonly selectedProviderStatus: Pick<ServerProvider, "driver" | "slashCommands"> | null; |
| 119 | }, |
| 120 | resolve: MessageResolver = m, |
| 121 | ): ComposerCommandItem[] { |
| 122 | const query = input.query.toLowerCase(); |
| 123 | const items: ComposerCommandItem[] = "model".includes(query) |
| 124 | ? [ |
| 125 | { |
| 126 | id: "cmd:model", |
| 127 | type: "slash-command", |
| 128 | command: "model", |
| 129 | label: "/model", |
| 130 | description: resolve(msg("Switch model")), |
| 131 | }, |
| 132 | ] |
| 133 | : []; |
| 134 | |
| 135 | // Providers expand commands only at the start of a message. T3 commands |
| 136 | // change local state and do not have this restriction, except `/clear`. |
| 137 | if (!input.atMessageStart) return items; |
| 138 | if (input.offersSideChat) { |
| 139 | for (const [command, description] of [ |
| 140 | ["side", resolve(msg("Ask a side question in a new side chat"))], |
| 141 | ["btw", resolve(msg("Same as /side"))], |
| 142 | ] as const) { |
| 143 | if (!command.includes(query)) continue; |
| 144 | items.push({ |
| 145 | id: `cmd:${command}`, |
| 146 | type: "slash-command", |
| 147 | command, |
| 148 | label: `/${command}`, |
| 149 | description, |
| 150 | }); |
| 151 | } |
| 152 | } |
| 153 | if (input.offersFreshSession && "clear".includes(query)) { |
| 154 | items.push({ |
| 155 | id: "cmd:clear", |
| 156 | type: "slash-command", |
| 157 | command: "clear", |
| 158 | label: "/clear", |
| 159 | description: resolve(msg("Start a fresh session")), |
| 160 | }); |
| 161 | } |
| 162 | for (const command of input.selectedProviderStatus?.slashCommands ?? []) { |
| 163 | if (!command.name.toLowerCase().includes(query)) continue; |
| 164 | if (command.name === "clear" && input.offersFreshSession) continue; |
| 165 | if (command.name === "compact" && !input.hasCompactableConversation) continue; |
| 166 | if (command.name === USAGE_LIMITS_COMMAND.name && input.offersUsageLimits && !input.hasThread) { |
| 167 | continue; |
| 168 | } |
| 169 | if ( |
| 170 | !input.hasThread && |
| 171 | input.selectedProviderStatus?.driver === "codex" && |
| 172 | command.name === "feedback" |
| 173 | ) { |
| 174 | continue; |
| 175 | } |
| 176 | items.push({ |
| 177 | id: `pcmd:${command.name}`, |
| 178 | type: "provider-slash-command", |
| 179 | command, |
| 180 | label: `/${command.name}`, |
| 181 | description: command.description ?? "", |
| 182 | }); |
| 183 | } |
| 184 | return items; |
| 185 | } |
| 186 | |
| 187 | export function buildComposerModelItems( |
| 188 | modelOptions: ReadonlyArray<ModelOption>, |
| 189 | query: string, |
| 190 | providers: ReadonlyArray<ServerProvider>, |
| 191 | ): ComposerCommandItem[] { |
| 192 | // The picker retains saved selections even when their provider is no longer usable. |
| 193 | const readyProviderIds = new Set( |
| 194 | providers |
| 195 | .filter( |
| 196 | (provider) => |
| 197 | provider.installed && |
| 198 | provider.status === "ready" && |
| 199 | provider.auth.status !== "unauthenticated" && |
| 200 | provider.availability !== "unavailable", |
| 201 | ) |
| 202 | .map((provider) => provider.instanceId), |
| 203 | ); |
| 204 | return rankComposerModelMentions( |
| 205 | modelOptions.filter( |
| 206 | (option) => |
| 207 | readyProviderIds.has(option.selection.instanceId) && |
| 208 | !option.isUnavailable && |
| 209 | !option.isHidden && |
| 210 | !option.isLegacy, |
| 211 | ), |
| 212 | query, |
| 213 | (option) => ({ |
| 214 | name: option.label, |
| 215 | ...(option.subtitle ? { subProvider: option.subtitle } : {}), |
| 216 | driverKind: option.providerDriver, |
| 217 | providerDisplayName: option.providerLabel, |
| 218 | }), |
| 219 | ).map((option) => ({ |
| 220 | id: `model:${option.key}`, |
| 221 | type: "model", |
| 222 | option, |
| 223 | label: option.label, |
| 224 | description: option.subtitle |
| 225 | ? `${option.providerLabel} · ${option.subtitle}` |
| 226 | : option.providerLabel, |
| 227 | })); |
| 228 | } |
| 229 | |
| 230 | export function resolveComposerCommandSelection(input: { |
| 231 | readonly draftMessage: string; |
| 232 | readonly trigger: Pick<ComposerTrigger, "rangeStart" | "rangeEnd">; |
| 233 | readonly item: ComposerCommandItem; |
| 234 | }): { readonly text: string; readonly cursor: number } { |
| 235 | const { draftMessage, trigger, item } = input; |
| 236 | let replacement = ""; |
| 237 | if (item.type === "path") { |
| 238 | replacement = `${serializeComposerFileLink(item.path)} `; |
| 239 | } else if (item.type === "skill") { |
| 240 | replacement = `$${item.skill.name} `; |
| 241 | } else if (item.type === "slash-command") { |
| 242 | replacement = `/${item.command} `; |
| 243 | } else if (item.type === "provider-slash-command") { |
| 244 | replacement = `/${item.command.name} `; |
| 245 | } else if (item.type === "model") { |
| 246 | replacement = `${formatComposerModelMention(item.option.selection.instanceId, item.option.selection.model)} `; |
| 247 | } |
| 248 | return replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, replacement); |
| 249 | } |
| 250 | |
| 251 | export function useComposerCommandMenu({ |
| 252 | draftMessage, |
| 253 | ownerKey, |
| 254 | environmentId, |
| 255 | threadShells = EMPTY_THREAD_SHELLS, |
| 256 | environments = EMPTY_ENVIRONMENTS, |
| 257 | linkedEnvironments = NO_LINKED_ENVIRONMENTS, |
| 258 | currentThreadId = null, |
| 259 | projectCwd, |
| 260 | pullRequestProjectId = null, |
| 261 | pullRequestRepository = null, |
| 262 | threadPullRequests, |
| 263 | selectedProviderStatus, |
| 264 | hasThread, |
| 265 | hasCompactableConversation, |
| 266 | offersUsageLimits = false, |
| 267 | enabled = true, |
| 268 | onChangeDraftMessage, |
| 269 | onUsageLimits, |
| 270 | onOpenModelPicker, |
| 271 | modelOptions, |
| 272 | modelProviders, |
| 273 | onFreshSession, |
| 274 | offersSideChat = false, |
| 275 | }: { |
| 276 | readonly draftMessage: string; |
| 277 | readonly ownerKey: string | null; |
| 278 | readonly environmentId: EnvironmentId | null; |
| 279 | readonly threadShells?: ReadonlyArray<EnvironmentThreadShell>; |
| 280 | readonly environments?: ReadonlyArray<ComposerEnvironmentCandidate>; |
| 281 | /** The machines `environmentId` links to, by name, whose threads the picker also offers. */ |
| 282 | readonly linkedEnvironments?: ReadonlyMap<EnvironmentId, string>; |
| 283 | readonly currentThreadId?: ThreadId | null; |
| 284 | readonly projectCwd: string | null; |
| 285 | readonly pullRequestProjectId?: ProjectId | null; |
| 286 | readonly pullRequestRepository?: string | null; |
| 287 | readonly threadPullRequests?: ReadonlyArray<ThreadPullRequestLink>; |
| 288 | readonly selectedProviderStatus: ServerProvider | null; |
| 289 | readonly hasThread: boolean; |
| 290 | readonly hasCompactableConversation: boolean; |
| 291 | readonly offersUsageLimits?: boolean; |
| 292 | readonly enabled?: boolean; |
| 293 | readonly onChangeDraftMessage: (value: string) => void; |
| 294 | readonly onUsageLimits?: () => void; |
| 295 | /** `/model` opens this picker instead of inserting text. */ |
| 296 | readonly onOpenModelPicker: () => void; |
| 297 | readonly modelOptions?: ReadonlyArray<ModelOption>; |
| 298 | readonly modelProviders?: ReadonlyArray<ServerProvider>; |
| 299 | /** Arms a fresh session for the next message; absent where `/clear` is unavailable. */ |
| 300 | readonly onFreshSession?: () => void; |
| 301 | readonly offersSideChat?: boolean; |
| 302 | }) { |
| 303 | const gt = useGT(); |
| 304 | const messages = useMessages(); |
| 305 | const [localSelection, setLocalSelection] = useState(() => ({ |
| 306 | ownerKey, |
| 307 | ...composerSelectionAtEnd(draftMessage), |
| 308 | })); |
| 309 | // Thread mentions rank by recency as of when the composer mounted. |
| 310 | const [now] = useState(() => Date.now()); |
| 311 | const insertedSelection = useComposerDraftSelection(ownerKey, draftMessage); |
| 312 | const selection = resolveComposerMenuSelection({ |
| 313 | draftMessage, |
| 314 | ownerKey, |
| 315 | inserted: insertedSelection, |
| 316 | local: localSelection, |
| 317 | }); |
| 318 | const setSelection = (next: ComposerEditorSelection) => |
| 319 | setLocalSelection({ ownerKey, start: next.start, end: next.end }); |
| 320 | |
| 321 | const skills = selectedProviderStatus |
| 322 | ? resolveProviderSkillsForCwd(selectedProviderStatus, projectCwd) |
| 323 | : []; |
| 324 | const selectedProviderInstanceId = selectedProviderStatus?.instanceId; |
| 325 | const refreshWorkspaceSnapshot = useAtomRefresh( |
| 326 | environmentId && projectCwd && selectedProviderInstanceId |
| 327 | ? providerWorkspaceSnapshotRefresh({ |
| 328 | environmentId, |
| 329 | instanceId: selectedProviderInstanceId, |
| 330 | cwd: projectCwd, |
| 331 | }) |
| 332 | : idleWorkspaceSnapshotRefreshAtom, |
| 333 | ); |
| 334 | // Every draft change rechecks a stale snapshot, including drafts written by |
| 335 | // another surface (a prompt link) that never move the editor selection. |
| 336 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes the provider workspace snapshot atom whenever the draft text changes from any surface |
| 337 | useEffect(() => { |
| 338 | refreshWorkspaceSnapshot(); |
| 339 | }, [ |
| 340 | // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Draft changes are the recheck signal. |
| 341 | draftMessage, |
| 342 | refreshWorkspaceSnapshot, |
| 343 | ]); |
| 344 | const onSelectionChange = (nextSelection: ComposerEditorSelection) => { |
| 345 | setSelection(nextSelection); |
| 346 | }; |
| 347 | |
| 348 | const trigger = (() => { |
| 349 | if (!enabled || selection.start !== selection.end) { |
| 350 | return null; |
| 351 | } |
| 352 | return detectComposerTrigger(draftMessage, selection.end); |
| 353 | })(); |
| 354 | const pathSearch = useComposerPathSearch({ |
| 355 | environmentId, |
| 356 | cwd: trigger?.kind === "path" ? projectCwd : null, |
| 357 | query: trigger?.kind === "path" ? trigger.query : null, |
| 358 | }); |
| 359 | // Mounts older settled threads matching the mention, here and on linked machines, which shells |
| 360 | // may leave out. |
| 361 | useThreadSearch( |
| 362 | trigger?.kind === "path" && environmentId ? [environmentId, ...linkedEnvironments.keys()] : [], |
| 363 | trigger?.kind === "path" ? trigger.query : "", |
| 364 | { titlesOnly: true }, |
| 365 | ); |
| 366 | const pullRequestSearch = useComposerPullRequestSearch({ |
| 367 | environmentId, |
| 368 | projectId: pullRequestProjectId, |
| 369 | repository: pullRequestRepository, |
| 370 | threadPullRequests, |
| 371 | query: trigger?.kind === "pull-request" ? trigger.query : null, |
| 372 | }); |
| 373 | |
| 374 | const items = ((): ComposerCommandItem[] => { |
| 375 | if (!trigger) return []; |
| 376 | |
| 377 | if (trigger.kind === "pull-request") { |
| 378 | return pullRequestSearch.entries.map((entry) => ({ |
| 379 | id: `pr:${entry.projectId}:${threadPullRequestKeyOf(entry)}`, |
| 380 | type: "pull-request", |
| 381 | pullRequest: { |
| 382 | number: entry.number, |
| 383 | title: entry.title, |
| 384 | url: entry.url, |
| 385 | headBranch: entry.headBranch, |
| 386 | baseBranch: entry.baseBranch, |
| 387 | state: entry.state, |
| 388 | isDraft: entry.isDraft, |
| 389 | }, |
| 390 | label: `#${entry.number}`, |
| 391 | description: `${entry.isDraft ? gt("Draft", { $context: "pull request state" }) : messages(PULL_REQUEST_STATE_LABELS[entry.state])} · ${ |
| 392 | entry.repository.toLowerCase() === pullRequestRepository?.toLowerCase() |
| 393 | ? "" |
| 394 | : `${entry.repository} · ` |
| 395 | }${entry.title}`, |
| 396 | })); |
| 397 | } |
| 398 | |
| 399 | if (trigger.kind === "slash-command") { |
| 400 | const q = trigger.query.toLowerCase(); |
| 401 | const visibleSkills = getProviderSkillsForSlashMenu(skills, true); |
| 402 | const commandItems = buildComposerSlashCommandItems( |
| 403 | { |
| 404 | query: q, |
| 405 | atMessageStart: trigger.rangeStart === 0, |
| 406 | hasThread, |
| 407 | hasCompactableConversation, |
| 408 | offersUsageLimits, |
| 409 | offersFreshSession: onFreshSession !== undefined, |
| 410 | offersSideChat, |
| 411 | selectedProviderStatus: selectedProviderStatus |
| 412 | ? { |
| 413 | ...selectedProviderStatus, |
| 414 | slashCommands: getProviderSlashCommandsForSlashMenu( |
| 415 | resolveProviderSlashCommandsForCwd(selectedProviderStatus, projectCwd), |
| 416 | visibleSkills, |
| 417 | ), |
| 418 | } |
| 419 | : null, |
| 420 | }, |
| 421 | messages, |
| 422 | ); |
| 423 | |
| 424 | const skillItems = visibleSkills |
| 425 | .filter((skill) => matchesSlashSkillQuery(skill, q)) |
| 426 | .map((skill) => ({ |
| 427 | id: `skill:${skill.name}`, |
| 428 | type: "skill" as const, |
| 429 | skill, |
| 430 | label: `skill:${skill.name}`, |
| 431 | description: skill.shortDescription ?? skill.description ?? "", |
| 432 | })); |
| 433 | |
| 434 | return [...commandItems, ...skillItems]; |
| 435 | } |
| 436 | |
| 437 | if (trigger.kind === "skill") { |
| 438 | const enabledSkills = dedupeProviderSkillsByName(skills.filter(isProviderSkillUserInvocable)); |
| 439 | const normalizedQuery = normalizeSearchQuery(trigger.query, { |
| 440 | trimLeadingPattern: /^\p{Sc}+/u, |
| 441 | }); |
| 442 | |
| 443 | if (!normalizedQuery) { |
| 444 | return enabledSkills.slice(0, 20).map((skill) => ({ |
| 445 | id: `skill:${skill.name}`, |
| 446 | type: "skill" as const, |
| 447 | skill, |
| 448 | label: skill.displayName ?? skill.name, |
| 449 | description: skill.shortDescription ?? skill.description ?? "", |
| 450 | })); |
| 451 | } |
| 452 | |
| 453 | const ranked: Array<{ |
| 454 | item: (typeof enabledSkills)[number]; |
| 455 | score: number; |
| 456 | tieBreaker: string; |
| 457 | }> = []; |
| 458 | for (const skill of enabledSkills) { |
| 459 | const displayLabel = (skill.displayName ?? skill.name).toLowerCase(); |
| 460 | const scores = [ |
| 461 | scoreQueryMatch({ |
| 462 | value: skill.name.toLowerCase(), |
| 463 | query: normalizedQuery, |
| 464 | exactBase: 0, |
| 465 | prefixBase: 2, |
| 466 | boundaryBase: 4, |
| 467 | includesBase: 6, |
| 468 | fuzzyBase: 100, |
| 469 | boundaryMarkers: ["-", "_", "/"], |
| 470 | }), |
| 471 | scoreQueryMatch({ |
| 472 | value: displayLabel, |
| 473 | query: normalizedQuery, |
| 474 | exactBase: 1, |
| 475 | prefixBase: 3, |
| 476 | boundaryBase: 5, |
| 477 | includesBase: 7, |
| 478 | fuzzyBase: 110, |
| 479 | }), |
| 480 | scoreQueryMatch({ |
| 481 | value: skill.shortDescription?.toLowerCase() ?? "", |
| 482 | query: normalizedQuery, |
| 483 | exactBase: 20, |
| 484 | prefixBase: 22, |
| 485 | boundaryBase: 24, |
| 486 | includesBase: 26, |
| 487 | }), |
| 488 | scoreQueryMatch({ |
| 489 | value: skill.description?.toLowerCase() ?? "", |
| 490 | query: normalizedQuery, |
| 491 | exactBase: 30, |
| 492 | prefixBase: 32, |
| 493 | boundaryBase: 34, |
| 494 | includesBase: 36, |
| 495 | }), |
| 496 | ].filter((score): score is number => score !== null); |
| 497 | |
| 498 | if (scores.length > 0) { |
| 499 | insertRankedSearchResult( |
| 500 | ranked, |
| 501 | { |
| 502 | item: skill, |
| 503 | score: Math.min(...scores), |
| 504 | tieBreaker: `${displayLabel}\u0000${skill.name}`, |
| 505 | }, |
| 506 | 20, |
| 507 | ); |
| 508 | } |
| 509 | } |
| 510 | |
| 511 | return ranked.map(({ item: skill }) => ({ |
| 512 | id: `skill:${skill.name}`, |
| 513 | type: "skill" as const, |
| 514 | skill, |
| 515 | label: skill.displayName ?? skill.name, |
| 516 | description: skill.shortDescription ?? skill.description ?? "", |
| 517 | })); |
| 518 | } |
| 519 | |
| 520 | if (trigger.kind === "path") { |
| 521 | const threadItems = environmentId |
| 522 | ? matchComposerThreadItems( |
| 523 | { |
| 524 | shells: threadShells, |
| 525 | environmentId, |
| 526 | linkedEnvironments, |
| 527 | excludeThreadId: currentThreadId, |
| 528 | query: trigger.query, |
| 529 | now, |
| 530 | }, |
| 531 | messages, |
| 532 | ) |
| 533 | : []; |
| 534 | const environmentItems = environmentId |
| 535 | ? matchComposerEnvironmentItems( |
| 536 | { environments, environmentId, query: trigger.query }, |
| 537 | messages, |
| 538 | ) |
| 539 | : []; |
| 540 | const modelItems = |
| 541 | modelOptions && modelProviders |
| 542 | ? buildComposerModelItems(modelOptions, trigger.query, modelProviders) |
| 543 | : []; |
| 544 | return [ |
| 545 | ...threadItems, |
| 546 | ...environmentItems, |
| 547 | ...modelItems, |
| 548 | ...pathSearch.entries.map((entry) => { |
| 549 | const parts = entry.path.split("/"); |
| 550 | return { |
| 551 | id: `path:${entry.path}`, |
| 552 | type: "path" as const, |
| 553 | path: entry.path, |
| 554 | kind: entry.kind, |
| 555 | label: parts[parts.length - 1] ?? entry.path, |
| 556 | description: parts.length > 1 ? parts.slice(0, -1).join("/") : "", |
| 557 | }; |
| 558 | }), |
| 559 | ]; |
| 560 | } |
| 561 | |
| 562 | return []; |
| 563 | })(); |
| 564 | |
| 565 | const onSelect = (item: ComposerCommandItem) => { |
| 566 | if (!trigger) return; |
| 567 | if (item.type === "environment") { |
| 568 | if (!ownerKey || trigger.kind !== "path") return; |
| 569 | const record = environmentComposerContext(item.environmentId, item.label); |
| 570 | const existing = getComposerDraftSnapshot(ownerKey).context?.records ?? []; |
| 571 | const alreadyAttached = existing.some((entry) => entry.contextId === record.contextId); |
| 572 | if (!alreadyAttached && existing.length >= COMPOSER_CONTEXT_MAX_RECORDS) { |
| 573 | Dialog.alert( |
| 574 | gt("Too many context items"), |
| 575 | gt("Remove some context from the draft and try again."), |
| 576 | ); |
| 577 | return; |
| 578 | } |
| 579 | const result = replaceTextRange( |
| 580 | draftMessage, |
| 581 | trigger.rangeStart, |
| 582 | trigger.rangeEnd, |
| 583 | `${formatComposerContextReference(record)} `, |
| 584 | ); |
| 585 | onChangeDraftMessage(result.text); |
| 586 | if (!alreadyAttached) { |
| 587 | const draft = getComposerDraftSnapshot(ownerKey); |
| 588 | setComposerDraftContext(ownerKey, { |
| 589 | version: 1, |
| 590 | records: [...(draft.context?.records ?? []), record], |
| 591 | }); |
| 592 | } |
| 593 | setSelection({ start: result.cursor, end: result.cursor }); |
| 594 | return; |
| 595 | } |
| 596 | if (item.type === "thread") { |
| 597 | if (!ownerKey || trigger.kind !== "path") return; |
| 598 | const shell = threadShells.find( |
| 599 | (candidate) => |
| 600 | candidate.environmentId === item.thread.environmentId && |
| 601 | candidate.id === item.thread.threadId, |
| 602 | ); |
| 603 | if (!shell) return; |
| 604 | const record = threadContextRecord(item.thread, shell.title); |
| 605 | const existing = getComposerDraftSnapshot(ownerKey).context?.records ?? []; |
| 606 | const alreadyAttached = existing.some((entry) => entry.contextId === record.contextId); |
| 607 | if (!alreadyAttached && existing.length >= COMPOSER_CONTEXT_MAX_RECORDS) { |
| 608 | Dialog.alert( |
| 609 | gt("Too many context items"), |
| 610 | gt("Remove some context from the draft and try again."), |
| 611 | ); |
| 612 | return; |
| 613 | } |
| 614 | const result = replaceTextRange( |
| 615 | draftMessage, |
| 616 | trigger.rangeStart, |
| 617 | trigger.rangeEnd, |
| 618 | `${formatComposerContextReference(record)} `, |
| 619 | ); |
| 620 | onChangeDraftMessage(result.text); |
| 621 | if (!alreadyAttached) { |
| 622 | const draft = getComposerDraftSnapshot(ownerKey); |
| 623 | setComposerDraftContext(ownerKey, { |
| 624 | version: 1, |
| 625 | records: [...(draft.context?.records ?? []), record], |
| 626 | }); |
| 627 | } |
| 628 | setSelection({ start: result.cursor, end: result.cursor }); |
| 629 | return; |
| 630 | } |
| 631 | if (item.type === "pull-request") { |
| 632 | if ( |
| 633 | !ownerKey || |
| 634 | trigger.kind !== "pull-request" || |
| 635 | !items.some((candidate) => candidate.id === item.id) |
| 636 | ) |
| 637 | return; |
| 638 | const record = pullRequestComposerContext(item.pullRequest, uuidv4()); |
| 639 | if ( |
| 640 | (getComposerDraftSnapshot(ownerKey).context?.records.length ?? 0) >= |
| 641 | COMPOSER_CONTEXT_MAX_RECORDS |
| 642 | ) { |
| 643 | Dialog.alert( |
| 644 | gt("Too many context items"), |
| 645 | gt("Remove some context from the draft and try again."), |
| 646 | ); |
| 647 | return; |
| 648 | } |
| 649 | const result = replaceTextRange( |
| 650 | draftMessage, |
| 651 | trigger.rangeStart, |
| 652 | trigger.rangeEnd, |
| 653 | `${formatComposerContextReference(record)} `, |
| 654 | ); |
| 655 | onChangeDraftMessage(result.text); |
| 656 | const draft = getComposerDraftSnapshot(ownerKey); |
| 657 | setComposerDraftContext(ownerKey, { |
| 658 | version: 1, |
| 659 | records: [...(draft.context?.records ?? []), record], |
| 660 | }); |
| 661 | setSelection({ start: result.cursor, end: result.cursor }); |
| 662 | return; |
| 663 | } |
| 664 | |
| 665 | const clearTriggerThen = (action: () => void) => { |
| 666 | const cleared = replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, ""); |
| 667 | setSelection({ start: cleared.cursor, end: cleared.cursor }); |
| 668 | onChangeDraftMessage(cleared.text); |
| 669 | action(); |
| 670 | }; |
| 671 | if (item.type === "slash-command" && item.command === "model") { |
| 672 | clearTriggerThen(onOpenModelPicker); |
| 673 | return; |
| 674 | } |
| 675 | if (item.type === "slash-command" && item.command === "clear" && onFreshSession) { |
| 676 | clearTriggerThen(onFreshSession); |
| 677 | return; |
| 678 | } |
| 679 | if ( |
| 680 | item.type === "provider-slash-command" && |
| 681 | item.command.name === USAGE_LIMITS_COMMAND.name && |
| 682 | onUsageLimits |
| 683 | ) { |
| 684 | clearTriggerThen(onUsageLimits); |
| 685 | return; |
| 686 | } |
| 687 | |
| 688 | const result = resolveComposerCommandSelection({ draftMessage, trigger, item }); |
| 689 | setSelection({ start: result.cursor, end: result.cursor }); |
| 690 | onChangeDraftMessage(result.text); |
| 691 | }; |
| 692 | |
| 693 | return { |
| 694 | selection, |
| 695 | onSelectionChange, |
| 696 | trigger, |
| 697 | items, |
| 698 | skills, |
| 699 | isLoading: |
| 700 | trigger?.kind === "pull-request" ? pullRequestSearch.isPending : pathSearch.isPending, |
| 701 | error: |
| 702 | trigger?.kind === "pull-request" |
| 703 | ? pullRequestProjectId === null || pullRequestRepository === null |
| 704 | ? gt("Pull requests are unavailable for this project.") |
| 705 | : pullRequestSearch.error |
| 706 | : null, |
| 707 | onSelect, |
| 708 | }; |
| 709 | } |