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

ThreadNavigationSidebar.tsx

1,408 lines52.4 KB

1import { resolveThreadProviderInstance } from "./thread-provider-instance";
2import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
3import { createThreadMovePlanner } from "./threadOrder";
4import type {
5 EnvironmentProject,
6 EnvironmentThreadShell,
7} from "@t3tools/client-runtime/state/shell";
8import {
9 threadSearchMatchKey,
10 type EnvironmentThreadSearchMatch,
11} from "@t3tools/client-runtime/state/thread-search";
12import { LegendList } from "@legendapp/list/react-native";
13import type { MenuAction } from "@react-native-menu/menu";
14import { useAtomValue } from "@effect/atom-react";
15import { type EnvironmentId, resolveEnvironmentMachineKind } from "@t3tools/contracts";
16import { useCallback, useEffect, useMemo, useRef, useState } from "react";
17import type { LayoutChangeEvent } from "react-native";
18import { Platform, Pressable, StyleSheet, TextInput, View } from "react-native";
19import { Gesture, GestureDetector } from "react-native-gesture-handler";
20import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
21import { useSafeAreaInsets } from "react-native-safe-area-context";
22import type { SearchBarCommands } from "react-native-screens";
23​
24import { AppText as Text } from "../../components/AppText";
25import { CompactBrandTitle } from "../../components/CompactBrandTitle";
26import { ControlPillMenu } from "../../components/ControlPill";
27import { SymbolView } from "../../components/AppSymbol";
28import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
29import { NativeStackScreenOptions } from "../../native/StackHeader";
30import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
31import { useProjects, useNavigationThreadShells } from "../../state/entities";
32import { useThreadSearch } from "../../state/queries";
33import { useThreadListV2Enabled } from "./use-thread-list-v2-enabled";
34import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences";
35import { usePendingThreadOrder } from "../../state/thread-order";
36import { environmentServerConfigsAtom } from "../../state/server";
37import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
38import { useQueuedThreadKeys } from "../../state/use-thread-outbox";
39import { useWorkspaceState } from "../../state/workspace";
40import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
41import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
42import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts";
43import {
44 hasCustomHomeListOptions,
45 PROJECT_SORT_OPTIONS,
46 THREAD_SORT_OPTIONS,
47 useHomeListOptions,
48} from "../home/home-list-options";
49import { buildHomeListFilterMenu } from "../home/home-list-filter-menu";
50import {
51 buildHomeListLayout,
52 DEFAULT_GROUP_DISPLAY_STATE,
53 EMPTY_HOME_LIST_LAYOUT,
54 homeListItemsAreEqual,
55 nextGroupDisplayState,
56 type HomeGroupDisplayAction,
57 type HomeGroupDisplayState,
58 type HomeListItem,
59} from "../home/homeListItems";
60import { buildHomeProjectScopes, buildHomeThreadGroups } from "../home/homeThreadList";
61import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
62import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
63import { useThreadListActions } from "../home/useThreadListActions";
64import {
65 getConnectionAwareBrandHeaderOptions,
66 WorkspaceConnectionTitle,
67} from "../home/WorkspaceConnectionTitle";
68import { SidebarHeaderActions } from "./sidebar-header-actions";
69import { SidebarFilterButton } from "./sidebar-filter-button";
70import { createSidebarHeaderItems } from "./sidebar-native-header-items";
71import { SidebarNavigationShell } from "./sidebar-navigation-shell";
72import {
73 PendingTaskListRow,
74 ThreadListGroupHeader,
75 ThreadListRow,
76 ThreadListShowMoreRow,
77} from "./thread-list-items";
78import {
79 ThreadListV2PendingRow,
80 ThreadListV2Row,
81 ThreadListV2SettledShelfHeader,
82 ThreadListV2SnoozedShelfHeader,
83} from "./thread-list-v2-items";
84import {
85 buildThreadListV2Items,
86 getThreadListV2OrderedSection,
87 buildThreadListV2ListItems,
88 resolveThreadListV2ProviderDrivers,
89 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
90 THREAD_LIST_V2_SETTLED_PAGE_COUNT,
91 type ThreadListV2ListItem,
92} from "./threadListV2";
93​
94/** The sidebar list serves both lists: v1 grouped items or, when the Thread
95 List v2 beta is on, flat v2 rows with queued tasks spliced in, and a settled
96 "Show more" pager. */
97type SidebarListItem =
98 | HomeListItem
99 | ThreadListV2ListItem
100 | { readonly type: "v2-show-more"; readonly key: string; readonly hiddenCount: number };
101​
102const SIDEBAR_STICKY_HEADER_HEIGHT = 106;
103​
104interface ThreadNavigationSidebarProps {
105 readonly width: number;
106 readonly visible: boolean;
107 readonly selectedThreadKey: string | null;
108 readonly onOpenSettings: () => void;
109 readonly onOpenEnvironmentSettings: () => void;
110 readonly onNewThreadOnBranch: (thread: EnvironmentThreadShell) => void;
111 readonly onNewThreadInProject: (project: EnvironmentProject) => void;
112 readonly onSearchQueryChange: (query: string) => void;
113 readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
114 readonly onRequestVisibility: () => void;
115 readonly searchQuery: string;
117​
118/**
119 * iPad/large-width sidebar column.
120 *
121 * On iOS the pane is hosted inside its own navigation-inert single-screen
122 * native stack (SidebarNavigationShell) so the header is a real
123 * UINavigationBar: large title, native bar-button items, and a
124 * UISearchController search field — the same chrome a UISplitViewController
125 * column gets. Other platforms keep the custom header chrome.
126 */
127export function ThreadNavigationSidebar(props: ThreadNavigationSidebarProps) {
128 if (Platform.OS !== "ios") {
129 return <ThreadNavigationSidebarPane {...props} nativeChrome={false} />;
130 }
131 return <NativeSidebarContainer {...props} />;
133​
134function NativeSidebarContainer(props: ThreadNavigationSidebarProps) {
135 return (
136 <View
137 testID="thread-navigation-sidebar"
138 className="flex-1 border-border bg-drawer"
139 style={{ borderRightWidth: StyleSheet.hairlineWidth, width: props.width }}
140 >
141 <SidebarNavigationShell>
142 <ThreadNavigationSidebarPane {...props} nativeChrome />
143 </SidebarNavigationShell>
144 </View>
145 );
147​
148function ThreadNavigationSidebarPane(
149 props: ThreadNavigationSidebarProps & { readonly nativeChrome: boolean },
150) {
151 const { materialYouStyleLayoutActive, themeVariables: materialTheme } =
152 useAppearancePreferences();
153 const screenColor = materialTheme["--color-screen"];
154 const mutedColor = materialTheme["--color-foreground-muted"];
155​
156 const insets = useSafeAreaInsets();
157 const projects = useProjects();
158 const threads = useNavigationThreadShells();
159 const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
160 const { savedConnectionsById } = useSavedRemoteConnections();
161 const searchInputRef = useRef<TextInput>(null);
162 const searchBarRef = useRef<SearchBarCommands>(null);
163 const openSwipeableRef = useRef<SwipeableMethods | null>(null);
164 const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
165 const {
166 archiveThread,
167 confirmDeleteThread,
168 settleThread,
169 snoozeThread,
170 unsnoozeThread,
171 unsettleThread,
172 pinThread,
173 unpinThread,
174 moveThread,
175 regenerateThreadTitle,
176 } = useThreadListActions();
177 const threadListV2Enabled = useThreadListV2Enabled();
178 const pendingTasks = usePendingNewTasks();
179 const queuedThreadKeys = useQueuedThreadKeys();
180 const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
181 const environments = useMemo(
182 () =>
183 Object.values(savedConnectionsById)
184 .map((connection) => ({
185 environmentId: connection.environmentId,
186 label: connection.environmentLabel,
187 }))
188 .sort((left, right) => left.label.localeCompare(right.label)),
189 [savedConnectionsById],
190 );
191 const availableEnvironmentIds = useMemo(
192 () => new Set(environments.map((environment) => environment.environmentId)),
193 [environments],
194 );
195 const { options, setSelectedEnvironmentId, setProjectSortOrder, setThreadSortOrder } =
196 useHomeListOptions(availableEnvironmentIds);
197 const searchEnvironmentIds = useMemo(
198 () =>
199 options.selectedEnvironmentId === null
200 ? workspaceEnvironments
201 .filter((environment) => environment.connectionState === "connected")
202 .map((environment) => environment.environmentId)
203 : workspaceEnvironments.some(
204 (environment) =>
205 environment.environmentId === options.selectedEnvironmentId &&
206 environment.connectionState === "connected",
207 )
208 ? [options.selectedEnvironmentId]
209 : [],
210 [options.selectedEnvironmentId, workspaceEnvironments],
211 );
212 const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery);
213 const threadSearchMatchByKey = useMemo(() => {
214 const matches = new Map<string, EnvironmentThreadSearchMatch>();
215 for (const match of threadSearch.matches) {
216 if (match.source === "user" || match.source === "assistant") {
217 matches.set(threadSearchMatchKey(match), match);
218 }
219 }
220 return matches;
221 }, [threadSearch.matches]);
222 const matchedThreadKeys = useMemo(
223 () => new Set(threadSearch.matches.map(threadSearchMatchKey)),
224 [threadSearch.matches],
225 );
226 const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
227 const projectScopes = useMemo(
228 () =>
229 buildHomeProjectScopes({
230 projects,
231 environmentId: options.selectedEnvironmentId,
232 projectGroupingMode: options.projectGroupingMode,
233 }),
234 [options.projectGroupingMode, options.selectedEnvironmentId, projects],
235 );
236 const projectFilterOptions = useMemo(
237 () =>
238 projectScopes.map((scope) => ({
239 key: scope.key,
240 label: scope.title,
241 })),
242 [projectScopes],
243 );
244 const projectTitleByProjectKey = useMemo(
245 () =>
246 new Map(
247 projectScopes.flatMap((scope) =>
248 scope.projectRefs.map(
249 (projectRef) =>
250 [
251 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
252 scope.title,
253 ] as const,
254 ),
255 ),
256 ),
257 [projectScopes],
258 );
259 const selectedProjectScope = useMemo(
260 () =>
261 selectedProjectKey === null
262 ? null
263 : (projectScopes.find((scope) => scope.key === selectedProjectKey) ?? null),
264 [projectScopes, selectedProjectKey],
265 );
266 useEffect(() => {
267 if (
268 selectedProjectKey !== null &&
269 !projectFilterOptions.some((project) => project.key === selectedProjectKey)
270 ) {
271 setSelectedProjectKey(null);
272 }
273 }, [projectFilterOptions, selectedProjectKey]);
274 const selectedProjectRefs = useMemo(
275 () =>
276 selectedProjectScope === null
277 ? null
278 : new Set(
279 selectedProjectScope.projectRefs.map((projectRef) =>
280 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
281 ),
282 ),
283 [selectedProjectScope],
284 );
285 const scopedProjects = useMemo(
286 () =>
287 threadListV2Enabled
288 ? []
289 : selectedProjectRefs === null
290 ? projects
291 : projects.filter((project) =>
292 selectedProjectRefs.has(scopedProjectKey(project.environmentId, project.id)),
293 ),
294 [threadListV2Enabled, projects, selectedProjectRefs],
295 );
296 const scopedThreads = useMemo(
297 () =>
298 threadListV2Enabled
299 ? []
300 : selectedProjectRefs === null
301 ? threads
302 : threads.filter((thread) =>
303 selectedProjectRefs.has(scopedProjectKey(thread.environmentId, thread.projectId)),
304 ),
305 [threadListV2Enabled, selectedProjectRefs, threads],
306 );
307 const scopedPendingTasks = useMemo(
308 () =>
309 threadListV2Enabled
310 ? []
311 : selectedProjectRefs === null
312 ? pendingTasks
313 : pendingTasks.filter((pendingTask) =>
314 selectedProjectRefs.has(
315 scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),
316 ),
317 ),
318 [threadListV2Enabled, pendingTasks, selectedProjectRefs],
319 );
320 const groups = useMemo(
321 () =>
322 threadListV2Enabled
323 ? []
324 : buildHomeThreadGroups({
325 projects: scopedProjects,
326 threads: scopedThreads,
327 pendingTasks: scopedPendingTasks,
328 queuedThreadKeys,
329 environmentId: options.selectedEnvironmentId,
330 searchQuery: props.searchQuery,
331 matchedThreadKeys,
332 projectSortOrder: options.projectSortOrder,
333 threadSortOrder: options.threadSortOrder,
334 projectGroupingMode: options.projectGroupingMode,
335 }),
336 [
337 threadListV2Enabled,
338 queuedThreadKeys,
339 matchedThreadKeys,
340 options,
341 props.searchQuery,
342 scopedPendingTasks,
343 scopedProjects,
344 scopedThreads,
345 ],
346 );
347 const [groupDisplayStates, setGroupDisplayStates] = useState<
348 ReadonlyMap<string, HomeGroupDisplayState>
349 >(() => new Map());
350 const updateGroupDisplay = useCallback((key: string, action: HomeGroupDisplayAction) => {
351 setGroupDisplayStates((previous) => {
352 const next = new Map(previous);
353 next.set(
354 key,
355 nextGroupDisplayState(previous.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action),
356 );
357 return next;
358 });
359 }, []);
360 const hasSearchQuery = props.searchQuery.trim().length > 0;
361 const listLayout = useMemo(
362 () =>
363 threadListV2Enabled
364 ? EMPTY_HOME_LIST_LAYOUT
365 : buildHomeListLayout({
366 groups,
367 displayStates: groupDisplayStates,
368 showAllThreads: hasSearchQuery,
369 }),
370 [threadListV2Enabled, groups, groupDisplayStates, hasSearchQuery],
371 );
372 const projectByKey = useMemo(() => {
373 const map = new Map<string, EnvironmentProject>();
374 for (const project of projects) {
375 map.set(scopedProjectKey(project.environmentId, project.id), project);
376 }
377 return map;
378 }, [projects]);
379​
380 // Thread List v2 (beta) support — same model as the compact Home list
381 // (HomeScreen.tsx): flat creation-order card block + settled recency tail.
382 // The settled tail renders in pages; expansion resets when the filter
383 // context changes so environment/search flips never inherit a deep page.
384 const [settledVisibleCount, setSettledVisibleCount] = useState(
385 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
386 );
387 const settledResetKey = `${options.selectedEnvironmentId ?? "all"}:${selectedProjectKey ?? "all"}:${props.searchQuery.trim()}`;
388 const lastSettledResetKeyRef = useRef(settledResetKey);
389 if (lastSettledResetKeyRef.current !== settledResetKey) {
390 lastSettledResetKeyRef.current = settledResetKey;
391 setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
392 }
393 const showMoreSettled = useCallback(
394 () => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
395 [],
396 );
397 const {
398 loaded: shelfPreferencesLoaded,
399 settledShelfExpanded,
400 snoozedShelfExpanded,
401 toggleSettledShelf,
402 toggleSnoozedShelf,
403 } = useThreadListV2ShelfPreferences();
404 // The queued-start and snooze helpers need a clock while the pane stays open.
405 const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
406 // Snooze wake times are second-precise; a counter bumped exactly at the
407 // next wake boundary re-runs the partition with a fresh clock so a woken
408 // thread reappears immediately instead of on the next minute tick.
409 const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
410 useEffect(() => {
411 if (!threadListV2Enabled) return;
412 // Refresh immediately because the mount-time value can be hours old.
413 setNowMinute(new Date().toISOString().slice(0, 16));
414 const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
415 return () => clearInterval(id);
416 }, [threadListV2Enabled]);
417 // Threads on servers without the settlement capability never classify as
418 // settled (the user could neither un-settle nor pin them).
419 const serverConfigs = useAtomValue(environmentServerConfigsAtom);
420 const settlementEnvironmentIds = useMemo(() => {
421 const supported = new Set<EnvironmentId>();
422 for (const [environmentId, config] of serverConfigs) {
423 if (config.environment.capabilities.threadSettlement === true) {
424 supported.add(environmentId);
425 }
426 }
427 return supported;
428 }, [serverConfigs]);
429 const snoozeEnvironmentIds = useMemo(() => {
430 const supported = new Set<EnvironmentId>();
431 for (const [environmentId, config] of serverConfigs) {
432 if (config.environment.capabilities.threadSnooze === true) {
433 supported.add(environmentId);
434 }
435 }
436 return supported;
437 }, [serverConfigs]);
438 const pinningEnvironmentIds = useMemo(() => {
439 const supported = new Set<EnvironmentId>();
440 for (const [environmentId, config] of serverConfigs) {
441 if (config.environment.capabilities.threadPinning === true) {
442 supported.add(environmentId);
443 }
444 }
445 return supported;
446 }, [serverConfigs]);
447 const pinReorderEnvironmentIds = useMemo(() => {
448 const supported = new Set<EnvironmentId>();
449 for (const [environmentId, config] of serverConfigs) {
450 if (config.environment.capabilities.threadPinReorder === true) {
451 supported.add(environmentId);
452 }
453 }
454 return supported;
455 }, [serverConfigs]);
456 const activeReorderEnvironmentIds = useMemo(() => {
457 const supported = new Set<EnvironmentId>();
458 for (const [environmentId, config] of serverConfigs) {
459 if (config.environment.capabilities.threadActiveReorder === true) {
460 supported.add(environmentId);
461 }
462 }
463 return supported;
464 }, [serverConfigs]);
465 const titleRegenerationEnvironmentIds = useMemo(() => {
466 const supported = new Set<EnvironmentId>();
467 for (const [environmentId, config] of serverConfigs) {
468 if (config.environment.capabilities.threadTitleRegeneration === true) {
469 supported.add(environmentId);
470 }
471 }
472 return supported;
473 }, [serverConfigs]);
474 const machineByEnvironmentId = useMemo(
475 () =>
476 new Map(
477 [...serverConfigs].map(
478 ([environmentId, config]) =>
479 [environmentId, resolveEnvironmentMachineKind(config)] as const,
480 ),
481 ),
482 [serverConfigs],
483 );
484 const pendingOrder = usePendingThreadOrder(nowMinute, snoozeWakeTick);
485 const threadMovePlanners = useMemo(() => {
486 const sectionPlanner = (section: "pinned" | "active") =>
487 createThreadMovePlanner({
488 allThreads: threads,
489 section,
490 reorderableEnvironmentIds: new Set(
491 [...serverConfigs].flatMap(([id, config]) =>
492 (section === "pinned"
493 ? config.environment.capabilities.threadPinReorder
494 : config.environment.capabilities.threadActiveReorder) === true
495 ? [id]
496 : [],
497 ),
498 ),
499 ordered: getThreadListV2OrderedSection({
500 threads,
501 section,
502 pendingOrder,
503 now: new Date().toISOString(),
504 settlementEnvironmentIds,
505 snoozeEnvironmentIds,
506 queuedThreadKeys,
507 }),
508 });
509 return { pinned: sectionPlanner("pinned"), active: sectionPlanner("active") };
510 }, [
511 serverConfigs,
512 threads,
513 pendingOrder,
514 queuedThreadKeys,
515 settlementEnvironmentIds,
516 snoozeEnvironmentIds,
517 nowMinute,
518 snoozeWakeTick,
519 ]);
520 const threadListV2Layout = useMemo(() => {
521 if (!threadListV2Enabled)
522 return {
523 items: [],
524 hiddenSettledCount: 0,
525 snoozedCount: 0,
526 snoozedShelfHeaderIndex: null,
527 settledCount: 0,
528 settledShelfHeaderIndex: null,
529 nextSnoozeWakeAt: null,
530 };
531 return buildThreadListV2Items({
532 pendingOrder,
533 threads: threads.filter((thread) => thread.archivedAt === null),
534 environmentId: options.selectedEnvironmentId,
535 projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
536 searchQuery: props.searchQuery,
537 matchedThreadKeys,
538 settlementEnvironmentIds,
539 snoozeEnvironmentIds,
540 queuedThreadKeys,
541 settledLimit: settledVisibleCount,
542 now: new Date().toISOString(),
543 snoozedShelfExpanded,
544 settledShelfExpanded,
545 selectedThreadKey: props.selectedThreadKey ?? null,
546 });
547 }, [
548 pendingOrder,
549 queuedThreadKeys,
550 nowMinute,
551 snoozeWakeTick,
552 snoozedShelfExpanded,
553 settledShelfExpanded,
554 props.selectedThreadKey,
555 options.selectedEnvironmentId,
556 props.searchQuery,
557 matchedThreadKeys,
558 settledVisibleCount,
559 settlementEnvironmentIds,
560 snoozeEnvironmentIds,
561 threadListV2Enabled,
562 threads,
563 selectedProjectScope,
564 ]);
565 // Re-partition the moment the earliest snooze expires (clamped to the
566 // signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
567 const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
568 useEffect(() => {
569 if (nextSnoozeWakeAt === null) return;
570 const wakeAtMs = Date.parse(nextSnoozeWakeAt);
571 if (Number.isNaN(wakeAtMs)) return;
572 const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
573 const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
574 return () => clearTimeout(id);
575 // snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
576 // unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
577 // range) the boundary string is identical and the chain would die.
578 }, [nextSnoozeWakeAt, snoozeWakeTick]);
579 const listItems = useMemo<readonly SidebarListItem[]>(() => {
580 if (!threadListV2Enabled) return listLayout.items;
581 // Queued offline tasks are not thread shells, so the v2 item builder
582 // never sees them; the shared splice puts them below the active block
583 // (mirrors the compact Home v2 list) where they stay visible and
584 // deletable while their environment is offline. Same environment scope
585 // and search filter as the list.
586 const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
587 const v2PendingTasks = pendingTasks.filter(
588 (pendingTask) =>
589 (options.selectedEnvironmentId === null ||
590 pendingTask.environmentId === options.selectedEnvironmentId) &&
591 (selectedProjectRefs === null ||
592 selectedProjectRefs.has(
593 scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),
594 )) &&
595 (v2SearchQuery.length === 0 ||
596 pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
597 );
598 const items: SidebarListItem[] = buildThreadListV2ListItems({
599 items: threadListV2Layout.items,
600 pendingTasks: v2PendingTasks,
601 snoozedCount: threadListV2Layout.snoozedCount,
602 snoozedShelfExpanded,
603 snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
604 settledCount: threadListV2Layout.settledCount,
605 settledShelfExpanded,
606 settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
607 snoozeLabelNow: `${nowMinute}:00.000Z`,
608 });
609 if (settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0) {
610 items.push({
611 type: "v2-show-more",
612 key: "v2-show-more",
613 hiddenCount: threadListV2Layout.hiddenSettledCount,
614 });
615 }
616 return items;
617 }, [
618 listLayout.items,
619 nowMinute,
620 options.selectedEnvironmentId,
621 pendingTasks,
622 props.searchQuery,
623 selectedProjectRefs,
624 settledShelfExpanded,
625 snoozedShelfExpanded,
626 threadListV2Enabled,
627 threadListV2Layout,
628 ]);
629 const listMenuActions = useMemo<MenuAction[]>(
630 () => [
631 {
632 id: "environment",
633 title: "Environment",
634 subactions: [
635 {
636 id: "environment:all",
637 title: "All environments",
638 subtitle: "Show threads from every environment",
639 state: options.selectedEnvironmentId === null ? "on" : "off",
640 },
641 ...environments.map((environment) => ({
642 id: `environment:${environment.environmentId}`,
643 title: environment.label,
644 state:
645 options.selectedEnvironmentId === environment.environmentId
646 ? ("on" as const)
647 : ("off" as const),
648 })),
649 ],
650 },
651 ...(projectFilterOptions.length === 0
652 ? []
653 : ([
654 {
655 id: "project",
656 title: "Project",
657 subactions: [
658 {
659 id: "project:all",
660 title: "All projects",
661 subtitle: "Show threads from every project",
662 state: selectedProjectKey === null ? "on" : "off",
663 },
664 ...projectFilterOptions.map((project) => ({
665 id: `project:${project.key}`,
666 title: project.label,
667 state: selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
668 })),
669 ],
670 },
671 ] satisfies MenuAction[])),
672 // v2 lays the list out in fixed creation order — offering sort/group
673 // controls it silently ignores would be a lie. Environment still
674 // scopes the v2 partition, so it stays.
675 ...(threadListV2Enabled
676 ? []
677 : ([
678 {
679 id: "project-sort",
680 title: "Sort projects",
681 subactions: PROJECT_SORT_OPTIONS.map((option) => ({
682 id: `project-sort:${option.value}`,
683 title: option.label,
684 state: options.projectSortOrder === option.value ? "on" : "off",
685 })),
686 },
687 {
688 id: "thread-sort",
689 title: "Sort threads",
690 subactions: THREAD_SORT_OPTIONS.map((option) => ({
691 id: `thread-sort:${option.value}`,
692 title: option.label,
693 state: options.threadSortOrder === option.value ? "on" : "off",
694 })),
695 },
696 ] satisfies MenuAction[])),
697 ],
698 [environments, options, projectFilterOptions, selectedProjectKey, threadListV2Enabled],
699 );
700 const handleListMenuAction = useCallback(
701 ({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
702 const event = nativeEvent.event;
703 if (event === "environment:all") {
704 setSelectedEnvironmentId(null);
705 return;
706 }
707 if (event.startsWith("environment:")) {
708 const environment = environments.find(
709 (candidate) => String(candidate.environmentId) === event.slice("environment:".length),
710 );
711 if (environment) setSelectedEnvironmentId(environment.environmentId);
712 return;
713 }
714 if (event === "project:all") {
715 setSelectedProjectKey(null);
716 return;
717 }
718 if (event.startsWith("project:")) {
719 const projectKey = event.slice("project:".length);
720 if (projectFilterOptions.some((project) => project.key === projectKey)) {
721 setSelectedProjectKey(projectKey);
722 }
723 return;
724 }
725 const projectSort = PROJECT_SORT_OPTIONS.find(
726 (option) => `project-sort:${option.value}` === event,
727 );
728 if (projectSort) {
729 setProjectSortOrder(projectSort.value);
730 return;
731 }
732 const threadSort = THREAD_SORT_OPTIONS.find(
733 (option) => `thread-sort:${option.value}` === event,
734 );
735 if (threadSort) {
736 setThreadSortOrder(threadSort.value);
737 return;
738 }
739 },
740 [
741 environments,
742 projectFilterOptions,
743 setProjectSortOrder,
744 setSelectedEnvironmentId,
745 setThreadSortOrder,
746 ],
747 );
748​
749 const [measuredHeaderHeight, setMeasuredHeaderHeight] = useState<number | null>(null);
750 // The sticky header (title row, search field, optional connection status)
751 // is measured so the list inset always matches its real height — no
752 // hardcoded per-variant constants.
753 const stickyHeaderHeight = measuredHeaderHeight ?? insets.top + SIDEBAR_STICKY_HEADER_HEIGHT;
754 const topListInset = stickyHeaderHeight + 6;
755 const handleStickyHeaderLayout = useCallback((event: LayoutChangeEvent) => {
756 const nextHeight = Math.round(event.nativeEvent.layout.height);
757 setMeasuredHeaderHeight((current) => (current === nextHeight ? current : nextHeight));
758 }, []);
759 const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
760 if (openSwipeableRef.current !== methods) {
761 openSwipeableRef.current?.close();
762 openSwipeableRef.current = methods;
763 }
764 }, []);
765 const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
766 if (openSwipeableRef.current === methods) {
767 openSwipeableRef.current = null;
768 }
769 }, []);
770 const handleSelectThread = useCallback(
771 (thread: EnvironmentThreadShell) => {
772 props.onSelectThread(thread);
773 openSwipeableRef.current?.close();
774 },
775 [props.onSelectThread],
776 );
777 const handleScrollBeginDrag = useCallback(() => {
778 openSwipeableRef.current?.close();
779 }, []);
780 const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
781 onScrollBeginDrag: handleScrollBeginDrag,
782 });
783 // Project shells load after the first rows draw, so the maps they feed have
784 // to bust the recycler's memoization — otherwise a row keeps the blank
785 // favicon and fallback title it was first rendered with.
786 const listExtraData = useMemo(
787 () => ({
788 selectedThreadKey: props.selectedThreadKey ?? "",
789 projectByKey,
790 projectTitleByProjectKey,
791 savedConnectionsById,
792 serverConfigs,
793 snoozePresetMinute: nowMinute,
794 threadSearchMatchByKey,
795 }),
796 [
797 props.selectedThreadKey,
798 projectByKey,
799 projectTitleByProjectKey,
800 savedConnectionsById,
801 serverConfigs,
802 nowMinute,
803 threadSearchMatchByKey,
804 ],
805 );
806 useThreadJumpShortcuts(listItems, handleSelectThread);
807 const sidebarItemsAreEqual = useCallback(
808 (previous: SidebarListItem, item: SidebarListItem): boolean => {
809 if (previous.type === "v2-thread" && item.type === "v2-thread") {
810 return (
811 previous.key === item.key &&
812 previous.item.thread === item.item.thread &&
813 previous.item.variant === item.item.variant &&
814 previous.item.snoozed === item.item.snoozed &&
815 previous.item.pinned === item.item.pinned &&
816 previous.snoozeWakeLabelText === item.snoozeWakeLabelText
817 );
818 }
819 if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
820 return previous.hiddenCount === item.hiddenCount;
821 }
822 if (previous.type === "v2-pending" && item.type === "v2-pending") {
823 return (
824 previous.pendingTask === item.pendingTask &&
825 previous.showPendingDivider === item.showPendingDivider
826 );
827 }
828 if (previous.type === "v2-snoozed-shelf" && item.type === "v2-snoozed-shelf") {
829 return previous.count === item.count && previous.expanded === item.expanded;
830 }
831 if (previous.type === "v2-settled-shelf" && item.type === "v2-settled-shelf") {
832 return previous.count === item.count && previous.expanded === item.expanded;
833 }
834 if (
835 previous.type === "v2-thread" ||
836 previous.type === "v2-show-more" ||
837 previous.type === "v2-pending" ||
838 previous.type === "v2-snoozed-shelf" ||
839 previous.type === "v2-settled-shelf" ||
840 item.type === "v2-thread" ||
841 item.type === "v2-show-more" ||
842 item.type === "v2-pending" ||
843 item.type === "v2-snoozed-shelf" ||
844 item.type === "v2-settled-shelf"
845 ) {
846 return false;
847 }
848 return homeListItemsAreEqual(previous, item);
849 },
850 [],
851 );
852 const focusSearch = useCallback(() => {
853 const focus = () => {
854 if (props.nativeChrome) {
855 searchBarRef.current?.focus();
856 return;
857 }
858 searchInputRef.current?.focus();
859 };
860 if (!props.visible) {
861 props.onRequestVisibility();
862 setTimeout(focus, 240);
863 } else {
864 focus();
865 }
866 return true;
867 }, [props.nativeChrome, props.onRequestVisibility, props.visible]);
868 useHardwareKeyboardCommand("focusSearch", focusSearch);
869 const renderListItem = useCallback(
870 ({ item }: { readonly item: SidebarListItem }) => {
871 switch (item.type) {
872 case "v2-pending": {
873 const pendingScopeKey = scopedProjectKey(
874 item.pendingTask.environmentId,
875 item.pendingTask.projectId,
876 );
877 return (
878 <ThreadListV2PendingRow
879 pendingTask={item.pendingTask}
880 project={projectByKey.get(pendingScopeKey) ?? null}
881 projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}
882 environmentLabel={
883 Object.keys(savedConnectionsById).length > 1
884 ? (savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? null)
885 : null
886 }
887 environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
888 pane="sidebar"
889 showPendingDivider={item.showPendingDivider}
890 onSelectPendingTask={openPendingTask}
891 onDeletePendingTask={confirmDeletePendingTask}
892 />
893 );
894 }
895 case "v2-thread": {
896 const thread = item.item.thread;
897 const movePlanner = item.item.pinned
898 ? threadMovePlanners.pinned
899 : threadMovePlanners.active;
900 const movedId = `${thread.environmentId}:${thread.id}`;
901 const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId);
902 const provider = serverConfigs
903 .get(thread.environmentId)
904 ?.providers.find(
905 (candidate) =>
906 candidate.instanceId ===
907 (thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId),
908 );
909 return (
910 <ThreadListV2Row
911 onNewThreadOnBranch={props.onNewThreadOnBranch}
912 thread={thread}
913 variant={item.item.variant}
914 hasQueuedMessages={queuedThreadKeys.has(`${thread.environmentId}:${thread.id}`)}
915 snoozed={item.item.snoozed}
916 pinned={item.item.pinned}
917 snoozePresetMinute={nowMinute}
918 snoozeWakeLabelText={item.snoozeWakeLabelText}
919 project={projectByKey.get(scopeKey) ?? null}
920 projectTitle={projectTitleByProjectKey.get(scopeKey)}
921 providerDrivers={resolveThreadListV2ProviderDrivers(
922 thread,
923 serverConfigs.get(thread.environmentId)?.providers,
924 )}
925 providerInstance={resolveThreadProviderInstance(serverConfigs, thread)}
926 providerIconUrl={provider?.iconUrl}
927 environmentLabel={
928 Object.keys(savedConnectionsById).length > 1
929 ? (savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
930 : null
931 }
932 environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
933 searchMatch={threadSearchMatchByKey.get(
934 threadSearchMatchKey({
935 environmentId: thread.environmentId,
936 threadId: thread.id,
937 }),
938 )}
939 searchQuery={props.searchQuery}
940 pane={materialYouStyleLayoutActive ? "screen" : "sidebar"}
941 selected={
942 scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
943 }
944 fullSwipeWidth={props.width - 20}
945 onSelectThread={handleSelectThread}
946 onDeleteThread={confirmDeleteThread}
947 onArchiveThread={archiveThread}
948 onRegenerateThreadTitle={regenerateThreadTitle}
949 titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
950 settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
951 onSettleThread={settleThread}
952 snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
953 pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
954 reorderSupported={
955 item.item.pinned
956 ? pinReorderEnvironmentIds.has(thread.environmentId)
957 : activeReorderEnvironmentIds.has(thread.environmentId)
958 }
959 canMoveUp={pendingOrder === null && movePlanner(movedId, "up") !== null}
960 canMoveDown={pendingOrder === null && movePlanner(movedId, "down") !== null}
961 onSnoozeThread={snoozeThread}
962 onUnsnoozeThread={unsnoozeThread}
963 onUnsettleThread={unsettleThread}
964 onPinThread={pinThread}
965 onUnpinThread={unpinThread}
966 onMoveThread={moveThread}
967 onSwipeableClose={handleSwipeableClose}
968 onSwipeableWillOpen={handleSwipeableWillOpen}
969 simultaneousSwipeGesture={sidebarScrollGesture}
970 />
971 );
972 }
973 case "v2-snoozed-shelf":
974 return (
975 <ThreadListV2SnoozedShelfHeader
976 count={item.count}
977 disabled={!shelfPreferencesLoaded}
978 expanded={item.expanded}
979 onToggle={toggleSnoozedShelf}
980 pane={materialYouStyleLayoutActive ? "screen" : "sidebar"}
981 />
982 );
983 case "v2-settled-shelf":
984 return (
985 <ThreadListV2SettledShelfHeader
986 count={item.count}
987 disabled={!shelfPreferencesLoaded}
988 expanded={item.expanded}
989 onToggle={toggleSettledShelf}
990 pane={materialYouStyleLayoutActive ? "screen" : "sidebar"}
991 />
992 );
993 case "v2-show-more":
994 return (
995 <Pressable
996 accessibilityRole="button"
997 accessibilityLabel={`Show ${Math.min(item.hiddenCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
998 onPress={showMoreSettled}
999 className="mx-4 mt-2 items-center rounded-lg border border-dashed border-border py-2.5"
1000 style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
1002 <Text className="text-xs font-t3-medium text-foreground-muted">
1003 Show more ({item.hiddenCount} settled hidden)
1004 </Text>
1005 </Pressable>
1006 );
1007 case "header":
1008 return (
1009 <ThreadListGroupHeader
1010 variant={materialYouStyleLayoutActive ? "compact" : "sidebar"}
1011 collapsed={item.collapsed}
1012 isFirst={item.isFirst}
1013 groupKey={item.group.key}
1014 onGroupAction={updateGroupDisplay}
1015 // Same gating as the compact Home list: aggregated groups have no
1016 // single target project, and pending-project groups hold a
1017 // placeholder shell rather than a real project.
1018 newThreadTarget={item.group.newThreadTarget}
1019 onNewThread={props.onNewThreadInProject}
1020 project={item.group.representative}
1021 threadCount={item.group.threads.length + item.group.pendingTasks.length}
1022 title={item.group.title}
1023 />
1024 );
1025 case "pending-task":
1026 return (
1027 <PendingTaskListRow
1028 variant={materialYouStyleLayoutActive ? "compact" : "sidebar"}
1029 pendingTask={item.pendingTask}
1030 environmentLabel={
1031 savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? null
1033 environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
1034 isLast={item.isLast}
1035 onSelectPendingTask={openPendingTask}
1036 onDeletePendingTask={confirmDeletePendingTask}
1037 />
1038 );
1039 case "thread": {
1040 const thread = item.thread;
1041 return (
1042 <ThreadListRow
1043 onNewThreadOnBranch={props.onNewThreadOnBranch}
1044 variant="sidebar"
1045 thread={thread}
1046 hasQueuedMessages={queuedThreadKeys.has(`${thread.environmentId}:${thread.id}`)}
1047 environmentLabel={
1048 savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
1050 environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
1051 isLast={item.isLast}
1052 searchMatch={threadSearchMatchByKey.get(
1053 threadSearchMatchKey({
1054 environmentId: thread.environmentId,
1055 threadId: thread.id,
1056 }),
1057 )}
1058 searchQuery={props.searchQuery}
1059 selected={
1060 scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
1062 fullSwipeWidth={props.width - 20}
1063 onArchiveThread={archiveThread}
1064 onDeleteThread={confirmDeleteThread}
1065 onRegenerateThreadTitle={regenerateThreadTitle}
1066 titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
1067 onSelectThread={handleSelectThread}
1068 onSwipeableClose={handleSwipeableClose}
1069 onSwipeableWillOpen={handleSwipeableWillOpen}
1070 simultaneousSwipeGesture={sidebarScrollGesture}
1071 />
1072 );
1074 case "show-more":
1075 return (
1076 <ThreadListShowMoreRow
1077 variant={materialYouStyleLayoutActive ? "compact" : "sidebar"}
1078 hiddenCount={item.hiddenCount}
1079 canShowLess={item.canShowLess}
1080 groupKey={item.groupKey}
1081 onGroupAction={updateGroupDisplay}
1082 />
1083 );
1085 },
1087 materialYouStyleLayoutActive,
1088 archiveThread,
1089 activeReorderEnvironmentIds,
1090 threadMovePlanners,
1091 pendingOrder,
1092 queuedThreadKeys,
1093 confirmDeletePendingTask,
1094 confirmDeleteThread,
1095 handleSelectThread,
1096 handleSwipeableClose,
1097 handleSwipeableWillOpen,
1098 machineByEnvironmentId,
1099 moveThread,
1100 openPendingTask,
1101 pinReorderEnvironmentIds,
1102 pinThread,
1103 pinningEnvironmentIds,
1104 projectByKey,
1105 projectTitleByProjectKey,
1106 regenerateThreadTitle,
1107 props.onNewThreadInProject,
1108 props.onNewThreadOnBranch,
1109 props.searchQuery,
1110 props.selectedThreadKey,
1111 props.width,
1112 savedConnectionsById,
1113 serverConfigs,
1114 shelfPreferencesLoaded,
1115 threadSearchMatchByKey,
1116 titleRegenerationEnvironmentIds,
1117 settleThread,
1118 settlementEnvironmentIds,
1119 showMoreSettled,
1120 sidebarScrollGesture,
1121 snoozeEnvironmentIds,
1122 snoozeThread,
1123 nowMinute,
1124 toggleSettledShelf,
1125 toggleSnoozedShelf,
1126 unpinThread,
1127 unsettleThread,
1128 unsnoozeThread,
1129 updateGroupDisplay,
1130 ],
1131 );
1132 // v2 ignores the sort/group options, so only the environment filter can
1133 // light the "customized" state while the beta is on.
1134 const filterCustomized = threadListV2Enabled
1135 ? options.selectedEnvironmentId !== null || selectedProjectKey !== null
1136 : hasCustomHomeListOptions({ ...options, selectedProjectKey });
1137 const filterIcon = filterCustomized
1138 ? "line.3.horizontal.decrease.circle.fill"
1139 : "line.3.horizontal.decrease.circle";
1140 const filterMenu = useMemo(
1141 () =>
1142 buildHomeListFilterMenu({
1143 environments,
1144 projects: projectFilterOptions,
1145 selectedEnvironmentId: options.selectedEnvironmentId,
1146 selectedProjectKey,
1147 projectSortOrder: options.projectSortOrder,
1148 threadSortOrder: options.threadSortOrder,
1149 onEnvironmentChange: setSelectedEnvironmentId,
1150 onProjectChange: setSelectedProjectKey,
1151 onProjectSortOrderChange: setProjectSortOrder,
1152 onThreadSortOrderChange: setThreadSortOrder,
1153 listOrganization: !threadListV2Enabled,
1154 }),
1156 environments,
1157 options,
1158 projectFilterOptions,
1159 selectedProjectKey,
1160 setProjectSortOrder,
1161 setSelectedEnvironmentId,
1162 setThreadSortOrder,
1163 threadListV2Enabled,
1164 ],
1165 );
1166 const nativeHeaderItems = useMemo(
1167 () =>
1168 createSidebarHeaderItems({
1169 filterIcon,
1170 filterMenu,
1171 onOpenSettings: props.onOpenSettings,
1172 }),
1173 [filterIcon, filterMenu, props.onOpenSettings],
1174 );
1175 // Snoozed threads need no special case: the shelf header is a list row
1176 // even while collapsed.
1177 const listEmpty = (
1178 <Text className="px-2 py-4 text-sm text-foreground-muted">
1179 {catalogState.isLoadingConnections
1180 ? "Loading threads…"
1181 : props.searchQuery.trim().length > 0
1182 ? threadSearch.isPending
1183 ? "Searching thread messages…"
1184 : "No matching threads"
1185 : selectedProjectScope !== null
1186 ? `No threads in ${selectedProjectScope.title}`
1187 : "No threads yet"}
1188 </Text>
1189 );
1190​
1191 if (props.nativeChrome) {
1192 return (
1193 <>
1194 <NativeStackScreenOptions
1195 optionsVersion={[nativeHeaderItems, props.width]}
1196 options={{
1197 // Re-applies the shell's static brand slot with the
1198 // connection-status swap so reconnects surface in the header
1199 // instead of shifting the list.
1200 ...getConnectionAwareBrandHeaderOptions({
1201 headerWidth: props.width,
1202 trailingItemCount: nativeHeaderItems.length,
1203 onOpenEnvironments: props.onOpenEnvironmentSettings,
1204 fallbackTitleStyle: { fontSize: 18, fontWeight: "800" },
1205 }),
1206 headerSearchBarOptions: {
1207 ref: searchBarRef,
1208 autoCapitalize: "none",
1209 hideNavigationBar: false,
1210 // Keep the search bar pinned under the title — UIKit's default
1211 // hidesSearchBarWhenScrolling collapses it on scroll.
1212 hideWhenScrolling: false,
1213 obscureBackground: false,
1214 placeholder: "Search",
1215 placement: "stacked",
1216 onCancelButtonPress: () => {
1217 props.onSearchQueryChange("");
1218 },
1219 onChangeText: (event) => {
1220 props.onSearchQueryChange(event.nativeEvent.text);
1221 },
1222 },
1223 unstable_headerRightItems: () => nativeHeaderItems,
1224 }}
1225 />
1226 <View className="flex-1">
1227 <SwipeableScrollGateProvider enabled={swipeEnabled}>
1228 <GestureDetector gesture={sidebarScrollGesture}>
1229 <LegendList
1230 data={listItems}
1231 drawDistance={500}
1232 estimatedItemSize={64}
1233 extraData={listExtraData}
1234 getItemType={(item) => item.type}
1235 itemsAreEqual={sidebarItemsAreEqual}
1236 keyExtractor={(item) => item.key}
1237 renderItem={renderListItem}
1238 automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
1239 contentInsetAdjustmentBehavior={
1240 NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"
1242 contentContainerStyle={[
1243 styles.threadListContent,
1244 materialYouStyleLayoutActive ? { paddingHorizontal: 0 } : null,
1246 paddingBottom: Math.max(insets.bottom, 16) + 16,
1247 paddingTop: 6,
1248 },
1249 ]}
1250 keyboardDismissMode="on-drag"
1251 keyboardShouldPersistTaps="handled"
1252 {...scrollGateHandlers}
1253 recycleItems
1254 scrollEventThrottle={16}
1255 showsVerticalScrollIndicator={false}
1256 style={styles.threadList}
1257 ListEmptyComponent={listEmpty}
1258 />
1259 </GestureDetector>
1260 </SwipeableScrollGateProvider>
1261 </View>
1262 </>
1263 );
1265​
1266 return (
1267 <View
1268 testID="thread-navigation-sidebar"
1269 className="flex-1 border-r border-border bg-drawer"
1270 style={{ width: props.width }}
1272 <View
1273 className="flex-1"
1274 style={
1275 materialYouStyleLayoutActive
1276 ? {
1277 marginTop: stickyHeaderHeight,
1278 paddingBottom: insets.bottom,
1279 backgroundColor: screenColor,
1280 borderTopLeftRadius: 28,
1281 borderTopRightRadius: 28,
1282 overflow: "hidden",
1284 : { paddingBottom: insets.bottom }
1287 <SwipeableScrollGateProvider enabled={swipeEnabled}>
1288 <GestureDetector gesture={sidebarScrollGesture}>
1289 <LegendList
1290 data={listItems}
1291 drawDistance={500}
1292 estimatedItemSize={64}
1293 extraData={listExtraData}
1294 getItemType={(item) => item.type}
1295 itemsAreEqual={sidebarItemsAreEqual}
1296 keyExtractor={(item) => item.key}
1297 renderItem={renderListItem}
1298 contentContainerStyle={[
1299 styles.threadListContent,
1300 materialYouStyleLayoutActive ? { paddingHorizontal: 0 } : null,
1302 paddingBottom:
1303 Platform.OS === "android"
1304 ? Math.max(insets.bottom, 16) + 88 - insets.bottom
1305 : 16 + insets.bottom,
1306 paddingTop: materialYouStyleLayoutActive ? 6 : topListInset,
1307 },
1308 ]}
1309 keyboardDismissMode="on-drag"
1310 keyboardShouldPersistTaps="handled"
1311 {...scrollGateHandlers}
1312 recycleItems
1313 scrollEventThrottle={16}
1314 showsVerticalScrollIndicator={false}
1315 style={styles.threadList}
1316 ListEmptyComponent={listEmpty}
1317 />
1318 </GestureDetector>
1319 </SwipeableScrollGateProvider>
1320 </View>
1321​
1322 <View
1323 className="absolute inset-x-0 top-0 z-[4] bg-drawer"
1324 collapsable={false}
1325 onLayout={handleStickyHeaderLayout}
1326 pointerEvents="auto"
1327 style={{ paddingTop: insets.top }}
1329 <View className="h-[50px] flex-row items-end gap-0.5 pr-2 pl-5">
1330 {/* Title slot doubles as the connection status surface: while an
1331 environment reconnects, the brand fades to a status label in
1332 place (no layout shift in the list below). */}
1333 <WorkspaceConnectionTitle
1334 grow
1335 onPress={props.onOpenEnvironmentSettings}
1336 size="pageTitle"
1337 brand={
1338 <View className="h-11 flex-1 justify-center">
1339 <CompactBrandTitle allowFontScaling={false} />
1340 </View>
1342 />
1343 <View className="flex-row items-center gap-2.5">
1344 <ControlPillMenu actions={listMenuActions} onPressAction={handleListMenuAction}>
1345 <SidebarFilterButton accessibilityLabel="Filter and sort threads" icon={filterIcon} />
1346 </ControlPillMenu>
1347 <SidebarHeaderActions onOpenSettings={props.onOpenSettings} />
1348 </View>
1349 </View>
1350​
1351 <View
1352 className={
1353 materialYouStyleLayoutActive
1354 ? "mx-4 mt-[9px] min-h-12 flex-row items-center gap-2.5 rounded-full border border-input-border bg-input px-3.5"
1355 : "mx-4 mt-[9px] h-[38px] flex-row items-center gap-1.5 rounded-xl bg-sidebar-search pr-2.5 pl-[11px]"
1358 <SymbolView
1359 name="magnifyingglass"
1360 size={15}
1361 tintColorClassName={"accent-foreground-muted"}
1362 type="monochrome"
1363 />
1364 <TextInput
1365 ref={searchInputRef}
1366 accessibilityLabel="Search threads"
1367 autoCapitalize="none"
1368 autoCorrect={false}
1369 clearButtonMode={materialYouStyleLayoutActive ? "never" : "while-editing"}
1370 onChangeText={props.onSearchQueryChange}
1371 placeholder="Search"
1372 placeholderTextColorClassName={"accent-placeholder"}
1373 returnKeyType="search"
1374 className={
1375 materialYouStyleLayoutActive
1376 ? "flex-1 px-0 py-2.5 font-sans text-base text-foreground"
1377 : "h-[34px] flex-1 px-0 py-0 font-sans text-base text-foreground"
1379 value={props.searchQuery}
1380 />
1381 {materialYouStyleLayoutActive && props.searchQuery.length > 0 ? (
1382 <Pressable
1383 accessibilityLabel="Clear search"
1384 hitSlop={10}
1385 onPress={() => props.onSearchQueryChange("")}
1387 <SymbolView
1388 name="xmark.circle.fill"
1389 size={17}
1390 tintColor={mutedColor}
1391 type="monochrome"
1392 />
1393 </Pressable>
1394 ) : null}
1395 </View>
1396 </View>
1397 </View>
1398 );
1400​
1401const styles = StyleSheet.create({
1402 threadList: {
1403 flex: 1,
1404 },
1405 threadListContent: {
1406 paddingHorizontal: 8,
1407 },
1408});