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