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

CommandPalette.tsx

650 lines24.5 KB

1import { uuidv4 } from "../../lib/uuid";
2import { useNavigation } from "@react-navigation/native";
3import {
4 claimThreadOpen,
5 nextShownOrder,
6 threadSearchSubject,
7 type EnvironmentThreadSearchMatch,
8 type ShownOrder,
9} from "@t3tools/client-runtime/state/thread-search";
10import { THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts";
11import {
12 foldSearchQuery,
13 PALETTE_MESSAGE_LIMIT,
14 rankMessageMatches,
15 splitSearchText,
16 pickedQuery,
17 threadRecentUse,
18} from "@t3tools/shared/paletteSearch";
19import { useCallback, useEffect, useMemo, useRef, useState } from "react";
20import {
21 FlatList,
22 KeyboardAvoidingView,
23 Modal,
24 Pressable,
25 Text as NativeText,
26 TextInput,
27 useWindowDimensions,
28 View,
29 type TextInputInstance,
30} from "react-native";
31​
32import { GestureHandlerRootView } from "react-native-gesture-handler";
33​
34import { ProjectFavicon } from "../../components/ProjectFavicon";
35import { GlassSurface } from "../../components/ui/GlassSurface";
36import { RowPressable } from "../../components/ui/RowPressable";
37import { AppText as Text } from "../../components/ui/AppText";
38import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
39import { cn } from "../../lib/cn";
40import { deriveBottomControlInsets } from "../../lib/reserved-regions";
41import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
42import { useNativeLayoutMetrics } from "../../native/native-layout-metrics";
43import { T3KeyboardCommands } from "../../native/T3KeyboardCommands";
44import { useProjects, useThreadShell, useThreadShells } from "../../state/entities";
45import { useThreadSearch } from "../../state/queries";
46import { requestThreadMessageJump } from "../threads/threadMessageJump";
47import { threadEnvironment } from "../../state/threads";
48import { useAtomCommand } from "../../state/use-atom-command";
49import { useWorkspaceEnvironments } from "../../state/workspace";
50import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
51import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
52import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
53import { ThreadSearchMatchExcerpt } from "../threads/thread-search-match";
54import {
55 filterCommandPaletteItems,
56 nextPaletteIndex,
57 type CommandPaletteItem,
58 type CommandPaletteResult,
59} from "./commandPaletteItems";
60import { parseActiveThreadPath, type HardwareKeyboardCommand } from "./hardwareKeyboardCommands";
61import { threadJumpIndex } from "./threadKeyboardShortcuts";
62import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs";
63import { openSettings } from "../settings/settings-navigation";
64import { useSelectWorkspaceTab } from "../workspace/useSelectWorkspaceTab";
65​
66const PALETTE_COMMANDS: ReadonlyArray<HardwareKeyboardCommand> = [
67 "commandPalette",
68 "paletteDismiss",
69 "paletteNext",
70 "palettePrevious",
71 ...THREAD_JUMP_KEYBINDING_COMMANDS,
72];
73const ROW_HEIGHT = 50;
74// The "In messages" label above the first message match; server results always come last.
75const SECTION_LABEL_HEIGHT = 26;
76​
77const ACTION_ICONS: Record<string, AppSymbolName> = {
78 newTask: "square.and.pencil",
79 newThread: "square.and.pencil",
80 addProject: "folder.badge.plus",
81 settings: "gearshape",
82 appearance: "paintbrush",
83 environments: "desktopcomputer",
84 usage: "chart.bar.xaxis",
85 archive: "archivebox",
86 files: "doc.text",
87 terminal: "terminal",
88 review: PullRequestGlyph.pullRequest,
89 copyThreadReference: "link",
90};
91​
92function itemIcon(item: CommandPaletteItem): AppSymbolName {
93 if (item.kind === "thread") return "text.bubble";
94 return ACTION_ICONS[item.key] ?? "ellipsis";
96​
97function PaletteRow(props: {
98 readonly item: CommandPaletteResult;
99 readonly index: number;
100 readonly selected: boolean;
101 readonly searchMatch?: EnvironmentThreadSearchMatch;
102 readonly searchQuery: string;
103 readonly onSelect: () => void;
104}) {
105 const foregroundClassName = props.selected
106 ? "text-thread-selected-foreground"
107 : "text-foreground";
108 const mutedForegroundClassName = props.selected
109 ? "text-thread-selected-foreground-muted"
110 : "text-foreground-muted";
111 return (
112 <RowPressable
113 accessibilityRole="button"
114 interactionOpacity={props.selected ? 0 : 1}
115 accessibilityState={{ selected: props.selected }}
116 onPress={props.onSelect}
117 className={
118 props.selected
119 ? "mx-2 flex-row items-center gap-3 rounded-xl bg-thread-selected px-3"
120 : "mx-2 flex-row items-center gap-3 rounded-xl px-3"
121 }
122 style={{ height: ROW_HEIGHT }}
123 >
124 <View className="w-7 items-center">
125 {props.item.project ? (
126 <ProjectFavicon
127 environmentId={props.item.project.environmentId}
128 faviconPath={props.item.project.faviconPath}
129 projectIcon={props.item.project.projectIcon}
130 projectTitle={props.item.project.title}
131 size={20}
132 workspaceRoot={props.item.project.workspaceRoot}
133 />
134 ) : (
135 <SymbolView
136 name={itemIcon(props.item)}
137 size={20}
138 tintColorClassName={
139 props.selected ? "accent-thread-selected-foreground" : "accent-icon"
140 }
141 />
142 )}
143 </View>
144 <View className="flex-1">
145 <View className="flex-row items-baseline gap-2">
146 <Text numberOfLines={1} className={cn("shrink text-base", foregroundClassName)}>
147 {props.item.titleRanges?.length
148 ? splitSearchText(props.item.title, props.item.titleRanges).map((part) => (
149 <Text
150 key={part.start}
151 className={cn("text-base", part.highlighted && "font-t3-bold")}
152 >
153 {part.text}
154 </Text>
155 ))
156 : props.item.title}
157 </Text>
158 {/* The second line shows the snippet or hint, so keep where the thread
159 lives, unless the hint already names it. */}
160 {(props.searchMatch ||
161 (props.item.matchHint &&
162 props.item.matchHint.label !== "Project" &&
163 props.item.matchHint.label !== "Environment")) &&
164 props.item.detail ? (
165 <Text
166 numberOfLines={1}
167 className={cn("max-w-[45%] shrink-0 text-sm", mutedForegroundClassName)}
168 >
169 {props.item.detail}
170 </Text>
171 ) : null}
172 </View>
173 {props.searchMatch ? (
174 <ThreadSearchMatchExcerpt
175 match={props.searchMatch}
176 query={props.searchQuery}
177 selected={props.selected}
178 compact
179 />
180 ) : props.item.matchHint ? (
181 <Text numberOfLines={1} className={cn("text-sm", mutedForegroundClassName)}>
182 {props.item.matchHint.label}:{" "}
183 {splitSearchText(props.item.matchHint.text, props.item.matchHint.ranges).map((part) => (
184 <Text key={part.start} className={cn("text-sm", part.highlighted && "font-t3-bold")}>
185 {part.text}
186 </Text>
187 ))}
188 </Text>
189 ) : props.item.detail ? (
190 <Text numberOfLines={1} className={cn("text-sm", mutedForegroundClassName)}>
191 {props.item.detail}
192 </Text>
193 ) : null}
194 </View>
195 {props.index < 9 ? (
196 <NativeText
197 className={cn("w-8 shrink-0 text-right text-sm tabular-nums", mutedForegroundClassName)}
198 >
199 ⌘{props.index + 1}
200 </NativeText>
201 ) : null}
202 </RowPressable>
203 );
205​
206/** Mounted only while open, so the app root does not subscribe to the full thread catalog. */
207export function CommandPalette(props: {
208 readonly pathname: string;
209 readonly onClose: () => void;
210 readonly onCommand: (command: HardwareKeyboardCommand) => void;
211}) {
212 const navigation = useNavigation();
213 const selectTab = useSelectWorkspaceTab();
214 const { themeVariables } = useAppearancePreferences();
215 const { selectThread, selectThreadRoute } = useAdaptiveWorkspaceLayout();
216 const runCommand = props.onCommand;
217 const projects = useProjects();
218 const threads = useThreadShells();
219 const activeThreadRef = useMemo(() => parseActiveThreadPath(props.pathname), [props.pathname]);
220 const activeThread = useThreadShell(activeThreadRef);
221 const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
222 const environments = useWorkspaceEnvironments();
223 const { savedConnectionsById } = useSavedRemoteConnections();
224 const [query, setQuery] = useState("");
225 // Ranking is relative to when the palette opened, so rows do not reorder as time passes.
226 const [now] = useState(() => Date.now());
227 const [selection, setSelection] = useState<string | null>(null);
228 const [visible, setVisible] = useState(true);
229 const pendingAction = useRef<(() => void) | null>(null);
230 const closing = useRef(false);
231 const inputRef = useRef<TextInputInstance>(null);
232 const listRef = useRef<FlatList<CommandPaletteResult>>(null);
233 const { width, height } = useWindowDimensions();
234 // The palette floats above every column, so it keeps itself inside the window's side insets
235 // and to one side of a book fold.
236 const bounds = deriveBottomControlInsets(useNativeLayoutMetrics());
237 const searchEnvironmentIds = useMemo(
238 () =>
239 environments
240 .filter((environment) => environment.connectionState === "connected")
241 .map((environment) => environment.environmentId),
242 [environments],
243 );
244 const search = useThreadSearch(searchEnvironmentIds, query.startsWith(">") ? "" : query);
245 const contentMatchByKey = useMemo(
246 () =>
247 new Map(
248 search.matches
249 .filter((match) => match.source === "user" || match.source === "assistant")
250 .map((match) => [scopedThreadKey(match.environmentId, match.threadId), match]),
251 ),
252 [search.matches],
253 );
254 const items = useMemo(() => {
255 const actions: CommandPaletteItem[] = [
256 {
257 key: "newTask",
258 kind: "action",
259 title: "New thread in…",
260 searchTerms: ["new task", "chat", "create", "project"],
261 run: () => runCommand("newTask"),
262 },
263 {
264 key: "addProject",
265 kind: "action",
266 title: "Add project",
267 searchTerms: ["folder", "clone", "repository", "git"],
268 run: () => navigation.navigate("AddProject"),
269 },
270 {
271 key: "settings",
272 kind: "action",
273 title: "Open settings",
274 searchTerms: ["preferences", "configuration"],
275 run: () => selectTab("settings"),
276 },
277 {
278 key: "appearance",
279 kind: "action",
280 title: "Appearance",
281 searchTerms: ["theme", "colors", "dark", "light"],
282 run: () => openSettings(navigation, "SettingsAppearance"),
283 },
284 {
285 key: "environments",
286 kind: "action",
287 title: "Manage environments",
288 searchTerms: ["connections", "server", "remote"],
289 run: () => openSettings(navigation, "SettingsEnvironments"),
290 },
291 {
292 key: "scheduledTasks",
293 kind: "action",
294 title: "Scheduled tasks",
295 searchTerms: ["schedule", "automations", "recurring"],
296 run: () => openSettings(navigation, "SettingsScheduledTasks"),
297 },
298 {
299 key: "usage",
300 kind: "action",
301 title: "Usage",
302 searchTerms: ["limits", "accounts", "quota"],
303 run: () => openSettings(navigation, "SettingsUsage"),
304 },
305 {
306 key: "archive",
307 kind: "action",
308 title: "Archived threads",
309 searchTerms: ["restore", "history"],
310 run: () => openSettings(navigation, "SettingsArchive"),
311 },
312 ];
313 const projectByKey = new Map(
314 projects.map((project) => [scopedProjectKey(project.environmentId, project.id), project]),
315 );
316 const activeProject = activeThread
317 ? projectByKey.get(scopedProjectKey(activeThread.environmentId, activeThread.projectId))
318 : null;
319 if (activeProject) {
320 actions.unshift({
321 key: "newThread",
322 kind: "action",
323 title: `New thread in ${activeProject.title}`,
324 searchTerms: ["new task", "chat", "create"],
325 run: () =>
326 selectThreadRoute({
327 draft: {
328 requestId: uuidv4(),
329 environmentId: activeProject.environmentId,
330 projectId: activeProject.id,
331 title: activeProject.title,
332 },
333 }),
334 });
335 }
336 if (activeThreadRef) {
337 const threadActions = [
338 ["files", "Go to file", ["open", "files", "browse", "search"]],
339 ["terminal", "Open terminal", ["shell", "console"]],
340 ["review", "Review changes", ["diff", "git", "pull request"]],
341 ["copyThreadReference", "Copy PR link or thread ID", ["reference", "clipboard"]],
342 ] as const;
343 actions.push(
344 ...threadActions.map(([command, title, searchTerms]) => ({
345 key: command,
346 kind: "action" as const,
347 title,
348 searchTerms,
349 run: () => runCommand(command),
350 })),
351 );
352 }
353 const projectItems: CommandPaletteItem[] = projects.map((project) => ({
354 key: `project:${scopedProjectKey(project.environmentId, project.id)}`,
355 kind: "project",
356 project,
357 title: project.title,
358 detail: `New thread · ${savedConnectionsById[project.environmentId]?.environmentLabel ?? project.environmentId}`,
359 searchTerms: [project.workspaceRoot, "new thread", "project"],
360 run: () =>
361 selectThreadRoute({
362 draft: {
363 requestId: uuidv4(),
364 environmentId: project.environmentId,
365 projectId: project.id,
366 title: project.title,
367 },
368 }),
369 }));
370 const threadItems: CommandPaletteItem[] = threads
371 .filter(
372 (thread) =>
373 thread.archivedAt === null && thread.lineage.relationshipToParent !== "subagent",
374 )
375 .map((thread) => {
376 const project = projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId));
377 const environment =
378 savedConnectionsById[thread.environmentId]?.environmentLabel ?? thread.environmentId;
379 return {
380 key: scopedThreadKey(thread.environmentId, thread.id),
381 kind: "thread",
382 title: thread.title || "Untitled thread",
383 detail: [project?.title, environment].filter(Boolean).join(" · "),
384 searchTerms: [],
385 threadSearch: threadSearchSubject(
386 thread,
387 project?.title,
388 environments.length > 1 ? environment : null,
389 ),
390 // Last among threads: picking the thread already open does nothing.
391 ...(thread.environmentId === activeThread?.environmentId && thread.id === activeThread.id
392 ? { secondary: true }
393 : {}),
394 run: () => selectThread(thread),
395 };
396 });
397 // Recent means used recently: written in or opened, whichever is later.
398 threadItems.sort(
399 (left, right) =>
400 (right.threadSearch ? threadRecentUse(right.threadSearch) : 0) -
401 (left.threadSearch ? threadRecentUse(left.threadSearch) : 0),
402 );
403 return [...actions, ...projectItems, ...threadItems];
404 }, [
405 selectTab,
406 activeThread,
407 activeThreadRef,
408 environments.length,
409 navigation,
410 projects,
411 runCommand,
412 savedConnectionsById,
413 selectThread,
414 selectThreadRoute,
415 threads,
416 ]);
417 const rankedMessageKeys = useMemo(() => {
418 const subjectByKey = new Map(
419 items.flatMap((item) => (item.threadSearch ? [[item.key, item.threadSearch] as const] : [])),
420 );
421 const keyOf = (match: EnvironmentThreadSearchMatch) =>
422 scopedThreadKey(match.environmentId, match.threadId);
423 return rankMessageMatches(
424 search.matches,
425 (match) => subjectByKey.get(keyOf(match)),
426 foldSearchQuery(query),
427 now,
428 { withoutTitleMatches: true },
429 ).map(keyOf);
430 }, [items, now, query, search.matches]);
431 // Rows already shown keep their places when a slower environment answers.
432 const [shownOrder, setShownOrder] = useState<ShownOrder | null>(null);
433 const messageOrder = nextShownOrder(
434 shownOrder,
435 search.query,
436 rankedMessageKeys,
437 PALETTE_MESSAGE_LIMIT,
438 );
439 if (messageOrder !== shownOrder) setShownOrder(messageOrder);
440 const messageMatchKeys = useMemo(
441 () => messageOrder.keys.slice(0, messageOrder.shown),
442 [messageOrder.keys, messageOrder.shown],
443 );
444 const results = useMemo(() => {
445 const ranked = filterCommandPaletteItems(items, query, messageMatchKeys, now);
446 // Recent threads leave out the open one, which would always lead them.
447 const activeKey = activeThread
448 ? scopedThreadKey(activeThread.environmentId, activeThread.id)
449 : null;
450 return query.trim() ? ranked : ranked.filter((item) => item.key !== activeKey);
451 }, [activeThread, items, messageMatchKeys, now, query]);
452 const runResult = (item: CommandPaletteResult) => {
453 const thread =
454 item.kind === "thread" && query.trim() && !query.startsWith(">")
455 ? threads.find(
456 (candidate) => scopedThreadKey(candidate.environmentId, candidate.id) === item.key,
457 )
458 : undefined;
459 // A message result opens the thread at that message.
460 const messageId = item.fromMessages ? contentMatchByKey.get(item.key)?.messageId : undefined;
461 if (messageId) requestThreadMessageJump(item.key, messageId);
462 // A pick sends its open with the query, always, so the server records it;
463 // the thread screen then skips its own open. The open thread is no pick.
464 if (thread && !item.secondary) claimThreadOpen(thread.environmentId, thread.id, Date.now());
465 if (thread && thread.lastVisitedAt !== undefined && !item.secondary) {
466 void visitThread({
467 environmentId: thread.environmentId,
468 input: {
469 threadId: thread.id,
470 visitedAt: thread.updatedAt,
471 opened: true,
472 searchQuery: pickedQuery(query),
473 },
474 });
475 }
476 item.run();
477 };
478 const firstMessageIndex = results.findIndex((item) => item.fromMessages);
479 const selectedIndex = Math.max(
480 0,
481 results.findIndex((item) => item.key === selection),
482 );
483 const selectedKey = results[selectedIndex]?.key;
484 useEffect(() => {
485 if (selectedIndex === 0) {
486 // Centering before the list measures its height scrolls half the first row out of view.
487 listRef.current?.scrollToOffset({ offset: 0, animated: false });
488 } else if (selectedKey !== undefined) {
489 listRef.current?.scrollToIndex({ index: selectedIndex, animated: false, viewPosition: 0.5 });
490 }
491 }, [selectedIndex, selectedKey]);
492​
493 const dismissed = useRef(false);
494 const handleDismissed = useCallback(() => {
495 if (dismissed.current) return;
496 dismissed.current = true;
497 // Present navigation sheets only after UIKit has dismissed this modal.
498 props.onClose();
499 pendingAction.current?.();
500 }, [props]);
501​
502 // iOS may drop onDismiss during presentation or competing sheets; a fallback clears stale palette state.
503 useEffect(() => {
504 if (visible) return;
505 const fallback = setTimeout(handleDismissed, 400);
506 return () => clearTimeout(fallback);
507 }, [visible, handleDismissed]);
508​
509 function close(run?: () => void) {
510 if (closing.current) return;
511 closing.current = true;
512 pendingAction.current = run ?? null;
513 setVisible(false);
514 }
515​
516 function onCommand(command: HardwareKeyboardCommand) {
517 if (command === "commandPalette" || command === "paletteDismiss") {
518 close();
519 } else if (command === "paletteNext" || command === "palettePrevious") {
520 setSelection(
521 results[nextPaletteIndex(selectedIndex, command === "paletteNext" ? 1 : -1, results.length)]
522 ?.key ?? null,
523 );
524 } else {
525 const item = results[threadJumpIndex(command)];
526 if (item) close(() => runResult(item));
527 }
528 }
529​
530 return (
531 <Modal
532 visible={visible}
533 transparent
534 animationType="fade"
535 onShow={() => inputRef.current?.focus()}
536 onRequestClose={() => close()}
537 onDismiss={handleDismissed}
538 >
539 <GestureHandlerRootView className="flex-1">
540 <T3KeyboardCommands enabledCommands={PALETTE_COMMANDS} onCommand={onCommand}>
541 <KeyboardAvoidingView
542 behavior="padding"
543 className="flex-1 items-center justify-center py-4"
544 style={{ paddingLeft: 16 + bounds.left, paddingRight: 16 + bounds.right }}
545 >
546 <Pressable
547 className="absolute inset-0 bg-backdrop"
548 accessibilityLabel="Close command palette"
549 onPress={() => close()}
550 />
551 <GlassSurface
552 accessibilityViewIsModal
553 className="bg-sheet"
554 tintColorClassName="accent-sheet/20"
555 fallbackColor={themeVariables["--color-sheet"]}
556 style={{
557 width: Math.min(600, width - 32 - bounds.left - bounds.right),
558 height: Math.min(520, height - 80),
559 borderRadius: 20,
560 }}
561 >
562 <View className="px-3 pb-2.5 pt-3.5">
563 <View className="h-[38px] flex-row items-center gap-1.5 pr-2.5 pl-[11px]">
564 <SymbolView
565 name="magnifyingglass"
566 size={15}
567 tintColorClassName="accent-foreground-muted"
568 type="monochrome"
569 />
570 <TextInput
571 ref={inputRef}
572 accessibilityLabel="Search commands, projects, and threads"
573 placeholder="Search commands, projects, and threads…"
574 placeholderTextColorClassName="accent-placeholder"
575 autoCorrect={false}
576 autoCapitalize="none"
577 clearButtonMode="while-editing"
578 className="h-[34px] flex-1 px-0 py-0 font-sans text-base text-foreground"
579 value={query}
580 onChangeText={(value) => {
581 setQuery(value);
582 setSelection(null);
583 listRef.current?.scrollToOffset({ offset: 0, animated: false });
584 }}
585 returnKeyType="go"
586 submitBehavior="submit"
587 onSubmitEditing={() => {
588 const item = results[selectedIndex];
589 if (item) close(() => runResult(item));
590 }}
591 />
592 </View>
593 </View>
594 <FlatList
595 ref={listRef}
596 data={results}
597 extraData={selectedKey}
598 keyboardShouldPersistTaps="handled"
599 keyExtractor={(item) => item.key}
600 getItemLayout={(_, index) => ({
601 length: ROW_HEIGHT + (index === firstMessageIndex ? SECTION_LABEL_HEIGHT : 0),
602 offset:
603 ROW_HEIGHT * index +
604 (firstMessageIndex !== -1 && index > firstMessageIndex
605 ? SECTION_LABEL_HEIGHT
606 : 0),
607 index,
608 })}
609 contentContainerClassName="pb-2"
610 ListEmptyComponent={
611 <Text className="p-5 text-center text-foreground-muted">
612 {search.isPending ? "Searching…" : "No results"}
613 </Text>
614 }
615 // Message results from slower environments may still arrive below.
616 ListFooterComponent={
617 results.length > 0 && search.isPending && !query.startsWith(">") ? (
618 <Text className="px-5 pt-2 text-xs text-foreground-muted">
619 Searching messages…
620 </Text>
621 ) : undefined
622 }
623 renderItem={({ item, index }) => (
624 <>
625 {index === firstMessageIndex ? (
626 <Text
627 className="px-5 pt-2 text-xs text-foreground-muted"
628 style={{ height: SECTION_LABEL_HEIGHT }}
629 >
630 In messages
631 </Text>
632 ) : null}
633 <PaletteRow
634 item={item}
635 index={index}
636 selected={item.key === selectedKey}
637 searchMatch={item.fromMessages ? contentMatchByKey.get(item.key) : undefined}
638 searchQuery={search.query}
639 onSelect={() => close(() => runResult(item))}
640 />
641 </>
642 )}
643 />
644 </GlassSurface>
645 </KeyboardAvoidingView>
646 </T3KeyboardCommands>
647 </GestureHandlerRootView>
648 </Modal>
649 );