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

CommandPaletteThreadItems.tsx

235 lines9.0 KB

1import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2import { findForMessageMatch, requestThreadFindQuery } from "./chat/threadFindActionBus";
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 { useThreadShells } 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 );
68​
69function useConnectedThreadSearch(query: string) {
70 const { environments } = useEnvironments();
71 const environmentIds: ReadonlyArray<EnvironmentId> = environments
72 .filter((environment) => environment.connection.phase === "connected")
73 .map((environment) => environment.environmentId);
74 return useThreadSearch(environmentIds, query);
76​
77/**
78 * Every visible thread as a palette item, plus, for a non-empty
79 * `threadSearchQuery`, the threads whose messages match, best first.
80 */
81export function useCommandPaletteThreadItems(input: {
82 readonly activeThread: { readonly environmentId: EnvironmentId; readonly id: ThreadId } | null;
83 readonly threadSearchQuery: string;
84}) {
85 const { activeThread, threadSearchQuery } = input;
86 const navigate = useNavigate();
87 const threads = useThreadShells();
88 const { projectEnvironmentLocationById } = useEnvironmentLookups();
89 const providerEntryByEnvironmentAndInstanceId = useProviderEntryByEnvironmentAndInstanceId();
90 const messageSearch = useConnectedThreadSearch(threadSearchQuery);
91 const { projectByKey } = useProjectLookups();
92 const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
93 // Ranking is relative to when the palette opened, so rows do not reorder as time passes.
94 const [now] = useState(() => Date.now());
95​
96 const { environments } = useEnvironments();
97 const threadItems = buildThreadActionItems({
98 threads,
99 ...(environments.length > 1
100 ? {
101 environmentLabelOf: (thread: (typeof threads)[number]) =>
102 projectEnvironmentLocationById.get(thread.environmentId)?.label ?? null,
103 }
104 : {}),
105 ...(activeThread ? { activeThread } : {}),
106 projectByKey,
107 icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />,
108 renderLeadingContent: (thread) => <ThreadRowLeadingStatus thread={thread} />,
109 renderTrailingContent: (thread) => (
110 <>
111 <ThreadSearchPullRequestNumber
112 thread={thread}
113 query={threadSearchQuery}
114 settled={thread.settledOverride === "settled"}
115 />
116 <ThreadRowTrailingStatus thread={thread} />
117 </>
118 ),
119 renderDescription: (thread, { projectTitle }) => {
120 const modelInstanceId =
121 thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
122 const providerEntry =
123 providerEntryByEnvironmentAndInstanceId.get(`${thread.environmentId}:${modelInstanceId}`) ??
124 null;
125 return (
126 <ThreadCommandSubtitle
127 project={projectByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null}
128 projectTitle={projectTitle ?? null}
129 environmentLabel={
130 projectEnvironmentLocationById.get(thread.environmentId)?.label ?? "Remote"
131 }
132 branch={thread.branch}
133 worktreePath={thread.worktreePath}
134 isCurrent={
135 thread.id === activeThread?.id && thread.environmentId === activeThread.environmentId
136 }
137 driverKind={providerEntry?.driverKind ?? null}
138 providerDisplayName={
139 thread.runtime?.providerName ?? providerEntry?.displayName ?? modelInstanceId
140 }
141 acpRegistryAgentId={providerEntry?.acpRegistryAgentId}
142 acpRegistryIconUrl={providerEntry?.acpRegistryIconUrl}
143 />
144 );
145 },
146 runThread: async (thread) => {
147 // A pick sends its open with the query, always, so the server records
148 // it; the thread view then skips its own open. The open thread is no pick.
149 const isOpen =
150 activeThread?.environmentId === thread.environmentId && activeThread.id === thread.id;
151 if (threadSearchQuery.trim().length > 0 && !threadSearchQuery.startsWith(">") && !isOpen) {
152 claimThreadOpen(thread.environmentId, thread.id, Date.now());
153 }
154 if (
155 threadSearchQuery.trim().length > 0 &&
156 !threadSearchQuery.startsWith(">") &&
157 thread.lastVisitedAt !== undefined &&
158 !isOpen
159 ) {
160 void visitThread({
161 environmentId: thread.environmentId,
162 input: {
163 threadId: thread.id,
164 visitedAt: thread.updatedAt,
165 opened: true,
166 searchQuery: pickedQuery(threadSearchQuery),
167 },
168 });
169 }
170 await navigate({
171 to: "/$environmentId/$threadId",
172 params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.id)),
173 });
174 },
175 });
176​
177 const itemByValue = new Map(threadItems.map((item) => [item.value, item]));
178 const itemForMatch = (match: EnvironmentThreadSearchMatch) =>
179 itemByValue.get(`thread:${match.environmentId}:${match.threadId}`);
180 const rankedMessageItems = rankMessageMatches(
181 messageSearch.matches,
182 (match) => itemForMatch(match)?.threadSearch,
183 foldSearchQuery(threadSearchQuery),
184 now,
185 { withoutTitleMatches: true },
186 ).flatMap((match) => {
187 const item = itemForMatch(match);
188 if (!item) return [];
189 // The snippet replaces the project line, so a message row is as tall as a title row.
190 const { description: _description, ...rest } = item;
191 return [
192 {
193 ...rest,
194 // When the matching message was written, not when the thread last moved.
195 ...(match.messageCreatedAt
196 ? { timestamp: formatRelativeTimeLabel(match.messageCreatedAt) }
197 : {}),
198 threadContentMatch: {
199 source: match.source,
200 snippet: match.snippet,
201 query: messageSearch.query,
202 },
203 // Opens the thread with find on the word at the matched message, so it is in view.
204 run: async () => {
205 await item.run();
206 requestThreadFindQuery(
207 scopedThreadKey(scopeThreadRef(match.environmentId, match.threadId)),
208 findForMessageMatch(match, messageSearch.query),
209 );
210 },
211 },
212 ];
213 });
214​
215 // Rows already shown keep their places when a slower environment answers.
216 const [shownOrder, setShownOrder] = useState<ShownOrder | null>(null);
217 const order = nextShownOrder(
218 shownOrder,
219 messageSearch.query,
220 rankedMessageItems.map((item) => item.value),
221 PALETTE_MESSAGE_LIMIT,
222 );
223 if (order !== shownOrder) setShownOrder(order);
224 const messageItemByValue = new Map(rankedMessageItems.map((item) => [item.value, item]));
225 const threadMessageItems = order.keys
226 .slice(0, order.shown)
227 .flatMap((value) => messageItemByValue.get(value) ?? []);
228​
229 return {
230 threadItems,
231 threadMessageItems,
232 now,
233 isSearchPending: messageSearch.isPending,
234 };