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