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

CommandPaletteThreadItems.tsx

261 lines10.1 KB

1import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2import { findForMessageMatch, openThreadFindOnQuery } from "./chat/threadFindStore";
3import {
4 claimThreadOpen,
5 nextShownOrder,
6 type EnvironmentThreadSearchMatch,
7 type ShownOrder,
8} from "@t3tools/client-runtime/state/thread-search";
9import {
10 foldSearchQuery,
11 PALETTE_MESSAGE_LIMIT,
12 pickedQuery,
13 rankMessageMatches,
14} from "@t3tools/shared/paletteSearch";
15import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
16import { useAtomValue } from "@effect/atom-react";
17import { useNavigate } from "@tanstack/react-router";
18import { MessageSquareIcon } from "lucide-react";
19import { useState } from "react";
20import { useGT, useMessages } from "gt-react";
21​
22import {
23 applyProviderInstanceSettings,
24 deriveProviderInstanceEntries,
25 type ProviderInstanceEntry,
26} from "../providerInstances";
27import { useDelegatedUnderParent, useVisibleThreadShells } from "../state/entities";
28import {
29 useEnvironmentProviders,
30 useEnvironments,
31 usePrimaryEnvironmentId,
32} from "../state/environments";
33import { useThreadSearch } from "../state/queries";
34import { primaryServerProvidersAtom } from "../state/server";
35import { threadEnvironment } from "../state/threads";
36import { useAtomCommand } from "../state/use-atom-command";
37import { buildThreadRouteParams } from "../threadRoutes";
38import { formatRelativeTimeLabel } from "../timestampFormat";
39import { buildThreadActionItems, ITEM_ICON_CLASS } from "./CommandPalette.logic";
40import { useEnvironmentLookups, useProjectLookups } from "./CommandPaletteLookups";
41import { ThreadCommandSubtitle } from "./ThreadCommandSubtitle";
42import {
43 ThreadRowLeadingStatus,
44 ThreadRowTrailingStatus,
45 ThreadSearchPullRequestNumber,
46} from "./ThreadStatusIndicators";
47​
48function 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 );
69​
70function 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 );
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 */
97export 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 claimThreadOpen(thread.environmentId, thread.id, Date.now());
176 }
177 if (
178 threadSearchQuery.trim().length > 0 &&
179 !threadSearchQuery.startsWith(">") &&
180 thread.lastVisitedAt !== undefined &&
181 !isOpen
182 ) {
183 void visitThread({
184 environmentId: thread.environmentId,
185 input: {
186 threadId: thread.id,
187 visitedAt: thread.updatedAt,
188 opened: true,
189 searchQuery: pickedQuery(threadSearchQuery),
190 },
191 });
192 }
193 await navigate({
194 to: "/$environmentId/$threadId",
195 params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.id)),
196 });
197 },
198 },
199 messages,
200 );
201​
202 const itemByValue = new Map(threadItems.map((item) => [item.value, item]));
203 const itemForMatch = (match: EnvironmentThreadSearchMatch) =>
204 itemByValue.get(`thread:${match.environmentId}:${match.threadId}`);
205 const rankedMessageItems = rankMessageMatches(
206 messageSearch.matches,
207 (match) => itemForMatch(match)?.threadSearch,
208 foldSearchQuery(threadSearchQuery),
209 now,
210 { withoutTitleMatches: true },
211 ).flatMap((match) => {
212 const item = itemForMatch(match);
213 if (!item) return [];
214 // The snippet replaces the project line, so a message row is as tall as a title row.
215 const { description: _description, ...rest } = item;
216 return [
217 {
218 ...rest,
219 // When the matching message was written, not when the thread last moved.
220 ...(match.messageCreatedAt
221 ? { timestamp: formatRelativeTimeLabel(match.messageCreatedAt, undefined, messages) }
222 : {}),
223 threadContentMatch: {
224 source: match.source,
225 snippet: match.snippet,
226 query: messageSearch.query,
227 },
228 // Opens the thread with find on the word at the matched message, so it is in view.
229 run: async () => {
230 await item.run();
231 openThreadFindOnQuery(
232 scopedThreadKey(scopeThreadRef(match.environmentId, match.threadId)),
233 findForMessageMatch(match, messageSearch.query),
234 );
235 },
236 },
237 ];
238 });
239​
240 // Rows already shown keep their places when a slower environment answers.
241 const [shownOrder, setShownOrder] = useState<ShownOrder | null>(null);
242 const order = nextShownOrder(
243 shownOrder,
244 messageSearch.query,
245 rankedMessageItems.map((item) => item.value),
246 PALETTE_MESSAGE_LIMIT,
247 );
248 if (order !== shownOrder) setShownOrder(order);
249 const messageItemByValue = new Map(rankedMessageItems.map((item) => [item.value, item]));
250 const threadMessageItems = order.keys
251 .slice(0, order.shown)
252 .flatMap((value) => messageItemByValue.get(value) ?? []);
253​
254 return {
255 threadItems,
256 threadMessageItems,
257 now,
258 isSearchPending: messageSearch.isPending,
259 isSearchFailed: messageSearch.failed,
260 };