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 { errorDisplayMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import { |
| 3 | foldSearchQuery, |
| 4 | PALETTE_SECONDARY_LIMIT, |
| 5 | PALETTE_THREAD_LIMIT, |
| 6 | rankSearchGroups, |
| 7 | scoreSearchTerms, |
| 8 | scoreThreadSearch, |
| 9 | type SearchMatchHint, |
| 10 | type SearchRange, |
| 11 | type ThreadSearchSubject, |
| 12 | } from "@t3tools/shared/paletteSearch"; |
| 13 | import { threadSearchSubject } from "@t3tools/client-runtime/state/thread-search"; |
| 14 | import type { CommandPaletteLinkedThreads } from "../commandPaletteBus"; |
| 15 | import { |
| 16 | addProjectRemoteSourceLabel, |
| 17 | addProjectRemoteSourcePathHint, |
| 18 | buildAddProjectRemoteSourceReadiness, |
| 19 | type AddProjectRemoteSource, |
| 20 | type AddProjectRemoteSourceReadiness, |
| 21 | } from "@t3tools/client-runtime/operations/projects"; |
| 22 | import { |
| 23 | type ScopedThreadRef, |
| 24 | type EnvironmentId, |
| 25 | type ProjectId, |
| 26 | type EnvironmentMachineKind, |
| 27 | type FilesystemBrowseEntry, |
| 28 | type KeybindingCommand, |
| 29 | type SourceControlDiscoveryResult, |
| 30 | type SourceControlRepositoryInfo, |
| 31 | THREAD_JUMP_KEYBINDING_COMMANDS, |
| 32 | } from "@t3tools/contracts"; |
| 33 | import { filterFilesystemBrowseEntries } from "@t3tools/client-runtime/state/filesystem"; |
| 34 | import { isShownUnderParent } from "@t3tools/client-runtime/state/threads"; |
| 35 | import { type ReactNode } from "react"; |
| 36 | import { msg } from "gt-react"; |
| 37 | import { m, type MessageResolver } from "../i18n/messages"; |
| 38 | import { formatRelativeTimeLabel } from "../timestampFormat"; |
| 39 | import { type Project, type SidebarThreadSummary, type Thread } from "../types"; |
| 40 | |
| 41 | export const RECENT_THREAD_LIMIT = 12; |
| 42 | const NO_THREAD_KEYS: ReadonlySet<string> = new Set(); |
| 43 | export const ITEM_ICON_CLASS = "size-4 text-icon-muted"; |
| 44 | export const ADDON_ICON_CLASS = "size-4"; |
| 45 | |
| 46 | export function buildLinkedThreadActionItems( |
| 47 | input: CommandPaletteLinkedThreads & { |
| 48 | query: string; |
| 49 | icon: ReactNode; |
| 50 | runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>; |
| 51 | }, |
| 52 | resolve: MessageResolver = m, |
| 53 | ): CommandPaletteActionItem[] { |
| 54 | return input.threads.map((thread) => ({ |
| 55 | kind: "action", |
| 56 | value: `thread:${input.environmentId}:${thread.id}`, |
| 57 | threadRef: { environmentId: input.environmentId, threadId: thread.id }, |
| 58 | title: thread.title || resolve(msg("Untitled thread")), |
| 59 | description: |
| 60 | thread.archivedAt === null ? resolve(msg("Linked thread")) : resolve(msg("Archived thread")), |
| 61 | searchTerms: [input.query, thread.title], |
| 62 | icon: input.icon, |
| 63 | run: () => input.runThread({ environmentId: input.environmentId, id: thread.id }), |
| 64 | })); |
| 65 | } |
| 66 | |
| 67 | export function browseInputEndPaddingClass(input: { |
| 68 | readonly willCreateProjectPath: boolean; |
| 69 | readonly hasHighlightedBrowseItem: boolean; |
| 70 | }): string { |
| 71 | if (input.willCreateProjectPath) { |
| 72 | return "*:data-[slot=autocomplete-input]:pe-38!"; |
| 73 | } |
| 74 | if (input.hasHighlightedBrowseItem) { |
| 75 | return "*:data-[slot=autocomplete-input]:pe-30!"; |
| 76 | } |
| 77 | return "*:data-[slot=autocomplete-input]:pe-24!"; |
| 78 | } |
| 79 | |
| 80 | export type SearchOverlayMode = "command" | "files" | "content"; |
| 81 | |
| 82 | export type CommandPaletteOpenIntent = |
| 83 | | { readonly kind: "add-project" | "new-thread-in" | "change-theme" } |
| 84 | | { |
| 85 | readonly kind: "search"; |
| 86 | readonly query: string; |
| 87 | readonly linkedThreads?: CommandPaletteLinkedThreads; |
| 88 | }; |
| 89 | |
| 90 | export interface CommandPaletteUiState { |
| 91 | readonly open: boolean; |
| 92 | readonly mode: SearchOverlayMode; |
| 93 | /** What the current palette session opened to; read once when the palette view mounts. */ |
| 94 | readonly openIntent: CommandPaletteOpenIntent | null; |
| 95 | /** Bumped by every intent so an open palette starts over from the new one. */ |
| 96 | readonly session: number; |
| 97 | readonly parentSearch?: CommandPaletteReturnContext; |
| 98 | readonly restoredSearch?: CommandPaletteReturnContext; |
| 99 | } |
| 100 | |
| 101 | export type CommandPaletteUiAction = |
| 102 | | { readonly _tag: "SetOpen"; readonly open: boolean } |
| 103 | | { readonly _tag: "ToggleMode"; readonly mode: SearchOverlayMode } |
| 104 | | { |
| 105 | readonly _tag: "OpenSearch"; |
| 106 | readonly query: string; |
| 107 | readonly linkedThreads?: CommandPaletteLinkedThreads; |
| 108 | } |
| 109 | | { readonly _tag: "OpenAddProject" } |
| 110 | | { readonly _tag: "OpenNewThreadIn" } |
| 111 | | { readonly _tag: "OpenChangeTheme" } |
| 112 | | { |
| 113 | readonly _tag: "OpenChildSearch"; |
| 114 | readonly mode: "files" | "content"; |
| 115 | readonly context: CommandPaletteReturnContext; |
| 116 | } |
| 117 | | { readonly _tag: "BackToCommand" }; |
| 118 | |
| 119 | export function reduceCommandPaletteUiState( |
| 120 | state: CommandPaletteUiState, |
| 121 | action: CommandPaletteUiAction, |
| 122 | ): CommandPaletteUiState { |
| 123 | const { session } = state; |
| 124 | const openWithIntent = (openIntent: CommandPaletteOpenIntent): CommandPaletteUiState => ({ |
| 125 | open: true, |
| 126 | mode: "command", |
| 127 | openIntent, |
| 128 | session: session + 1, |
| 129 | }); |
| 130 | switch (action._tag) { |
| 131 | case "SetOpen": |
| 132 | return action.open |
| 133 | ? { open: true, mode: "command", openIntent: state.openIntent, session } |
| 134 | : { open: false, mode: state.mode, openIntent: null, session }; |
| 135 | case "ToggleMode": |
| 136 | return state.open && state.mode === action.mode |
| 137 | ? { open: false, mode: state.mode, openIntent: null, session } |
| 138 | : { open: true, mode: action.mode, openIntent: null, session }; |
| 139 | case "OpenChildSearch": |
| 140 | return { |
| 141 | open: true, |
| 142 | mode: action.mode, |
| 143 | openIntent: null, |
| 144 | session, |
| 145 | parentSearch: action.context, |
| 146 | }; |
| 147 | case "BackToCommand": |
| 148 | return state.open && state.mode !== "command" |
| 149 | ? { |
| 150 | open: true, |
| 151 | mode: "command", |
| 152 | openIntent: null, |
| 153 | session, |
| 154 | ...(state.parentSearch ? { restoredSearch: state.parentSearch } : {}), |
| 155 | } |
| 156 | : state; |
| 157 | case "OpenSearch": |
| 158 | return openWithIntent({ |
| 159 | kind: "search", |
| 160 | query: action.query, |
| 161 | ...(action.linkedThreads ? { linkedThreads: action.linkedThreads } : {}), |
| 162 | }); |
| 163 | case "OpenAddProject": |
| 164 | return openWithIntent({ kind: "add-project" }); |
| 165 | case "OpenNewThreadIn": |
| 166 | return openWithIntent({ kind: "new-thread-in" }); |
| 167 | case "OpenChangeTheme": |
| 168 | return openWithIntent({ kind: "change-theme" }); |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | /** Where "Add project" starts, given the environments that can take a new project. */ |
| 173 | export type AddProjectEntry = |
| 174 | | { readonly kind: "connect-environment" } |
| 175 | | { readonly kind: "choose-environment" } |
| 176 | | { readonly kind: "choose-source"; readonly environmentId: EnvironmentId }; |
| 177 | |
| 178 | export function resolveAddProjectEntry( |
| 179 | options: ReadonlyArray<Pick<AddProjectEnvironmentOption, "environmentId">>, |
| 180 | defaultEnvironmentId: EnvironmentId | null, |
| 181 | ): AddProjectEntry { |
| 182 | if (options.length === 0) return { kind: "connect-environment" }; |
| 183 | if (options.length > 1 || defaultEnvironmentId === null) return { kind: "choose-environment" }; |
| 184 | return { kind: "choose-source", environmentId: defaultEnvironmentId }; |
| 185 | } |
| 186 | |
| 187 | export interface CommandPaletteThreadContentMatch { |
| 188 | readonly source: "user" | "assistant"; |
| 189 | readonly snippet: string; |
| 190 | readonly query: string; |
| 191 | } |
| 192 | |
| 193 | export interface CommandPaletteItem { |
| 194 | readonly kind: "action" | "submenu"; |
| 195 | readonly value: string; |
| 196 | readonly searchTerms: ReadonlyArray<string>; |
| 197 | readonly title: ReactNode; |
| 198 | /** The title as plain text, for searching, when `title` is styled. */ |
| 199 | readonly searchTitle?: string; |
| 200 | readonly description?: ReactNode; |
| 201 | readonly threadContentMatch?: CommandPaletteThreadContentMatch; |
| 202 | readonly timestamp?: string; |
| 203 | /** Thread rows rank by this, with use history, instead of by `searchTerms`. */ |
| 204 | readonly threadSearch?: ThreadSearchSubject; |
| 205 | readonly threadRef?: ScopedThreadRef; |
| 206 | /** Shown in place of the description when the match is not in the title. */ |
| 207 | readonly matchHint?: SearchMatchHint; |
| 208 | readonly icon: ReactNode; |
| 209 | readonly disabled?: boolean; |
| 210 | readonly titleLeadingContent?: ReactNode; |
| 211 | readonly titleTrailingContent?: ReactNode; |
| 212 | readonly shortcutCommand?: KeybindingCommand; |
| 213 | readonly secondary?: boolean; |
| 214 | } |
| 215 | |
| 216 | export interface CommandPaletteActionItem extends CommandPaletteItem { |
| 217 | readonly kind: "action"; |
| 218 | readonly keepOpen?: boolean; |
| 219 | readonly run: () => Promise<void>; |
| 220 | /** A pin toggle on the row, also reached with the pin shortcut while the row is highlighted. */ |
| 221 | readonly pin?: CommandPaletteItemPin; |
| 222 | /** Set on toggle rows; exposed to assistive technology as `aria-checked`. */ |
| 223 | readonly checked?: boolean; |
| 224 | } |
| 225 | |
| 226 | export interface CommandPaletteItemPin { |
| 227 | readonly name: string; |
| 228 | readonly pinned: boolean; |
| 229 | readonly toggle: () => void; |
| 230 | } |
| 231 | |
| 232 | export interface CommandPaletteSubmenuItem extends CommandPaletteItem { |
| 233 | readonly kind: "submenu"; |
| 234 | readonly addonIcon: ReactNode; |
| 235 | readonly groups: ReadonlyArray<CommandPaletteGroup>; |
| 236 | readonly initialQuery?: string; |
| 237 | } |
| 238 | |
| 239 | export interface CommandPaletteGroup { |
| 240 | readonly value: string; |
| 241 | readonly label: string; |
| 242 | readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>; |
| 243 | } |
| 244 | |
| 245 | export interface CommandPaletteView { |
| 246 | readonly addonIcon: ReactNode; |
| 247 | readonly groups: ReadonlyArray<CommandPaletteGroup>; |
| 248 | readonly initialQuery?: string; |
| 249 | } |
| 250 | |
| 251 | // Child search unmounts the palette; retain search data without its view closures. |
| 252 | export interface CommandPaletteReturnContext { |
| 253 | readonly query: string; |
| 254 | readonly linkedThreadSearch: Extract<CommandPaletteOpenIntent, { kind: "search" }> | null; |
| 255 | } |
| 256 | |
| 257 | export interface CommandPaletteSearchState { |
| 258 | readonly query: string; |
| 259 | readonly views: ReadonlyArray<{ |
| 260 | readonly view: CommandPaletteView; |
| 261 | readonly parentQuery: string; |
| 262 | }>; |
| 263 | } |
| 264 | |
| 265 | export function createCommandPaletteSearchState(query = ""): CommandPaletteSearchState { |
| 266 | return { query, views: [] }; |
| 267 | } |
| 268 | |
| 269 | export function reduceCommandPaletteSearchState( |
| 270 | state: CommandPaletteSearchState, |
| 271 | action: |
| 272 | | { readonly type: "query"; readonly query: string } |
| 273 | | { readonly type: "push"; readonly view: CommandPaletteView } |
| 274 | | { readonly type: "back" } |
| 275 | | { readonly type: "reset"; readonly query?: string }, |
| 276 | ): CommandPaletteSearchState { |
| 277 | switch (action.type) { |
| 278 | case "query": |
| 279 | return { ...state, query: action.query }; |
| 280 | case "push": |
| 281 | return { |
| 282 | query: action.view.initialQuery ?? "", |
| 283 | views: [...state.views, { view: action.view, parentQuery: state.query }], |
| 284 | }; |
| 285 | case "back": { |
| 286 | const parent = state.views.at(-1); |
| 287 | return parent ? { query: parent.parentQuery, views: state.views.slice(0, -1) } : state; |
| 288 | } |
| 289 | case "reset": |
| 290 | return createCommandPaletteSearchState(action.query); |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | export type CommandPaletteRow = |
| 295 | | { |
| 296 | readonly kind: "label"; |
| 297 | readonly key: string; |
| 298 | readonly label: string; |
| 299 | readonly first: boolean; |
| 300 | } |
| 301 | | { |
| 302 | readonly kind: "item"; |
| 303 | readonly key: string; |
| 304 | readonly item: CommandPaletteActionItem | CommandPaletteSubmenuItem; |
| 305 | readonly itemIndex: number | null; |
| 306 | }; |
| 307 | |
| 308 | export function buildCommandPaletteRows(groups: ReadonlyArray<CommandPaletteGroup>) { |
| 309 | const rows: CommandPaletteRow[] = []; |
| 310 | const itemValues: string[] = []; |
| 311 | const rowIndexByItemIndex: number[] = []; |
| 312 | for (const group of groups) { |
| 313 | if (group.label) { |
| 314 | rows.push({ |
| 315 | kind: "label", |
| 316 | key: `group:${group.value}`, |
| 317 | label: group.label, |
| 318 | first: rows.length === 0, |
| 319 | }); |
| 320 | } |
| 321 | for (const item of group.items) { |
| 322 | const itemIndex = item.disabled ? null : itemValues.length; |
| 323 | if (itemIndex !== null) { |
| 324 | itemValues.push(item.value); |
| 325 | rowIndexByItemIndex.push(rows.length); |
| 326 | } |
| 327 | rows.push({ kind: "item", key: `${group.value}:${item.value}`, item, itemIndex }); |
| 328 | } |
| 329 | } |
| 330 | return { rows, itemValues, rowIndexByItemIndex }; |
| 331 | } |
| 332 | |
| 333 | export function findHighlightedCommandPaletteItem( |
| 334 | groups: ReadonlyArray<CommandPaletteGroup>, |
| 335 | highlightedItemValue: string | null, |
| 336 | ): CommandPaletteActionItem | CommandPaletteSubmenuItem | null { |
| 337 | if (highlightedItemValue === null) return null; |
| 338 | for (const group of groups) { |
| 339 | for (const item of group.items) { |
| 340 | if (item.value === highlightedItemValue && !item.disabled) return item; |
| 341 | } |
| 342 | } |
| 343 | return null; |
| 344 | } |
| 345 | |
| 346 | export function enumerateCommandPaletteItems( |
| 347 | items: ReadonlyArray<CommandPaletteActionItem>, |
| 348 | ): CommandPaletteActionItem[] { |
| 349 | return items.map((item, index) => { |
| 350 | const shortcutCommand = THREAD_JUMP_KEYBINDING_COMMANDS[index]; |
| 351 | if (shortcutCommand) return { ...item, shortcutCommand }; |
| 352 | |
| 353 | const { shortcutCommand: _shortcutCommand, ...itemWithoutShortcut } = item; |
| 354 | return itemWithoutShortcut; |
| 355 | }); |
| 356 | } |
| 357 | |
| 358 | export type CommandPaletteMode = "root" | "root-browse" | "submenu" | "submenu-browse"; |
| 359 | |
| 360 | export type CommandPaletteProject = Project & { readonly displayName: string }; |
| 361 | |
| 362 | export function buildCommandPaletteProjectMetadata( |
| 363 | input: { |
| 364 | readonly projects: ReadonlyArray<Pick<Project, "environmentId" | "title" | "workspaceRoot">>; |
| 365 | readonly locationByEnvironmentId: ReadonlyMap<EnvironmentId, { readonly label: string }>; |
| 366 | }, |
| 367 | resolve: MessageResolver = m, |
| 368 | ) { |
| 369 | const searchTerms: string[] = []; |
| 370 | const environmentLabels = new Set<string>(); |
| 371 | |
| 372 | for (const project of input.projects) { |
| 373 | const label = |
| 374 | input.locationByEnvironmentId.get(project.environmentId)?.label ?? |
| 375 | resolve(msg("Remote", { $context: "machine location" })); |
| 376 | searchTerms.push(project.title, project.workspaceRoot, label); |
| 377 | environmentLabels.add(label); |
| 378 | } |
| 379 | |
| 380 | return { searchTerms, environmentLabels: [...environmentLabels] }; |
| 381 | } |
| 382 | |
| 383 | export function buildProjectActionItems(input: { |
| 384 | projects: ReadonlyArray<CommandPaletteProject>; |
| 385 | valuePrefix: string; |
| 386 | icon: (project: CommandPaletteProject) => ReactNode; |
| 387 | runProject: (project: CommandPaletteProject) => Promise<void>; |
| 388 | searchTerms?: (project: CommandPaletteProject) => ReadonlyArray<string>; |
| 389 | renderDescription?: (project: CommandPaletteProject) => ReactNode; |
| 390 | shortcutCommand?: KeybindingCommand; |
| 391 | pin?: (project: CommandPaletteProject) => CommandPaletteItemPin | null; |
| 392 | }): CommandPaletteActionItem[] { |
| 393 | return input.projects.map((project) => { |
| 394 | const pin = input.pin?.(project) ?? null; |
| 395 | return { |
| 396 | kind: "action", |
| 397 | value: `${input.valuePrefix}:${project.environmentId}:${project.id}`, |
| 398 | searchTerms: [ |
| 399 | project.displayName, |
| 400 | project.title, |
| 401 | project.workspaceRoot, |
| 402 | ...(input.searchTerms?.(project) ?? []), |
| 403 | ], |
| 404 | title: project.displayName, |
| 405 | description: input.renderDescription?.(project) ?? project.workspaceRoot, |
| 406 | icon: input.icon(project), |
| 407 | ...(input.shortcutCommand !== undefined ? { shortcutCommand: input.shortcutCommand } : {}), |
| 408 | ...(pin ? { pin } : {}), |
| 409 | run: async () => { |
| 410 | await input.runProject(project); |
| 411 | }, |
| 412 | }; |
| 413 | }); |
| 414 | } |
| 415 | |
| 416 | export type BuildThreadActionItemsThread = Pick< |
| 417 | SidebarThreadSummary, |
| 418 | | "archivedAt" |
| 419 | | "branch" |
| 420 | | "createdAt" |
| 421 | | "environmentId" |
| 422 | | "id" |
| 423 | | "lineage" |
| 424 | | "modelSelection" |
| 425 | | "projectId" |
| 426 | | "runtime" |
| 427 | | "title" |
| 428 | | "worktreePath" |
| 429 | > & |
| 430 | Partial< |
| 431 | Pick< |
| 432 | SidebarThreadSummary, |
| 433 | "pullRequests" | "linkedPullRequest" | "branchPullRequest" | "opens" | "latestUserMessageAt" |
| 434 | > |
| 435 | > & { |
| 436 | updatedAt: string; |
| 437 | }; |
| 438 | |
| 439 | export function buildThreadActionItems<TThread extends BuildThreadActionItemsThread>( |
| 440 | input: { |
| 441 | threads: ReadonlyArray<TThread>; |
| 442 | activeThread?: Pick<Thread, "environmentId" | "id">; |
| 443 | projectByKey: ReadonlyMap<string, Pick<Project, "title">>; |
| 444 | icon: ReactNode; |
| 445 | renderLeadingContent?: (thread: TThread) => ReactNode; |
| 446 | renderTrailingContent?: (thread: TThread) => ReactNode; |
| 447 | renderDescription?: (thread: TThread, meta: { projectTitle: string | undefined }) => ReactNode; |
| 448 | runThread: (thread: TThread) => Promise<void>; |
| 449 | /** Makes the environment searchable; pass it only with two or more environments. */ |
| 450 | environmentLabelOf?: (thread: TThread) => string | null; |
| 451 | /** Tasks linked environments run for a listed thread; they open from under that thread. */ |
| 452 | delegatedUnderParent?: ReadonlySet<string>; |
| 453 | }, |
| 454 | resolve: MessageResolver = m, |
| 455 | ): CommandPaletteActionItem[] { |
| 456 | const delegatedUnderParent = input.delegatedUnderParent ?? NO_THREAD_KEYS; |
| 457 | // Callers order these: recents by last use, search results by rank. |
| 458 | const visibleThreads = input.threads.filter( |
| 459 | (thread) => |
| 460 | thread.archivedAt === null && |
| 461 | !isShownUnderParent( |
| 462 | { environmentId: thread.environmentId, threadId: thread.id }, |
| 463 | thread.lineage, |
| 464 | delegatedUnderParent, |
| 465 | ), |
| 466 | ); |
| 467 | |
| 468 | return visibleThreads.map((thread) => { |
| 469 | const projectTitle = input.projectByKey.get( |
| 470 | `${thread.environmentId}:${thread.projectId}`, |
| 471 | )?.title; |
| 472 | const descriptionParts: string[] = []; |
| 473 | |
| 474 | if (projectTitle) { |
| 475 | descriptionParts.push(projectTitle); |
| 476 | } |
| 477 | if (thread.branch) { |
| 478 | descriptionParts.push(`#${thread.branch}`); |
| 479 | } |
| 480 | const isCurrent = |
| 481 | thread.id === input.activeThread?.id && |
| 482 | thread.environmentId === input.activeThread.environmentId; |
| 483 | if (isCurrent) { |
| 484 | descriptionParts.push(resolve(msg("Current thread"))); |
| 485 | } |
| 486 | |
| 487 | const leadingContent = input.renderLeadingContent?.(thread); |
| 488 | const trailingContent = input.renderTrailingContent?.(thread); |
| 489 | const description = input.renderDescription |
| 490 | ? input.renderDescription(thread, { projectTitle }) |
| 491 | : descriptionParts.join(` · `); |
| 492 | |
| 493 | return Object.assign( |
| 494 | { |
| 495 | kind: "action" as const, |
| 496 | value: `thread:${thread.environmentId}:${thread.id}`, |
| 497 | threadRef: { environmentId: thread.environmentId, threadId: thread.id }, |
| 498 | searchTerms: [thread.title], |
| 499 | threadSearch: threadSearchSubject( |
| 500 | { |
| 501 | ...thread, |
| 502 | latestUserMessageAt: thread.latestUserMessageAt ?? null, |
| 503 | opens: thread.opens ?? null, |
| 504 | }, |
| 505 | projectTitle, |
| 506 | input.environmentLabelOf?.(thread), |
| 507 | ), |
| 508 | title: thread.title, |
| 509 | description, |
| 510 | timestamp: formatRelativeTimeLabel( |
| 511 | thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt, |
| 512 | undefined, |
| 513 | resolve, |
| 514 | ), |
| 515 | icon: input.icon, |
| 516 | }, |
| 517 | leadingContent ? { titleLeadingContent: leadingContent } : {}, |
| 518 | trailingContent ? { titleTrailingContent: trailingContent } : {}, |
| 519 | // Last in its group: picking the thread already open does nothing. |
| 520 | isCurrent ? { secondary: true } : {}, |
| 521 | { |
| 522 | run: async () => { |
| 523 | await input.runThread(thread); |
| 524 | }, |
| 525 | }, |
| 526 | ); |
| 527 | }); |
| 528 | } |
| 529 | |
| 530 | type PaletteItem = CommandPaletteActionItem | CommandPaletteSubmenuItem; |
| 531 | |
| 532 | function rankPaletteItem( |
| 533 | item: PaletteItem, |
| 534 | normalizedQuery: string, |
| 535 | now: number, |
| 536 | options: { readonly typos: boolean }, |
| 537 | ): { |
| 538 | readonly score: number; |
| 539 | readonly quality: number; |
| 540 | readonly groupQuality?: number; |
| 541 | readonly strong: boolean; |
| 542 | readonly ranges: ReadonlyArray<SearchRange>; |
| 543 | readonly explain?: () => SearchMatchHint | undefined; |
| 544 | readonly pickedAt?: number; |
| 545 | readonly pickedExactly?: boolean; |
| 546 | } | null { |
| 547 | const match = scorePaletteItem(item, normalizedQuery, now, options); |
| 548 | // A row listed last in its group (a keybinding setting, the open thread) |
| 549 | // does not decide where the group sits. |
| 550 | return match && item.secondary ? { ...match, groupQuality: 0 } : match; |
| 551 | } |
| 552 | |
| 553 | function scorePaletteItem( |
| 554 | item: PaletteItem, |
| 555 | normalizedQuery: string, |
| 556 | now: number, |
| 557 | options: { readonly typos: boolean }, |
| 558 | ) { |
| 559 | if (item.threadSearch) return scoreThreadSearch(normalizedQuery, item.threadSearch, now, options); |
| 560 | // The title names the item; search terms are keywords. Ranges index the |
| 561 | // first term, so they only highlight a title that is that term. |
| 562 | const name = typeof item.title === "string" ? item.title : item.searchTitle; |
| 563 | const terms = |
| 564 | name !== undefined && name !== item.searchTerms[0] |
| 565 | ? [name, ...item.searchTerms] |
| 566 | : item.searchTerms; |
| 567 | const match = scoreSearchTerms(normalizedQuery, terms, options); |
| 568 | return match && (item.title === terms[0] ? match : { ...match, ranges: [] }); |
| 569 | } |
| 570 | |
| 571 | /** |
| 572 | * Equal match classes put commands before threads, so "new" runs "New thread". |
| 573 | * Server message matches stay in a final group so late results cannot move earlier rows. |
| 574 | */ |
| 575 | export function filterCommandPaletteGroups( |
| 576 | input: { |
| 577 | activeGroups: ReadonlyArray<CommandPaletteGroup>; |
| 578 | query: string; |
| 579 | isInSubmenu: boolean; |
| 580 | /** Submenu options join the root search, and a submenu with no match falls back to it. */ |
| 581 | allOptions?: { |
| 582 | readonly rootGroups: ReadonlyArray<CommandPaletteGroup>; |
| 583 | readonly nestedItems: ReadonlyArray<CommandPaletteActionItem>; |
| 584 | }; |
| 585 | projectSearchItems: ReadonlyArray<CommandPaletteActionItem>; |
| 586 | settingsSearchItems?: ReadonlyArray<CommandPaletteActionItem>; |
| 587 | threadSearchItems: ReadonlyArray<CommandPaletteActionItem>; |
| 588 | /** Threads whose messages match, best first; threads already listed are skipped. */ |
| 589 | threadMessageItems?: ReadonlyArray<CommandPaletteActionItem>; |
| 590 | now?: number; |
| 591 | }, |
| 592 | resolve: MessageResolver = m, |
| 593 | ): CommandPaletteGroup[] { |
| 594 | if (input.allOptions && input.isInSubmenu) { |
| 595 | const { allOptions, ...submenuInput } = input; |
| 596 | const scoped = filterCommandPaletteGroups(submenuInput, resolve); |
| 597 | if (scoped.length > 0 || input.query.trim().length === 0) return scoped; |
| 598 | return filterCommandPaletteGroups( |
| 599 | { |
| 600 | ...input, |
| 601 | activeGroups: allOptions.rootGroups, |
| 602 | isInSubmenu: false, |
| 603 | }, |
| 604 | resolve, |
| 605 | ); |
| 606 | } |
| 607 | |
| 608 | const isActionsFilter = input.query.startsWith(">"); |
| 609 | const searchQuery = isActionsFilter ? input.query.slice(1) : input.query; |
| 610 | const normalizedQuery = foldSearchQuery(searchQuery); |
| 611 | |
| 612 | if (normalizedQuery.length === 0) { |
| 613 | if (isActionsFilter) { |
| 614 | return input.activeGroups.filter((group) => group.value === "actions"); |
| 615 | } |
| 616 | return [...input.activeGroups]; |
| 617 | } |
| 618 | |
| 619 | let baseGroups = [...input.activeGroups]; |
| 620 | if (isActionsFilter) { |
| 621 | baseGroups = baseGroups.filter((group) => group.value === "actions"); |
| 622 | } else if (!input.isInSubmenu) { |
| 623 | baseGroups = baseGroups.filter((group) => group.value !== "recent-threads"); |
| 624 | } |
| 625 | |
| 626 | const searchableGroups = [...baseGroups]; |
| 627 | const searchesEverything = !input.isInSubmenu && !isActionsFilter; |
| 628 | // On equal match classes, groups keep this order: threads, what people search |
| 629 | // for most, right after commands. |
| 630 | if (searchesEverything) { |
| 631 | if (input.allOptions && input.allOptions.nestedItems.length > 0) { |
| 632 | searchableGroups.push({ |
| 633 | value: "nested-search", |
| 634 | label: resolve(msg("Suggestions")), |
| 635 | items: input.allOptions.nestedItems, |
| 636 | }); |
| 637 | } |
| 638 | if (input.threadSearchItems.length > 0) { |
| 639 | searchableGroups.push({ |
| 640 | value: "threads-search", |
| 641 | label: resolve(msg("Threads")), |
| 642 | items: input.threadSearchItems, |
| 643 | }); |
| 644 | } |
| 645 | if (input.projectSearchItems.length > 0) { |
| 646 | searchableGroups.push({ |
| 647 | value: "projects-search", |
| 648 | label: resolve(msg("Projects")), |
| 649 | items: input.projectSearchItems, |
| 650 | }); |
| 651 | } |
| 652 | if (input.settingsSearchItems && input.settingsSearchItems.length > 0) { |
| 653 | searchableGroups.push({ |
| 654 | value: "settings-search", |
| 655 | label: resolve(msg("Settings")), |
| 656 | items: input.settingsSearchItems, |
| 657 | }); |
| 658 | } |
| 659 | } |
| 660 | |
| 661 | const now = input.now ?? Date.now(); |
| 662 | const ranked = rankSearchGroups( |
| 663 | searchableGroups.map((group) => ({ group, items: group.items })), |
| 664 | (item, options) => rankPaletteItem(item, normalizedQuery, now, options), |
| 665 | ); |
| 666 | const threadsMatch = ranked.some(({ group }) => group.value === "threads-search"); |
| 667 | const groups = ranked.map(({ group, ranked }): CommandPaletteGroup => { |
| 668 | // Secondary items stay below the rest; the sort is stable, so score order holds. |
| 669 | const limit = |
| 670 | group.value === "threads-search" |
| 671 | ? PALETTE_THREAD_LIMIT |
| 672 | : group.value === "nested-search" || (searchesEverything && threadsMatch) |
| 673 | ? PALETTE_SECONDARY_LIMIT |
| 674 | : ranked.length; |
| 675 | // Hints are built only for the rows shown. |
| 676 | const items = ranked |
| 677 | .toSorted( |
| 678 | (left, right) => |
| 679 | Number(left.item.secondary ?? false) - Number(right.item.secondary ?? false), |
| 680 | ) |
| 681 | .slice(0, limit) |
| 682 | .map(({ item, match }) => { |
| 683 | if (match.ranges.length > 0) return item; |
| 684 | // Built only for the rows shown. |
| 685 | const matchHint = match.explain?.(); |
| 686 | return matchHint ? { ...item, matchHint } : item; |
| 687 | }); |
| 688 | return { value: group.value, label: group.label, items }; |
| 689 | }); |
| 690 | |
| 691 | if (!searchesEverything) return groups; |
| 692 | const listed = new Set(groups.flatMap((group) => group.items.map((item) => item.value))); |
| 693 | // The items arrive cut to what the palette shows; see `nextShownOrder`. |
| 694 | const messageItems = (input.threadMessageItems ?? []).filter((item) => !listed.has(item.value)); |
| 695 | return messageItems.length === 0 |
| 696 | ? groups |
| 697 | : [ |
| 698 | ...groups, |
| 699 | { value: "threads-messages", label: resolve(msg("In messages")), items: messageItems }, |
| 700 | ]; |
| 701 | } |
| 702 | |
| 703 | /** Every option inside a submenu as one row, e.g. "New thread in t3code" or "Change theme: Dracula". */ |
| 704 | export function buildNestedSearchItems( |
| 705 | items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>, |
| 706 | query: string, |
| 707 | ): CommandPaletteActionItem[] { |
| 708 | const nameOf = (item: CommandPaletteItem) => |
| 709 | typeof item.title === "string" ? item.title : item.searchTitle; |
| 710 | const topLevelNames = new Set(items.map(nameOf)); |
| 711 | const foldedQuery = foldSearchQuery(query); |
| 712 | return items.flatMap((parent) => { |
| 713 | if (parent.kind !== "submenu" || typeof parent.title !== "string") return []; |
| 714 | const stem = parent.title.replace(/(\.\.\.|…)$/u, ""); |
| 715 | // A query that only names the submenu ("new thread in") wants the submenu row itself. |
| 716 | if (foldSearchQuery(stem).startsWith(foldedQuery)) return []; |
| 717 | const prefix = stem === parent.title ? `${stem}: ` : `${stem.trimEnd()} `; |
| 718 | return parent.groups.flatMap((group) => |
| 719 | group.items.flatMap((child) => { |
| 720 | const name = nameOf(child); |
| 721 | if (child.kind !== "action" || name === undefined) return []; |
| 722 | const title = `${prefix}${name}`; |
| 723 | if (topLevelNames.has(title)) return []; |
| 724 | const { searchTitle: _searchTitle, ...rest } = child; |
| 725 | // Only the combined title: child keywords like "theme" would list every theme. |
| 726 | return [{ ...rest, title, searchTerms: [title] }]; |
| 727 | }), |
| 728 | ); |
| 729 | }); |
| 730 | } |
| 731 | |
| 732 | export function buildBrowseGroups( |
| 733 | input: { |
| 734 | browseEntries: ReadonlyArray<FilesystemBrowseEntry>; |
| 735 | browseQuery: string; |
| 736 | canBrowseUp: boolean; |
| 737 | upIcon: ReactNode; |
| 738 | directoryIcon: ReactNode; |
| 739 | browseUp: () => void | Promise<void>; |
| 740 | browseTo: (name: string) => void | Promise<void>; |
| 741 | }, |
| 742 | resolve: MessageResolver = m, |
| 743 | ): CommandPaletteGroup[] { |
| 744 | const items: CommandPaletteActionItem[] = []; |
| 745 | |
| 746 | if (input.canBrowseUp) { |
| 747 | items.push({ |
| 748 | kind: "action", |
| 749 | value: "browse:up", |
| 750 | searchTerms: [input.browseQuery, ".."], |
| 751 | title: "..", |
| 752 | icon: input.upIcon, |
| 753 | keepOpen: true, |
| 754 | run: async () => { |
| 755 | await input.browseUp(); |
| 756 | }, |
| 757 | }); |
| 758 | } |
| 759 | |
| 760 | for (const entry of input.browseEntries) { |
| 761 | items.push({ |
| 762 | kind: "action", |
| 763 | value: `browse:${entry.fullPath}`, |
| 764 | searchTerms: [input.browseQuery, entry.fullPath, entry.name], |
| 765 | title: entry.name, |
| 766 | icon: input.directoryIcon, |
| 767 | keepOpen: true, |
| 768 | run: async () => { |
| 769 | await input.browseTo(entry.name); |
| 770 | }, |
| 771 | }); |
| 772 | } |
| 773 | |
| 774 | return [{ value: "directories", label: resolve(msg("Directories")), items }]; |
| 775 | } |
| 776 | |
| 777 | export function filterPinnedBrowseEntries(input: { |
| 778 | browseEntries: ReadonlyArray<FilesystemBrowseEntry>; |
| 779 | filterQuery: string; |
| 780 | pinnedDirectoryName: string; |
| 781 | caseSensitive: boolean; |
| 782 | }): ReturnType<typeof filterFilesystemBrowseEntries> { |
| 783 | const namesMatch = (left: string, right: string) => |
| 784 | input.caseSensitive ? left === right : left.toLowerCase() === right.toLowerCase(); |
| 785 | const visibleFilterQuery = namesMatch(input.filterQuery, input.pinnedDirectoryName) |
| 786 | ? "" |
| 787 | : input.filterQuery; |
| 788 | const { visibleEntries } = filterFilesystemBrowseEntries(input.browseEntries, visibleFilterQuery); |
| 789 | const normalizedFilterQuery = input.filterQuery.normalize("NFC"); |
| 790 | const normalizedMatches = input.browseEntries.filter((entry) => |
| 791 | namesMatch(entry.name.normalize("NFC"), normalizedFilterQuery), |
| 792 | ); |
| 793 | const exactEntry = |
| 794 | input.filterQuery.length > 0 |
| 795 | ? (input.browseEntries.find((entry) => namesMatch(entry.name, input.filterQuery)) ?? |
| 796 | (normalizedMatches.length === 1 ? normalizedMatches[0] : null)) |
| 797 | : null; |
| 798 | return { visibleEntries, exactEntry }; |
| 799 | } |
| 800 | |
| 801 | export function getCommandPaletteMode(input: { |
| 802 | currentView: CommandPaletteView | null; |
| 803 | isBrowsing: boolean; |
| 804 | }): CommandPaletteMode { |
| 805 | if (input.currentView) { |
| 806 | return input.isBrowsing ? "submenu-browse" : "submenu"; |
| 807 | } |
| 808 | return input.isBrowsing ? "root-browse" : "root"; |
| 809 | } |
| 810 | |
| 811 | export function buildRootGroups( |
| 812 | input: { |
| 813 | actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>; |
| 814 | recentThreadItems: ReadonlyArray<CommandPaletteActionItem>; |
| 815 | }, |
| 816 | resolve: MessageResolver = m, |
| 817 | ): CommandPaletteGroup[] { |
| 818 | const groups: CommandPaletteGroup[] = []; |
| 819 | if (input.actionItems.length > 0) { |
| 820 | groups.push({ value: "actions", label: resolve(msg("Actions")), items: input.actionItems }); |
| 821 | } |
| 822 | if (input.recentThreadItems.length > 0) { |
| 823 | groups.push({ |
| 824 | value: "recent-threads", |
| 825 | label: resolve(msg("Recent Threads")), |
| 826 | items: input.recentThreadItems, |
| 827 | }); |
| 828 | } |
| 829 | return groups; |
| 830 | } |
| 831 | |
| 832 | export function getCommandPaletteInputPlaceholder( |
| 833 | mode: CommandPaletteMode, |
| 834 | resolve: MessageResolver = m, |
| 835 | ): string { |
| 836 | switch (mode) { |
| 837 | case "root": |
| 838 | return resolve(msg("Search commands, projects, and threads...")); |
| 839 | case "root-browse": |
| 840 | return resolve(msg("Enter project path (e.g. ~/projects/my-app)")); |
| 841 | case "submenu": |
| 842 | return resolve(msg("Search...")); |
| 843 | case "submenu-browse": |
| 844 | return resolve(msg("Enter path (e.g. ~/projects/my-app)")); |
| 845 | } |
| 846 | } |
| 847 | |
| 848 | export function getEnvironmentBrowsePlatform(os: string | null | undefined): string { |
| 849 | if (os === "windows") { |
| 850 | return "Win32"; |
| 851 | } |
| 852 | if (os === "darwin") { |
| 853 | return "MacIntel"; |
| 854 | } |
| 855 | if (os === "linux") { |
| 856 | return "Linux"; |
| 857 | } |
| 858 | return typeof navigator === "undefined" ? "" : navigator.platform; |
| 859 | } |
| 860 | |
| 861 | export interface AddProjectEnvironmentOption { |
| 862 | readonly environmentId: EnvironmentId; |
| 863 | readonly label: string; |
| 864 | readonly machine: EnvironmentMachineKind; |
| 865 | readonly isPrimary: boolean; |
| 866 | readonly isConnected: boolean; |
| 867 | readonly status: string; |
| 868 | } |
| 869 | |
| 870 | export type AddProjectCloneFlow = |
| 871 | | { |
| 872 | readonly step: "repository"; |
| 873 | readonly environmentId: EnvironmentId; |
| 874 | readonly source: AddProjectRemoteSource; |
| 875 | } |
| 876 | | { |
| 877 | readonly step: "confirm"; |
| 878 | readonly environmentId: EnvironmentId; |
| 879 | readonly source: AddProjectRemoteSource; |
| 880 | readonly repositoryInput: string; |
| 881 | readonly repository: SourceControlRepositoryInfo | null; |
| 882 | readonly remoteUrl: string; |
| 883 | }; |
| 884 | |
| 885 | export function remoteProjectInputPlaceholder( |
| 886 | flow: AddProjectCloneFlow | null, |
| 887 | resolve: MessageResolver = m, |
| 888 | ): string | null { |
| 889 | if (!flow) return null; |
| 890 | if (flow.step === "confirm") return null; |
| 891 | if (flow.source === "url") { |
| 892 | return resolve(msg("Enter Git clone URL")); |
| 893 | } |
| 894 | return resolve( |
| 895 | msg("Enter {source} repository ({hint})", { |
| 896 | source: addProjectRemoteSourceLabel(flow.source, resolve), |
| 897 | hint: addProjectRemoteSourcePathHint(flow.source, resolve), |
| 898 | }), |
| 899 | ); |
| 900 | } |
| 901 | |
| 902 | export function buildPaletteRemoteSourceReadiness( |
| 903 | discovery: SourceControlDiscoveryResult | null, |
| 904 | resolve: MessageResolver = m, |
| 905 | ): AddProjectRemoteSourceReadiness { |
| 906 | return buildAddProjectRemoteSourceReadiness(discovery, resolve); |
| 907 | } |
| 908 | |
| 909 | export function errorMessage(error: unknown, resolve: MessageResolver = m): string { |
| 910 | return ( |
| 911 | (error instanceof Error ? errorDisplayMessage(error, resolve) : null) ?? |
| 912 | resolve(msg("An error occurred.")) |
| 913 | ); |
| 914 | } |
| 915 | |
| 916 | const OVERLAY_MODE_BY_COMMAND = { |
| 917 | "commandPalette.toggle": "command", |
| 918 | "filePicker.toggle": "files", |
| 919 | "projectSearch.toggle": "content", |
| 920 | } as const satisfies Partial<Record<string, SearchOverlayMode>>; |
| 921 | |
| 922 | export function overlayModeForCommand(command: string | null): SearchOverlayMode | null { |
| 923 | if (command === null) return null; |
| 924 | return command in OVERLAY_MODE_BY_COMMAND |
| 925 | ? OVERLAY_MODE_BY_COMMAND[command as keyof typeof OVERLAY_MODE_BY_COMMAND] |
| 926 | : null; |
| 927 | } |
| 928 | |
| 929 | export function resolveCommandPaletteProject<TProject>( |
| 930 | projects: ReadonlyMap<string, TProject>, |
| 931 | environmentId: EnvironmentId | null, |
| 932 | projectId: ProjectId | null, |
| 933 | ) { |
| 934 | return environmentId && projectId ? projects.get(`${environmentId}:${projectId}`) : undefined; |
| 935 | } |
| 936 | |
| 937 | /** |
| 938 | * Where "No project" goes among the new-thread picker's real projects: at the |
| 939 | * scratch project's own place when it is pinned or current, else after the |
| 940 | * pinned projects and the first unpinned one. |
| 941 | */ |
| 942 | export function newThreadNoProjectIndex( |
| 943 | entries: ReadonlyArray<{ |
| 944 | readonly isScratch: boolean; |
| 945 | readonly pinned: boolean; |
| 946 | readonly isPreferred: boolean; |
| 947 | }>, |
| 948 | ): number { |
| 949 | const projects = entries.filter((entry) => !entry.isScratch); |
| 950 | const scratchAt = entries.findIndex((entry) => entry.isScratch); |
| 951 | const scratch = entries[scratchAt]; |
| 952 | if (scratch && (scratch.pinned || scratch.isPreferred)) { |
| 953 | return entries.slice(0, scratchAt).filter((entry) => !entry.isScratch).length; |
| 954 | } |
| 955 | const pinnedCount = projects.filter((entry) => entry.pinned).length; |
| 956 | return Math.min(pinnedCount + 1, projects.length); |
| 957 | } |