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 { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; |
| 2 | import { findForMessageMatch, openThreadFindOnQuery } from "./chat/threadFindStore"; |
| 3 | import { |
| 4 | claimThreadOpen, |
| 5 | nextShownOrder, |
| 6 | type EnvironmentThreadSearchMatch, |
| 7 | type ShownOrder, |
| 8 | } from "@t3tools/client-runtime/state/thread-search"; |
| 9 | import { |
| 10 | foldSearchQuery, |
| 11 | PALETTE_MESSAGE_LIMIT, |
| 12 | pickedQuery, |
| 13 | rankMessageMatches, |
| 14 | } from "@t3tools/shared/paletteSearch"; |
| 15 | import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; |
| 16 | import { useAtomValue } from "@effect/atom-react"; |
| 17 | import { useNavigate } from "@tanstack/react-router"; |
| 18 | import { MessageSquareIcon } from "lucide-react"; |
| 19 | import { useState } from "react"; |
| 20 | import { useGT, useMessages } from "gt-react"; |
| 21 | |
| 22 | import { |
| 23 | applyProviderInstanceSettings, |
| 24 | deriveProviderInstanceEntries, |
| 25 | type ProviderInstanceEntry, |
| 26 | } from "../providerInstances"; |
| 27 | import { useDelegatedUnderParent, useVisibleThreadShells } from "../state/entities"; |
| 28 | import { |
| 29 | useEnvironmentProviders, |
| 30 | useEnvironments, |
| 31 | usePrimaryEnvironmentId, |
| 32 | } from "../state/environments"; |
| 33 | import { useThreadSearch } from "../state/queries"; |
| 34 | import { primaryServerProvidersAtom } from "../state/server"; |
| 35 | import { threadEnvironment } from "../state/threads"; |
| 36 | import { useAtomCommand } from "../state/use-atom-command"; |
| 37 | import { buildThreadRouteParams } from "../threadRoutes"; |
| 38 | import { formatRelativeTimeLabel } from "../timestampFormat"; |
| 39 | import { buildThreadActionItems, ITEM_ICON_CLASS } from "./CommandPalette.logic"; |
| 40 | import { useEnvironmentLookups, useProjectLookups } from "./CommandPaletteLookups"; |
| 41 | import { ThreadCommandSubtitle } from "./ThreadCommandSubtitle"; |
| 42 | import { |
| 43 | ThreadRowLeadingStatus, |
| 44 | ThreadRowTrailingStatus, |
| 45 | ThreadSearchPullRequestNumber, |
| 46 | } from "./ThreadStatusIndicators"; |
| 47 | |
| 48 | function useProviderEntryByEnvironmentAndInstanceId() { |
| 49 | const { environments } = useEnvironments(); |
| 50 | const primaryEnvironmentId = usePrimaryEnvironmentId(); |
| 51 | const providers = useAtomValue(primaryServerProvidersAtom); |
| 52 | const providersByEnvironment = useEnvironmentProviders(); |
| 53 | return new Map<string, ProviderInstanceEntry>( |
| 54 | environments.flatMap((environment) => { |
| 55 | const serverConfig = environment.serverConfig; |
| 56 | const derived = deriveProviderInstanceEntries( |
| 57 | providersByEnvironment.get(environment.environmentId) ?? |
| 58 | (environment.environmentId === primaryEnvironmentId ? providers : []), |
| 59 | ); |
| 60 | const entries = serverConfig |
| 61 | ? applyProviderInstanceSettings(derived, serverConfig.settings, null) |
| 62 | : derived; |
| 63 | return entries.map( |
| 64 | (entry) => [`${environment.environmentId}:${entry.instanceId}`, entry] as const, |
| 65 | ); |
| 66 | }), |
| 67 | ); |
| 68 | } |
| 69 | |
| 70 | function useConnectedThreadSearch(query: string) { |
| 71 | const { environments } = useEnvironments(); |
| 72 | const { projectEnvironmentLocationById } = useEnvironmentLookups(); |
| 73 | const environmentIds: ReadonlyArray<EnvironmentId> = environments |
| 74 | .filter((environment) => environment.connection.phase === "connected") |
| 75 | .map((environment) => environment.environmentId); |
| 76 | // The palette matches environment names when there are several; older rows must match the same. |
| 77 | const environmentLabels = |
| 78 | environments.length > 1 |
| 79 | ? Object.fromEntries( |
| 80 | environmentIds.flatMap((environmentId) => { |
| 81 | const label = projectEnvironmentLocationById.get(environmentId)?.label; |
| 82 | return label === undefined || label === null ? [] : [[environmentId, label]]; |
| 83 | }), |
| 84 | ) |
| 85 | : undefined; |
| 86 | return useThreadSearch( |
| 87 | environmentIds, |
| 88 | query, |
| 89 | environmentLabels === undefined ? {} : { environmentLabels }, |
| 90 | ); |
| 91 | } |
| 92 | |
| 93 | /** |
| 94 | * Every visible thread as a palette item, plus, for a non-empty |
| 95 | * `threadSearchQuery`, the threads whose messages match, best first. |
| 96 | */ |
| 97 | export function useCommandPaletteThreadItems(input: { |
| 98 | readonly activeThread: { readonly environmentId: EnvironmentId; readonly id: ThreadId } | null; |
| 99 | readonly threadSearchQuery: string; |
| 100 | }) { |
| 101 | const { activeThread, threadSearchQuery } = input; |
| 102 | const messages = useMessages(); |
| 103 | const gt = useGT(); |
| 104 | const navigate = useNavigate(); |
| 105 | const threads = useVisibleThreadShells(); |
| 106 | const delegatedUnderParent = useDelegatedUnderParent(); |
| 107 | const { projectEnvironmentLocationById } = useEnvironmentLookups(); |
| 108 | const providerEntryByEnvironmentAndInstanceId = useProviderEntryByEnvironmentAndInstanceId(); |
| 109 | const messageSearch = useConnectedThreadSearch(threadSearchQuery); |
| 110 | const { projectByKey } = useProjectLookups(); |
| 111 | const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false }); |
| 112 | // Ranking is relative to when the palette opened, so rows do not reorder as time passes. |
| 113 | const [now] = useState(() => Date.now()); |
| 114 | |
| 115 | const { environments } = useEnvironments(); |
| 116 | const threadItems = buildThreadActionItems( |
| 117 | { |
| 118 | threads, |
| 119 | delegatedUnderParent, |
| 120 | ...(environments.length > 1 |
| 121 | ? { |
| 122 | environmentLabelOf: (thread: (typeof threads)[number]) => |
| 123 | projectEnvironmentLocationById.get(thread.environmentId)?.label ?? null, |
| 124 | } |
| 125 | : {}), |
| 126 | ...(activeThread ? { activeThread } : {}), |
| 127 | projectByKey, |
| 128 | icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />, |
| 129 | renderLeadingContent: (thread) => <ThreadRowLeadingStatus thread={thread} />, |
| 130 | renderTrailingContent: (thread) => ( |
| 131 | <> |
| 132 | <ThreadSearchPullRequestNumber |
| 133 | thread={thread} |
| 134 | query={threadSearchQuery} |
| 135 | settled={thread.settledOverride === "settled"} |
| 136 | /> |
| 137 | <ThreadRowTrailingStatus thread={thread} /> |
| 138 | </> |
| 139 | ), |
| 140 | renderDescription: (thread, { projectTitle }) => { |
| 141 | const modelInstanceId = |
| 142 | thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId; |
| 143 | const providerEntry = |
| 144 | providerEntryByEnvironmentAndInstanceId.get( |
| 145 | `${thread.environmentId}:${modelInstanceId}`, |
| 146 | ) ?? null; |
| 147 | return ( |
| 148 | <ThreadCommandSubtitle |
| 149 | project={projectByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null} |
| 150 | projectTitle={projectTitle ?? null} |
| 151 | environmentLabel={ |
| 152 | projectEnvironmentLocationById.get(thread.environmentId)?.label ?? |
| 153 | gt("Remote", { $context: "machine location" }) |
| 154 | } |
| 155 | branch={thread.branch} |
| 156 | worktreePath={thread.worktreePath} |
| 157 | isCurrent={ |
| 158 | thread.id === activeThread?.id && thread.environmentId === activeThread.environmentId |
| 159 | } |
| 160 | driverKind={providerEntry?.driverKind ?? null} |
| 161 | providerDisplayName={ |
| 162 | thread.runtime?.providerName ?? providerEntry?.displayName ?? modelInstanceId |
| 163 | } |
| 164 | acpRegistryAgentId={providerEntry?.acpRegistryAgentId} |
| 165 | acpRegistryIconUrl={providerEntry?.acpRegistryIconUrl} |
| 166 | /> |
| 167 | ); |
| 168 | }, |
| 169 | runThread: async (thread) => { |
| 170 | // A pick sends its open with the query, always, so the server records |
| 171 | // it; the thread view then skips its own open. The open thread is no pick. |
| 172 | const isOpen = |
| 173 | activeThread?.environmentId === thread.environmentId && activeThread.id === thread.id; |
| 174 | if (threadSearchQuery.trim().length > 0 && !threadSearchQuery.startsWith(">") && !isOpen) { |
| 175 | // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309) |
| 176 | claimThreadOpen(thread.environmentId, thread.id, Date.now()); |
| 177 | } |
| 178 | if ( |
| 179 | threadSearchQuery.trim().length > 0 && |
| 180 | !threadSearchQuery.startsWith(">") && |
| 181 | thread.lastVisitedAt !== undefined && |
| 182 | !isOpen |
| 183 | ) { |
| 184 | void visitThread({ |
| 185 | environmentId: thread.environmentId, |
| 186 | input: { |
| 187 | threadId: thread.id, |
| 188 | visitedAt: thread.updatedAt, |
| 189 | opened: true, |
| 190 | searchQuery: pickedQuery(threadSearchQuery), |
| 191 | }, |
| 192 | }); |
| 193 | } |
| 194 | await navigate({ |
| 195 | to: "/$environmentId/$threadId", |
| 196 | params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.id)), |
| 197 | }); |
| 198 | }, |
| 199 | }, |
| 200 | messages, |
| 201 | ); |
| 202 | |
| 203 | const itemByValue = new Map(threadItems.map((item) => [item.value, item])); |
| 204 | const itemForMatch = (match: EnvironmentThreadSearchMatch) => |
| 205 | itemByValue.get(`thread:${match.environmentId}:${match.threadId}`); |
| 206 | const rankedMessageItems = rankMessageMatches( |
| 207 | messageSearch.matches, |
| 208 | (match) => itemForMatch(match)?.threadSearch, |
| 209 | foldSearchQuery(threadSearchQuery), |
| 210 | now, |
| 211 | { withoutTitleMatches: true }, |
| 212 | ).flatMap((match) => { |
| 213 | const item = itemForMatch(match); |
| 214 | if (!item) return []; |
| 215 | // The snippet replaces the project line, so a message row is as tall as a title row. |
| 216 | const { description: _description, ...rest } = item; |
| 217 | return [ |
| 218 | { |
| 219 | ...rest, |
| 220 | // When the matching message was written, not when the thread last moved. |
| 221 | ...(match.messageCreatedAt |
| 222 | ? { timestamp: formatRelativeTimeLabel(match.messageCreatedAt, undefined, messages) } |
| 223 | : {}), |
| 224 | threadContentMatch: { |
| 225 | source: match.source, |
| 226 | snippet: match.snippet, |
| 227 | query: messageSearch.query, |
| 228 | }, |
| 229 | // Opens the thread with find on the word at the matched message, so it is in view. |
| 230 | run: async () => { |
| 231 | await item.run(); |
| 232 | openThreadFindOnQuery( |
| 233 | scopedThreadKey(scopeThreadRef(match.environmentId, match.threadId)), |
| 234 | findForMessageMatch(match, messageSearch.query), |
| 235 | ); |
| 236 | }, |
| 237 | }, |
| 238 | ]; |
| 239 | }); |
| 240 | |
| 241 | // Rows already shown keep their places when a slower environment answers. |
| 242 | const [shownOrder, setShownOrder] = useState<ShownOrder | null>(null); |
| 243 | const order = nextShownOrder( |
| 244 | shownOrder, |
| 245 | messageSearch.query, |
| 246 | rankedMessageItems.map((item) => item.value), |
| 247 | PALETTE_MESSAGE_LIMIT, |
| 248 | ); |
| 249 | if (order !== shownOrder) setShownOrder(order); |
| 250 | const messageItemByValue = new Map(rankedMessageItems.map((item) => [item.value, item])); |
| 251 | const threadMessageItems = order.keys |
| 252 | .slice(0, order.shown) |
| 253 | .flatMap((value) => messageItemByValue.get(value) ?? []); |
| 254 | |
| 255 | return { |
| 256 | threadItems, |
| 257 | threadMessageItems, |
| 258 | now, |
| 259 | isSearchPending: messageSearch.isPending, |
| 260 | isSearchFailed: messageSearch.failed, |
| 261 | }; |
| 262 | } |