Open History to see the last commit
1import { uuidv4 } from "../../lib/uuid";
2import { useNavigation } from "@react-navigation/native";
3import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
4import { THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts";
5import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
6import { useCallback, useEffect, useMemo, useRef, useState } from "react";
7import {
8 FlatList,
9 KeyboardAvoidingView,
10 Modal,
11 Pressable,
12 Text as NativeText,
13 TextInput,
14 useWindowDimensions,
15 View,
16 type TextInputInstance,
17} from "react-native";
18
19import { GestureHandlerRootView } from "react-native-gesture-handler";
20
21import { ProjectFavicon } from "../../components/ProjectFavicon";
22import { GlassSurface } from "../../components/ui/GlassSurface";
23import { RowPressable } from "../../components/ui/RowPressable";
24import { AppText as Text } from "../../components/ui/AppText";
25import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
26import { cn } from "../../lib/cn";
27import { deriveBottomControlInsets } from "../../lib/reserved-regions";
28import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
29import { useNativeLayoutMetrics } from "../../native/native-layout-metrics";
30import { T3KeyboardCommands } from "../../native/T3KeyboardCommands";
31import { useProjects, useThreadShell, useThreadShells } from "../../state/entities";
32import { useThreadSearch } from "../../state/queries";
33import { useWorkspaceEnvironments } from "../../state/workspace";
34import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
35import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
36import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
37import { ThreadSearchMatchExcerpt } from "../threads/thread-search-match";
38import {
39 filterCommandPaletteItems,
40 nextPaletteIndex,
41 type CommandPaletteItem,
42} from "./commandPaletteItems";
43import { parseActiveThreadPath, type HardwareKeyboardCommand } from "./hardwareKeyboardCommands";
44import { threadJumpIndex } from "./threadKeyboardShortcuts";
45import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs";
46
47const PALETTE_COMMANDS: ReadonlyArray<HardwareKeyboardCommand> = [
48 "commandPalette",
49 "paletteDismiss",
50 "paletteNext",
51 "palettePrevious",
52 ...THREAD_JUMP_KEYBINDING_COMMANDS,
53];
54const ROW_HEIGHT = 50;
55
56const ACTION_ICONS: Record<string, AppSymbolName> = {
57 newTask: "square.and.pencil",
58 newThread: "square.and.pencil",
59 addProject: "folder.badge.plus",
60 settings: "gearshape",
61 appearance: "paintbrush",
62 environments: "desktopcomputer",
63 usage: "chart.bar.xaxis",
64 archive: "archivebox",
65 files: "doc.text",
66 terminal: "terminal",
67 review: PullRequestGlyph.pullRequest,
68 copyThreadReference: "link",
69};
70
71function itemIcon(item: CommandPaletteItem): AppSymbolName {
72 if (item.kind === "thread") return "text.bubble";
73 return ACTION_ICONS[item.key] ?? "ellipsis";
74}
75
76function PaletteRow(props: {
77 readonly item: CommandPaletteItem;
78 readonly index: number;
79 readonly selected: boolean;
80 readonly searchMatch?: EnvironmentThreadSearchMatch;
81 readonly searchQuery: string;
82 readonly onSelect: () => void;
83}) {
84 const foregroundClassName = props.selected
85 ? "text-thread-selected-foreground"
86 : "text-foreground";
87 const mutedForegroundClassName = props.selected
88 ? "text-thread-selected-foreground-muted"
89 : "text-foreground-muted";
90 return (
91 <RowPressable
92 accessibilityRole="button"
93 interactionOpacity={props.selected ? 0 : 1}
94 accessibilityState={{ selected: props.selected }}
95 onPress={props.onSelect}
96 className={
97 props.selected
98 ? "mx-2 flex-row items-center gap-3 rounded-xl bg-thread-selected px-3"
99 : "mx-2 flex-row items-center gap-3 rounded-xl px-3"
100 }
101 style={{ height: ROW_HEIGHT }}
102 >
103 <View className="w-7 items-center">
104 {props.item.project ? (
105 <ProjectFavicon
106 environmentId={props.item.project.environmentId}
107 faviconPath={props.item.project.faviconPath}
108 projectIcon={props.item.project.projectIcon}
109 projectTitle={props.item.project.title}
110 size={20}
111 workspaceRoot={props.item.project.workspaceRoot}
112 />
113 ) : (
114 <SymbolView
115 name={itemIcon(props.item)}
116 size={20}
117 tintColorClassName={
118 props.selected ? "accent-thread-selected-foreground" : "accent-icon"
119 }
120 />
121 )}
122 </View>
123 <View className="flex-1">
124 <Text numberOfLines={1} className={cn("text-base", foregroundClassName)}>
125 {props.item.title}
126 </Text>
127 {props.searchMatch ? (
128 <ThreadSearchMatchExcerpt
129 match={props.searchMatch}
130 query={props.searchQuery}
131 selected={props.selected}
132 compact
133 />
134 ) : props.item.detail ? (
135 <Text numberOfLines={1} className={cn("text-sm", mutedForegroundClassName)}>
136 {props.item.detail}
137 </Text>
138 ) : null}
139 </View>
140 {props.index < 9 ? (
141 <NativeText
142 className={cn("w-8 shrink-0 text-right text-sm tabular-nums", mutedForegroundClassName)}
143 >
144 ⌘{props.index + 1}
145 </NativeText>
146 ) : null}
147 </RowPressable>
148 );
149}
150
151/** Mounted only while open, so the app root does not subscribe to the full thread catalog. */
152export function CommandPalette(props: {
153 readonly pathname: string;
154 readonly onClose: () => void;
155 readonly onCommand: (command: HardwareKeyboardCommand) => void;
156}) {
157 const navigation = useNavigation();
158 const { themeVariables } = useAppearancePreferences();
159 const { selectThread, selectThreadRoute } = useAdaptiveWorkspaceLayout();
160 const runCommand = props.onCommand;
161 const projects = useProjects();
162 const threads = useThreadShells();
163 const activeThreadRef = useMemo(() => parseActiveThreadPath(props.pathname), [props.pathname]);
164 const activeThread = useThreadShell(activeThreadRef);
165 const environments = useWorkspaceEnvironments();
166 const { savedConnectionsById } = useSavedRemoteConnections();
167 const [query, setQuery] = useState("");
168 const [selection, setSelection] = useState<string | null>(null);
169 const [visible, setVisible] = useState(true);
170 const pendingAction = useRef<(() => void) | null>(null);
171 const closing = useRef(false);
172 const inputRef = useRef<TextInputInstance>(null);
173 const listRef = useRef<FlatList<CommandPaletteItem>>(null);
174 const { width, height } = useWindowDimensions();
175 // The palette floats above every column, so it keeps itself inside the window's side insets
176 // and to one side of a book fold.
177 const bounds = deriveBottomControlInsets(useNativeLayoutMetrics());
178 const searchEnvironmentIds = useMemo(
179 () =>
180 environments
181 .filter((environment) => environment.connectionState === "connected")
182 .map((environment) => environment.environmentId),
183 [environments],
184 );
185 const search = useThreadSearch(searchEnvironmentIds, query.startsWith(">") ? "" : query);
186 const matchedThreadKeys = useMemo(
187 () =>
188 new Set(search.matches.map((match) => scopedThreadKey(match.environmentId, match.threadId))),
189 [search.matches],
190 );
191 const contentMatchByKey = useMemo(
192 () =>
193 new Map(
194 search.matches
195 .filter((match) => match.source === "user" || match.source === "assistant")
196 .map((match) => [scopedThreadKey(match.environmentId, match.threadId), match]),
197 ),
198 [search.matches],
199 );
200 const items = useMemo(() => {
201 const actions: CommandPaletteItem[] = [
202 {
203 key: "newTask",
204 kind: "action",
205 title: "New thread in…",
206 searchTerms: ["new task", "chat", "create", "project"],
207 run: () => runCommand("newTask"),
208 },
209 {
210 key: "addProject",
211 kind: "action",
212 title: "Add project",
213 searchTerms: ["folder", "clone", "repository", "git"],
214 run: () => navigation.navigate("AddProject"),
215 },
216 {
217 key: "settings",
218 kind: "action",
219 title: "Open settings",
220 searchTerms: ["preferences", "configuration"],
221 run: () =>
222 navigation.navigate("SettingsSheet", {
223 screen: "SettingsContent",
224 params: { screen: "Settings" },
225 }),
226 },
227 {
228 key: "appearance",
229 kind: "action",
230 title: "Appearance",
231 searchTerms: ["theme", "colors", "dark", "light"],
232 run: () =>
233 navigation.navigate("SettingsSheet", {
234 screen: "SettingsContent",
235 params: { screen: "SettingsAppearance" },
236 }),
237 },
238 {
239 key: "environments",
240 kind: "action",
241 title: "Manage environments",
242 searchTerms: ["connections", "server", "remote"],
243 run: () =>
244 navigation.navigate("SettingsSheet", {
245 screen: "SettingsContent",
246 params: { screen: "SettingsEnvironments" },
247 }),
248 },
249 {
250 key: "scheduledTasks",
251 kind: "action",
252 title: "Scheduled tasks",
253 searchTerms: ["schedule", "automations", "recurring"],
254 run: () =>
255 navigation.navigate("SettingsSheet", {
256 screen: "SettingsContent",
257 params: { screen: "SettingsScheduledTasks" },
258 }),
259 },
260 {
261 key: "usage",
262 kind: "action",
263 title: "Usage",
264 searchTerms: ["limits", "accounts", "quota"],
265 run: () =>
266 navigation.navigate("SettingsSheet", {
267 screen: "SettingsContent",
268 params: { screen: "SettingsUsage" },
269 }),
270 },
271 {
272 key: "archive",
273 kind: "action",
274 title: "Archived threads",
275 searchTerms: ["restore", "history"],
276 run: () =>
277 navigation.navigate("SettingsSheet", {
278 screen: "SettingsContent",
279 params: { screen: "SettingsArchive" },
280 }),
281 },
282 ];
283 const projectByKey = new Map(
284 projects.map((project) => [scopedProjectKey(project.environmentId, project.id), project]),
285 );
286 const activeProject = activeThread
287 ? projectByKey.get(scopedProjectKey(activeThread.environmentId, activeThread.projectId))
288 : null;
289 if (activeProject) {
290 actions.unshift({
291 key: "newThread",
292 kind: "action",
293 title: `New thread in ${activeProject.title}`,
294 searchTerms: ["new task", "chat", "create"],
295 run: () =>
296 selectThreadRoute({
297 draft: {
298 requestId: uuidv4(),
299 environmentId: activeProject.environmentId,
300 projectId: activeProject.id,
301 title: activeProject.title,
302 },
303 }),
304 });
305 }
306 if (activeThreadRef) {
307 const threadActions = [
308 ["files", "Go to file", ["open", "files", "browse", "search"]],
309 ["terminal", "Open terminal", ["shell", "console"]],
310 ["review", "Review changes", ["diff", "git", "pull request"]],
311 ["copyThreadReference", "Copy PR link or thread ID", ["reference", "clipboard"]],
312 ] as const;
313 actions.push(
314 ...threadActions.map(([command, title, searchTerms]) => ({
315 key: command,
316 kind: "action" as const,
317 title,
318 searchTerms,
319 run: () => runCommand(command),
320 })),
321 );
322 }
323 const projectItems: CommandPaletteItem[] = projects.map((project) => ({
324 key: `project:${scopedProjectKey(project.environmentId, project.id)}`,
325 kind: "project",
326 project,
327 title: project.title,
328 detail: `New thread · ${savedConnectionsById[project.environmentId]?.environmentLabel ?? project.environmentId}`,
329 searchTerms: [project.workspaceRoot, "new thread", "project"],
330 run: () =>
331 selectThreadRoute({
332 draft: {
333 requestId: uuidv4(),
334 environmentId: project.environmentId,
335 projectId: project.id,
336 title: project.title,
337 },
338 }),
339 }));
340 const threadItems: CommandPaletteItem[] = threads
341 .filter(
342 (thread) =>
343 thread.archivedAt === null && thread.lineage.relationshipToParent !== "subagent",
344 )
345 .sort((left, right) =>
346 (right.latestUserMessageAt ?? right.updatedAt).localeCompare(
347 left.latestUserMessageAt ?? left.updatedAt,
348 ),
349 )
350 .map((thread) => {
351 const project = projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId));
352 const environment =
353 savedConnectionsById[thread.environmentId]?.environmentLabel ?? thread.environmentId;
354 return {
355 key: scopedThreadKey(thread.environmentId, thread.id),
356 kind: "thread",
357 title: thread.title || "Untitled thread",
358 detail: [project?.title, environment].filter(Boolean).join(" · "),
359 searchTerms: [
360 project?.title ?? "",
361 environment,
362 thread.branch ?? "",
363 ...threadPullRequestSearchTerms(thread),
364 ],
365 run: () => selectThread(thread),
366 };
367 });
368 return [...actions, ...projectItems, ...threadItems];
369 }, [
370 activeThread,
371 activeThreadRef,
372 navigation,
373 projects,
374 runCommand,
375 savedConnectionsById,
376 selectThread,
377 selectThreadRoute,
378 threads,
379 ]);
380 const results = useMemo(
381 () => filterCommandPaletteItems(items, query, matchedThreadKeys),
382 [items, matchedThreadKeys, query],
383 );
384 const selectedIndex = Math.max(
385 0,
386 results.findIndex((item) => item.key === selection),
387 );
388 const selectedKey = results[selectedIndex]?.key;
389 useEffect(() => {
390 if (selectedIndex === 0) {
391 // Centering before the list measures its height scrolls half the first row out of view.
392 listRef.current?.scrollToOffset({ offset: 0, animated: false });
393 } else if (selectedKey !== undefined) {
394 listRef.current?.scrollToIndex({ index: selectedIndex, animated: false, viewPosition: 0.5 });
395 }
396 }, [selectedIndex, selectedKey]);
397
398 const dismissed = useRef(false);
399 const handleDismissed = useCallback(() => {
400 if (dismissed.current) return;
401 dismissed.current = true;
402 // Present navigation sheets only after UIKit has dismissed this modal.
403 props.onClose();
404 pendingAction.current?.();
405 }, [props]);
406
407 // iOS drops Modal onDismiss when the VC is dismissed mid-presentation (e.g.
408 // ⌘K during the fade-in) or raced by another sheet — without a fallback the
409 // palette stays mounted-but-invisible and ⌘K dead-ends on a stale open state.
410 useEffect(() => {
411 if (visible) return;
412 const fallback = setTimeout(handleDismissed, 400);
413 return () => clearTimeout(fallback);
414 }, [visible, handleDismissed]);
415
416 function close(run?: () => void) {
417 if (closing.current) return;
418 closing.current = true;
419 pendingAction.current = run ?? null;
420 setVisible(false);
421 }
422
423 function onCommand(command: HardwareKeyboardCommand) {
424 if (command === "commandPalette" || command === "paletteDismiss") {
425 close();
426 } else if (command === "paletteNext" || command === "palettePrevious") {
427 setSelection(
428 results[nextPaletteIndex(selectedIndex, command === "paletteNext" ? 1 : -1, results.length)]
429 ?.key ?? null,
430 );
431 } else {
432 const item = results[threadJumpIndex(command)];
433 if (item) close(item.run);
434 }
435 }
436
437 return (
438 <Modal
439 visible={visible}
440 transparent
441 animationType="fade"
442 onShow={() => inputRef.current?.focus()}
443 onRequestClose={() => close()}
444 onDismiss={handleDismissed}
445 >
446 <GestureHandlerRootView className="flex-1">
447 <T3KeyboardCommands enabledCommands={PALETTE_COMMANDS} onCommand={onCommand}>
448 <KeyboardAvoidingView
449 behavior="padding"
450 className="flex-1 items-center justify-center py-4"
451 style={{ paddingLeft: 16 + bounds.left, paddingRight: 16 + bounds.right }}
452 >
453 <Pressable
454 className="absolute inset-0 bg-backdrop"
455 accessibilityLabel="Close command palette"
456 onPress={() => close()}
457 />
458 <GlassSurface
459 accessibilityViewIsModal
460 className="bg-sheet"
461 tintColorClassName="accent-sheet/20"
462 fallbackColor={themeVariables["--color-sheet"]}
463 style={{
464 width: Math.min(600, width - 32 - bounds.left - bounds.right),
465 height: Math.min(520, height - 80),
466 borderRadius: 20,
467 }}
468 >
469 <View className="px-3 pb-2.5 pt-3.5">
470 <View className="h-[38px] flex-row items-center gap-1.5 pr-2.5 pl-[11px]">
471 <SymbolView
472 name="magnifyingglass"
473 size={15}
474 tintColorClassName="accent-foreground-muted"
475 type="monochrome"
476 />
477 <TextInput
478 ref={inputRef}
479 accessibilityLabel="Search commands, projects, and threads"
480 placeholder="Search commands, projects, and threads…"
481 placeholderTextColorClassName="accent-placeholder"
482 autoCorrect={false}
483 autoCapitalize="none"
484 clearButtonMode="while-editing"
485 className="h-[34px] flex-1 px-0 py-0 font-sans text-base text-foreground"
486 value={query}
487 onChangeText={(value) => {
488 setQuery(value);
489 setSelection(null);
490 listRef.current?.scrollToOffset({ offset: 0, animated: false });
491 }}
492 returnKeyType="go"
493 submitBehavior="submit"
494 onSubmitEditing={() => {
495 const item = results[selectedIndex];
496 if (item) close(item.run);
497 }}
498 />
499 </View>
500 </View>
501 <FlatList
502 ref={listRef}
503 data={results}
504 extraData={selectedKey}
505 keyboardShouldPersistTaps="handled"
506 keyExtractor={(item) => item.key}
507 getItemLayout={(_, index) => ({
508 length: ROW_HEIGHT,
509 offset: ROW_HEIGHT * index,
510 index,
511 })}
512 contentContainerClassName="pb-2"
513 ListEmptyComponent={
514 <Text className="p-5 text-center text-foreground-muted">
515 {search.isPending ? "Searching…" : "No results"}
516 </Text>
517 }
518 renderItem={({ item, index }) => (
519 <PaletteRow
520 item={item}
521 index={index}
522 selected={item.key === selectedKey}
523 searchMatch={
524 item.kind === "thread" ? contentMatchByKey.get(item.key) : undefined
525 }
526 searchQuery={query}
527 onSelect={() => close(item.run)}
528 />
529 )}
530 />
531 </GlassSurface>
532 </KeyboardAvoidingView>
533 </T3KeyboardCommands>
534 </GestureHandlerRootView>
535 </Modal>
536 );
537}