Open History to see the last commit
1import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
2import { computeThreadMoveAvailability } from "./threadOrder";
3import type {
4 EnvironmentProject,
5 EnvironmentThreadShell,
6} from "@t3tools/client-runtime/state/shell";
7import {
8 threadSearchMatchKey,
9 type EnvironmentThreadSearchMatch,
10} from "@t3tools/client-runtime/state/thread-search";
11import { LegendList } from "@legendapp/list/react-native";
12import type { MenuAction } from "@react-native-menu/menu";
13import { useAtomValue } from "@effect/atom-react";
14import { useCallback, useEffect, useMemo, useRef, useState } from "react";
15import type { LayoutChangeEvent } from "react-native";
16import { Platform, StyleSheet, TextInput, View } from "react-native";
17import { Gesture, GestureDetector } from "react-native-gesture-handler";
18import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
19import { useSafeAreaInsets } from "react-native-safe-area-context";
20import type { SearchBarCommands } from "react-native-screens";
21
22import { AppText as Text } from "../../components/AppText";
23import { CompactBrandTitle } from "../../components/CompactBrandTitle";
24import { ControlPillMenu } from "../../components/ControlPill";
25import { SymbolView } from "../../components/AppSymbol";
26import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
27import { NativeStackScreenOptions } from "../../native/StackHeader";
28import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
29import { useProjects, useNavigationThreadShells } from "../../state/entities";
30import { useThreadSearch } from "../../state/queries";
31import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences";
32import { usePendingThreadOrder } from "../../state/thread-order";
33import { threadListEnvironmentsAtom } from "../../state/server";
34import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
35import { useQueuedThreadKeys } from "../../state/use-thread-outbox";
36import { useWorkspaceState } from "../../state/workspace";
37import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
38import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
39import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts";
40import { useHomeListOptions } from "../home/home-list-options";
41import { buildHomeListFilterMenu } from "../home/home-list-filter-menu";
42import { buildHomeProjectScopes } from "../home/homeThreadList";
43import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
44import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
45import { useThreadListActions } from "../home/useThreadListActions";
46import {
47 getConnectionAwareBrandHeaderOptions,
48 WorkspaceConnectionTitle,
49} from "../home/WorkspaceConnectionTitle";
50import { SidebarHeaderActions } from "./sidebar-header-actions";
51import { MaterialThreadListToolbar } from "../home/MaterialThreadListToolbar";
52import { useMaterialToolbarHeight } from "../../components/useMaterialToolbarHeight";
53import { useMaterialFabScroll } from "../home/MaterialFabScrollContext";
54import { SidebarFilterButton } from "./sidebar-filter-button";
55import { createSidebarHeaderItems } from "./sidebar-native-header-items";
56import { SidebarNavigationShell } from "./sidebar-navigation-shell";
57import {
58 ThreadListV2PendingRow,
59 ThreadListV2Row,
60 ThreadListV2SettledShelfHeader,
61 ThreadListV2ShowMoreRow,
62 ThreadListV2SnoozedShelfHeader,
63} from "./thread-list-v2-items";
64import { useThreadRowProviderInstanceResolver } from "./thread-provider-instance";
65import {
66 buildThreadListV2Items,
67 getThreadListV2OrderedSection,
68 buildThreadListV2ListItems,
69 isThreadListV2ListItem,
70 threadListV2ListItemsAreEqual,
71 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
72 THREAD_LIST_V2_SETTLED_PAGE_COUNT,
73 type ThreadListV2ListItem,
74} from "./threadListV2";
75
76/** The sidebar list: flat v2 rows with queued tasks spliced in, plus a
77 settled "Show more" pager row. */
78type SidebarListItem =
79 | ThreadListV2ListItem
80 | { readonly type: "v2-show-more"; readonly key: string; readonly hiddenCount: number };
81
82const SIDEBAR_STICKY_HEADER_HEIGHT = 106;
83
84interface ThreadNavigationSidebarProps {
85 readonly width: number;
86 readonly visible: boolean;
87 readonly selectedThreadKey: string | null;
88 readonly onOpenSettings: () => void;
89 readonly onOpenEnvironmentSettings: () => void;
90 readonly onNewThreadOnBranch: (thread: EnvironmentThreadShell) => void;
91 readonly onNewThreadInProject: (project: EnvironmentProject) => void;
92 readonly onSearchQueryChange: (query: string) => void;
93 readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
94 readonly onRequestVisibility: () => void;
95 readonly searchQuery: string;
96}
97
98/**
99 * iPad/large-width sidebar column.
100 *
101 * On iOS the pane is hosted inside its own navigation-inert single-screen
102 * native stack (SidebarNavigationShell) so the header is a real
103 * UINavigationBar: large title, native bar-button items, and a
104 * UISearchController search field — the same chrome a UISplitViewController
105 * column gets. Other platforms keep the custom header chrome.
106 */
107export function ThreadNavigationSidebar(props: ThreadNavigationSidebarProps) {
108 if (Platform.OS !== "ios") {
109 return <ThreadNavigationSidebarPane {...props} nativeChrome={false} />;
110 }
111 return <NativeSidebarContainer {...props} />;
112}
113
114function NativeSidebarContainer(props: ThreadNavigationSidebarProps) {
115 return (
116 <View
117 testID="thread-navigation-sidebar"
118 className="flex-1 border-border bg-drawer"
119 style={{ borderRightWidth: StyleSheet.hairlineWidth, width: props.width }}
120 >
121 <SidebarNavigationShell>
122 <ThreadNavigationSidebarPane {...props} nativeChrome />
123 </SidebarNavigationShell>
124 </View>
125 );
126}
127
128function ThreadNavigationSidebarPane(
129 props: ThreadNavigationSidebarProps & { readonly nativeChrome: boolean },
130) {
131 const { themeVariables: materialTheme } = useAppearancePreferences();
132 const drawerColor = materialTheme["--color-drawer"];
133
134 const insets = useSafeAreaInsets();
135 const projects = useProjects();
136 const threads = useNavigationThreadShells();
137 const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
138 const { savedConnectionsById } = useSavedRemoteConnections();
139 const searchInputRef = useRef<TextInput>(null);
140 const searchBarRef = useRef<SearchBarCommands>(null);
141 const openSwipeableRef = useRef<SwipeableMethods | null>(null);
142 const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
143 const {
144 archiveThread,
145 confirmDeleteThread,
146 settleThread,
147 snoozeThread,
148 unsnoozeThread,
149 unsettleThread,
150 pinThread,
151 unpinThread,
152 setThreadAutoSettle,
153 moveThread,
154 renameThread,
155 regenerateThreadTitle,
156 } = useThreadListActions();
157 const pendingTasks = usePendingNewTasks();
158 const queuedThreadKeys = useQueuedThreadKeys();
159 const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
160 const environments = useMemo(
161 () =>
162 Object.values(savedConnectionsById)
163 .map((connection) => ({
164 environmentId: connection.environmentId,
165 label: connection.environmentLabel,
166 }))
167 .sort((left, right) => left.label.localeCompare(right.label)),
168 [savedConnectionsById],
169 );
170 const availableEnvironmentIds = useMemo(
171 () => new Set(environments.map((environment) => environment.environmentId)),
172 [environments],
173 );
174 const { options, setSelectedEnvironmentId } = useHomeListOptions(availableEnvironmentIds);
175 const searchEnvironmentIds = useMemo(
176 () =>
177 options.selectedEnvironmentId === null
178 ? workspaceEnvironments
179 .filter((environment) => environment.connectionState === "connected")
180 .map((environment) => environment.environmentId)
181 : workspaceEnvironments.some(
182 (environment) =>
183 environment.environmentId === options.selectedEnvironmentId &&
184 environment.connectionState === "connected",
185 )
186 ? [options.selectedEnvironmentId]
187 : [],
188 [options.selectedEnvironmentId, workspaceEnvironments],
189 );
190 const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery);
191 const threadSearchMatchByKey = useMemo(() => {
192 const matches = new Map<string, EnvironmentThreadSearchMatch>();
193 for (const match of threadSearch.matches) {
194 if (match.source === "user" || match.source === "assistant") {
195 matches.set(threadSearchMatchKey(match), match);
196 }
197 }
198 return matches;
199 }, [threadSearch.matches]);
200 const matchedThreadKeys = useMemo(
201 () => new Set(threadSearch.matches.map(threadSearchMatchKey)),
202 [threadSearch.matches],
203 );
204 const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
205 const projectScopes = useMemo(
206 () =>
207 buildHomeProjectScopes({
208 projects,
209 environmentId: options.selectedEnvironmentId,
210 projectGroupingMode: options.projectGroupingMode,
211 }),
212 [options.projectGroupingMode, options.selectedEnvironmentId, projects],
213 );
214 const projectFilterOptions = useMemo(
215 () =>
216 projectScopes.map((scope) => ({
217 key: scope.key,
218 label: scope.title,
219 })),
220 [projectScopes],
221 );
222 const projectTitleByProjectKey = useMemo(
223 () =>
224 new Map(
225 projectScopes.flatMap((scope) =>
226 scope.projectRefs.map(
227 (projectRef) =>
228 [
229 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
230 scope.title,
231 ] as const,
232 ),
233 ),
234 ),
235 [projectScopes],
236 );
237 const selectedProjectScope = useMemo(
238 () =>
239 selectedProjectKey === null
240 ? null
241 : (projectScopes.find((scope) => scope.key === selectedProjectKey) ?? null),
242 [projectScopes, selectedProjectKey],
243 );
244 useEffect(() => {
245 if (
246 selectedProjectKey !== null &&
247 !projectFilterOptions.some((project) => project.key === selectedProjectKey)
248 ) {
249 setSelectedProjectKey(null);
250 }
251 }, [projectFilterOptions, selectedProjectKey]);
252 const selectedProjectRefs = useMemo(
253 () =>
254 selectedProjectScope === null
255 ? null
256 : new Set(
257 selectedProjectScope.projectRefs.map((projectRef) =>
258 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
259 ),
260 ),
261 [selectedProjectScope],
262 );
263 const projectByKey = useMemo(() => {
264 const map = new Map<string, EnvironmentProject>();
265 for (const project of projects) {
266 map.set(scopedProjectKey(project.environmentId, project.id), project);
267 }
268 return map;
269 }, [projects]);
270
271 // Thread List v2 (beta) support — same model as the compact Home list
272 // (HomeScreen.tsx): flat creation-order card block + settled recency tail.
273 // The settled tail renders in pages; expansion resets when the filter
274 // context changes so environment/search flips never inherit a deep page.
275 const [settledVisibleCount, setSettledVisibleCount] = useState(
276 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
277 );
278 const settledResetKey = `${options.selectedEnvironmentId ?? "all"}:${selectedProjectKey ?? "all"}:${props.searchQuery.trim()}`;
279 const lastSettledResetKeyRef = useRef(settledResetKey);
280 if (lastSettledResetKeyRef.current !== settledResetKey) {
281 lastSettledResetKeyRef.current = settledResetKey;
282 setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
283 }
284 const showMoreSettled = useCallback(
285 () => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
286 [],
287 );
288 const {
289 loaded: shelfPreferencesLoaded,
290 settledShelfExpanded,
291 snoozedShelfExpanded,
292 toggleSettledShelf,
293 toggleSnoozedShelf,
294 } = useThreadListV2ShelfPreferences();
295 // The queued-start and snooze helpers need a clock while the pane stays open.
296 const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
297 // Snooze wake times are second-precise; a counter bumped exactly at the
298 // next wake boundary re-runs the partition with a fresh clock so a woken
299 // thread reappears immediately instead of on the next minute tick.
300 const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
301 useEffect(() => {
302 // Refresh immediately because the mount-time value can be hours old.
303 setNowMinute(new Date().toISOString().slice(0, 16));
304 const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
305 return () => clearInterval(id);
306 }, []);
307 // Threads on servers without the settlement capability never classify as
308 // settled (the user could neither un-settle nor pin them).
309 const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
310 const {
311 providersByEnvironmentId,
312 machineByEnvironmentId,
313 settlementEnvironmentIds,
314 snoozeEnvironmentIds,
315 pinningEnvironmentIds,
316 autoSettleOptOutEnvironmentIds,
317 pinReorderEnvironmentIds,
318 activeReorderEnvironmentIds,
319 titleRegenerationEnvironmentIds,
320 } = listEnvironments;
321 const resolveProviderInstance = useThreadRowProviderInstanceResolver(providersByEnvironmentId);
322 const pendingOrder = usePendingThreadOrder(nowMinute, snoozeWakeTick);
323 // Up/down menu availability for every card, computed once per section per
324 // rebuild (see computeThreadMoveAvailability): per-thread planner calls made
325 // list construction quadratic, and this list rebuilds on every minute tick.
326 const threadMoveAvailability = useMemo(() => {
327 const sectionAvailability = (section: "pinned" | "active") =>
328 computeThreadMoveAvailability({
329 allThreads: threads,
330 section,
331 pendingOrder,
332 reorderableEnvironmentIds:
333 section === "pinned" ? pinReorderEnvironmentIds : activeReorderEnvironmentIds,
334 ordered: getThreadListV2OrderedSection({
335 threads,
336 section,
337 pendingOrder,
338 now: new Date().toISOString(),
339 settlementEnvironmentIds,
340 snoozeEnvironmentIds,
341 queuedThreadKeys,
342 }),
343 });
344 return new Map([...sectionAvailability("pinned"), ...sectionAvailability("active")]);
345 }, [
346 pinReorderEnvironmentIds,
347 activeReorderEnvironmentIds,
348 threads,
349 pendingOrder,
350 queuedThreadKeys,
351 settlementEnvironmentIds,
352 snoozeEnvironmentIds,
353 nowMinute,
354 snoozeWakeTick,
355 ]);
356 const threadListV2Layout = useMemo(() => {
357 return buildThreadListV2Items({
358 pendingOrder,
359 threads: threads.filter((thread) => thread.archivedAt === null),
360 environmentId: options.selectedEnvironmentId,
361 projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
362 searchQuery: props.searchQuery,
363 matchedThreadKeys,
364 settlementEnvironmentIds,
365 snoozeEnvironmentIds,
366 queuedThreadKeys,
367 settledLimit: settledVisibleCount,
368 now: new Date().toISOString(),
369 snoozedShelfExpanded,
370 settledShelfExpanded,
371 selectedThreadKey: props.selectedThreadKey ?? null,
372 });
373 }, [
374 pendingOrder,
375 queuedThreadKeys,
376 nowMinute,
377 snoozeWakeTick,
378 snoozedShelfExpanded,
379 settledShelfExpanded,
380 props.selectedThreadKey,
381 options.selectedEnvironmentId,
382 props.searchQuery,
383 matchedThreadKeys,
384 settledVisibleCount,
385 settlementEnvironmentIds,
386 snoozeEnvironmentIds,
387 threads,
388 selectedProjectScope,
389 ]);
390 // Re-partition the moment the earliest snooze expires (clamped to the
391 // signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
392 const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
393 useEffect(() => {
394 if (nextSnoozeWakeAt === null) return;
395 const wakeAtMs = Date.parse(nextSnoozeWakeAt);
396 if (Number.isNaN(wakeAtMs)) return;
397 const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
398 const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
399 return () => clearTimeout(id);
400 // snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
401 // unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
402 // range) the boundary string is identical and the chain would die.
403 }, [nextSnoozeWakeAt, snoozeWakeTick]);
404 const listItems = useMemo<readonly SidebarListItem[]>(() => {
405 // Queued offline tasks are not thread shells, so the v2 item builder
406 // never sees them; the shared splice puts them below the active block
407 // (mirrors the compact Home v2 list) where they stay visible and
408 // deletable while their environment is offline. Same environment scope
409 // and search filter as the list.
410 const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
411 const v2PendingTasks = pendingTasks.filter(
412 (pendingTask) =>
413 (options.selectedEnvironmentId === null ||
414 pendingTask.environmentId === options.selectedEnvironmentId) &&
415 (selectedProjectRefs === null ||
416 selectedProjectRefs.has(
417 scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),
418 )) &&
419 (v2SearchQuery.length === 0 ||
420 pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
421 );
422 const items: SidebarListItem[] = buildThreadListV2ListItems({
423 items: threadListV2Layout.items,
424 pendingTasks: v2PendingTasks,
425 snoozedCount: threadListV2Layout.snoozedCount,
426 snoozedShelfExpanded,
427 snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
428 settledCount: threadListV2Layout.settledCount,
429 settledShelfExpanded,
430 settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
431 snoozeLabelNow: `${nowMinute}:00.000Z`,
432 snoozeEnvironmentIds,
433 queuedThreadKeys,
434 moveAvailability: threadMoveAvailability,
435 shelfPreferencesLoading: !shelfPreferencesLoaded,
436 });
437 if (settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0) {
438 items.push({
439 type: "v2-show-more",
440 key: "v2-show-more",
441 hiddenCount: threadListV2Layout.hiddenSettledCount,
442 });
443 }
444 return items;
445 }, [
446 nowMinute,
447 options.selectedEnvironmentId,
448 pendingTasks,
449 props.searchQuery,
450 queuedThreadKeys,
451 threadMoveAvailability,
452 selectedProjectRefs,
453 settledShelfExpanded,
454 shelfPreferencesLoaded,
455 snoozedShelfExpanded,
456 snoozeEnvironmentIds,
457 threadListV2Layout,
458 ]);
459 const listMenuActions = useMemo<MenuAction[]>(
460 () => [
461 {
462 id: "environment",
463 title: "Environment",
464 subactions: [
465 {
466 id: "environment:all",
467 title: "All environments",
468 subtitle: "Show threads from every environment",
469 state: options.selectedEnvironmentId === null ? "on" : "off",
470 },
471 ...environments.map((environment) => ({
472 id: `environment:${environment.environmentId}`,
473 title: environment.label,
474 state:
475 options.selectedEnvironmentId === environment.environmentId
476 ? ("on" as const)
477 : ("off" as const),
478 })),
479 ],
480 },
481 ...(projectFilterOptions.length === 0
482 ? []
483 : ([
484 {
485 id: "project",
486 title: "Project",
487 subactions: [
488 {
489 id: "project:all",
490 title: "All projects",
491 subtitle: "Show threads from every project",
492 state: selectedProjectKey === null ? "on" : "off",
493 },
494 ...projectFilterOptions.map((project) => ({
495 id: `project:${project.key}`,
496 title: project.label,
497 state: selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
498 })),
499 ],
500 },
501 ] satisfies MenuAction[])),
502 ],
503 [environments, options, projectFilterOptions, selectedProjectKey],
504 );
505 const handleListMenuAction = useCallback(
506 ({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
507 const event = nativeEvent.event;
508 if (event === "environment:all") {
509 setSelectedEnvironmentId(null);
510 return;
511 }
512 if (event.startsWith("environment:")) {
513 const environment = environments.find(
514 (candidate) => String(candidate.environmentId) === event.slice("environment:".length),
515 );
516 if (environment) setSelectedEnvironmentId(environment.environmentId);
517 return;
518 }
519 if (event === "project:all") {
520 setSelectedProjectKey(null);
521 return;
522 }
523 if (event.startsWith("project:")) {
524 const projectKey = event.slice("project:".length);
525 if (projectFilterOptions.some((project) => project.key === projectKey)) {
526 setSelectedProjectKey(projectKey);
527 }
528 return;
529 }
530 },
531 [environments, projectFilterOptions, setSelectedEnvironmentId],
532 );
533
534 const [measuredHeaderHeight, setMeasuredHeaderHeight] = useState<number | null>(null);
535 const materialToolbarHeight = useMaterialToolbarHeight();
536 // The sticky header (title row, search field, optional connection status)
537 // is measured so the list inset always matches its real height — no
538 // hardcoded per-variant constants.
539 const stickyHeaderHeight =
540 measuredHeaderHeight ??
541 (Platform.OS === "android"
542 ? Math.max(insets.top, 12) + materialToolbarHeight + 8
543 : insets.top + SIDEBAR_STICKY_HEADER_HEIGHT);
544 const topListInset = stickyHeaderHeight + 6;
545 const handleStickyHeaderLayout = useCallback((event: LayoutChangeEvent) => {
546 const nextHeight = event.nativeEvent.layout.height;
547 setMeasuredHeaderHeight((current) => (current === nextHeight ? current : nextHeight));
548 }, []);
549 const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
550 if (openSwipeableRef.current !== methods) {
551 openSwipeableRef.current?.close();
552 openSwipeableRef.current = methods;
553 }
554 }, []);
555 const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
556 if (openSwipeableRef.current === methods) {
557 openSwipeableRef.current = null;
558 }
559 }, []);
560 const handleSelectThread = useCallback(
561 (thread: EnvironmentThreadShell) => {
562 props.onSelectThread(thread);
563 openSwipeableRef.current?.close();
564 },
565 [props.onSelectThread],
566 );
567 const handleScrollBeginDrag = useCallback(() => {
568 openSwipeableRef.current?.close();
569 }, []);
570 const onMaterialFabScroll = useMaterialFabScroll();
571 const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
572 onScroll: onMaterialFabScroll,
573 onScrollBeginDrag: handleScrollBeginDrag,
574 });
575 // The sticky header's project shells and search maps feed row props, so
576 // they have to bust the recycler's memoization — otherwise a row keeps the
577 // blank favicon and fallback title it was first rendered with. The minute
578 // clock deliberately stays out: its per-row text lives on the items, so a
579 // tick only re-renders rows whose displayed text actually moved.
580 const listExtraData = useMemo(
581 () => ({
582 selectedThreadKey: props.selectedThreadKey ?? "",
583 projectByKey,
584 projectTitleByProjectKey,
585 savedConnectionsById,
586 listEnvironments,
587 threadSearchMatchByKey,
588 }),
589 [
590 props.selectedThreadKey,
591 projectByKey,
592 projectTitleByProjectKey,
593 savedConnectionsById,
594 listEnvironments,
595 threadSearchMatchByKey,
596 ],
597 );
598 useThreadJumpShortcuts(listItems, handleSelectThread);
599 const sidebarItemsAreEqual = useCallback(
600 (previous: SidebarListItem, item: SidebarListItem): boolean => {
601 if (isThreadListV2ListItem(previous) && isThreadListV2ListItem(item)) {
602 return threadListV2ListItemsAreEqual(previous, item);
603 }
604 if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
605 return previous.hiddenCount === item.hiddenCount;
606 }
607 return false;
608 },
609 [],
610 );
611 const focusSearch = useCallback(() => {
612 if (Platform.OS === "android") return false;
613 const focus = () => {
614 if (props.nativeChrome) {
615 searchBarRef.current?.focus();
616 return;
617 }
618 searchInputRef.current?.focus();
619 };
620 if (!props.visible) {
621 props.onRequestVisibility();
622 setTimeout(focus, 240);
623 } else {
624 focus();
625 }
626 return true;
627 }, [props.nativeChrome, props.onRequestVisibility, props.visible]);
628 useHardwareKeyboardCommand("focusSearch", focusSearch);
629 const renderListItem = useCallback(
630 ({ item }: { readonly item: SidebarListItem }) => {
631 switch (item.type) {
632 case "v2-pending": {
633 const pendingScopeKey = scopedProjectKey(
634 item.pendingTask.environmentId,
635 item.pendingTask.projectId,
636 );
637 return (
638 <ThreadListV2PendingRow
639 pendingTask={item.pendingTask}
640 project={projectByKey.get(pendingScopeKey) ?? null}
641 projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}
642 environmentLabel={
643 Object.keys(savedConnectionsById).length > 1
644 ? (savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? null)
645 : null
646 }
647 environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
648 pane="sidebar"
649 showPendingDivider={item.showPendingDivider}
650 onSelectPendingTask={openPendingTask}
651 onDeletePendingTask={confirmDeletePendingTask}
652 />
653 );
654 }
655 case "v2-thread": {
656 const thread = item.item.thread;
657 const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId);
658 // Intentional difference from Home: the sidebar never passes
659 // `showTrailingDivider` because its rows render no Home-style row
660 // hairline at all — card rows carry tonal containers in this pane
661 // (the hairline branch is !sidebarPane-only) and slim rows have no
662 // hairline branch. The stamp still rides the shared list items
663 // because Home's boundary suppression consumes it; the sidebar's
664 // only cost is the occasional divider-only equality invalidation,
665 // which re-renders identically.
666 return (
667 <ThreadListV2Row
668 onNewThreadOnBranch={props.onNewThreadOnBranch}
669 thread={thread}
670 variant={item.item.variant}
671 hasQueuedMessages={item.hasQueuedMessages}
672 snoozed={item.item.snoozed}
673 pinned={item.item.pinned}
674 snoozePresetMinute={item.snoozePresetMinute ?? ""}
675 snoozeWakeLabelText={item.snoozeWakeLabelText}
676 timeLabel={item.timeLabel}
677 project={projectByKey.get(scopeKey) ?? null}
678 projectTitle={projectTitleByProjectKey.get(scopeKey)}
679 providerInstance={resolveProviderInstance(thread)}
680 providers={providersByEnvironmentId.get(thread.environmentId)}
681 environmentLabel={
682 Object.keys(savedConnectionsById).length > 1
683 ? (savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
684 : null
685 }
686 environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
687 searchMatch={threadSearchMatchByKey.get(
688 threadSearchMatchKey({
689 environmentId: thread.environmentId,
690 threadId: thread.id,
691 }),
692 )}
693 searchQuery={props.searchQuery}
694 pane="sidebar"
695 selected={
696 scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
697 }
698 fullSwipeWidth={props.width - 20}
699 onSelectThread={handleSelectThread}
700 onDeleteThread={confirmDeleteThread}
701 onArchiveThread={archiveThread}
702 onRenameThread={renameThread}
703 onRegenerateThreadTitle={regenerateThreadTitle}
704 titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
705 settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
706 onSettleThread={settleThread}
707 snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
708 pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
709 autoSettleOptOutSupported={autoSettleOptOutEnvironmentIds.has(thread.environmentId)}
710 reorderSupported={
711 item.item.pinned
712 ? pinReorderEnvironmentIds.has(thread.environmentId)
713 : activeReorderEnvironmentIds.has(thread.environmentId)
714 }
715 canMoveUp={item.canMoveUp}
716 canMoveDown={item.canMoveDown}
717 onSnoozeThread={snoozeThread}
718 onUnsnoozeThread={unsnoozeThread}
719 onUnsettleThread={unsettleThread}
720 onPinThread={pinThread}
721 onUnpinThread={unpinThread}
722 onSetThreadAutoSettle={setThreadAutoSettle}
723 onMoveThread={moveThread}
724 onSwipeableClose={handleSwipeableClose}
725 onSwipeableWillOpen={handleSwipeableWillOpen}
726 simultaneousSwipeGesture={sidebarScrollGesture}
727 />
728 );
729 }
730 case "v2-snoozed-shelf":
731 return (
732 <ThreadListV2SnoozedShelfHeader
733 count={item.count}
734 disabled={item.disabled}
735 expanded={item.expanded}
736 onToggle={toggleSnoozedShelf}
737 pane="sidebar"
738 />
739 );
740 case "v2-settled-shelf":
741 return (
742 <ThreadListV2SettledShelfHeader
743 count={item.count}
744 disabled={item.disabled}
745 expanded={item.expanded}
746 onToggle={toggleSettledShelf}
747 pane="sidebar"
748 />
749 );
750 case "v2-show-more":
751 return (
752 <ThreadListV2ShowMoreRow
753 pane="sidebar"
754 hiddenCount={item.hiddenCount}
755 onPress={showMoreSettled}
756 />
757 );
758 }
759 },
760 [
761 archiveThread,
762 activeReorderEnvironmentIds,
763 confirmDeletePendingTask,
764 confirmDeleteThread,
765 handleSelectThread,
766 handleSwipeableClose,
767 handleSwipeableWillOpen,
768 machineByEnvironmentId,
769 moveThread,
770 openPendingTask,
771 pinReorderEnvironmentIds,
772 pinThread,
773 pinningEnvironmentIds,
774 autoSettleOptOutEnvironmentIds,
775 autoSettleOptOutEnvironmentIds,
776 setThreadAutoSettle,
777 projectByKey,
778 projectTitleByProjectKey,
779 regenerateThreadTitle,
780 renameThread,
781 props.onNewThreadOnBranch,
782 props.searchQuery,
783 props.selectedThreadKey,
784 props.width,
785 savedConnectionsById,
786 resolveProviderInstance,
787 providersByEnvironmentId,
788 threadSearchMatchByKey,
789 titleRegenerationEnvironmentIds,
790 settleThread,
791 settlementEnvironmentIds,
792 showMoreSettled,
793 sidebarScrollGesture,
794 snoozeEnvironmentIds,
795 snoozeThread,
796 toggleSettledShelf,
797 toggleSnoozedShelf,
798 unpinThread,
799 unsettleThread,
800 unsnoozeThread,
801 ],
802 );
803 // The list ignores sort/group options, so only the environment and project
804 // filters can light the "customized" state.
805 const filterCustomized = options.selectedEnvironmentId !== null || selectedProjectKey !== null;
806 const filterIcon = filterCustomized
807 ? "line.3.horizontal.decrease.circle.fill"
808 : "line.3.horizontal.decrease.circle";
809 const filterMenu = useMemo(
810 () =>
811 buildHomeListFilterMenu({
812 environments,
813 projects: projectFilterOptions,
814 selectedEnvironmentId: options.selectedEnvironmentId,
815 selectedProjectKey,
816 onEnvironmentChange: setSelectedEnvironmentId,
817 onProjectChange: setSelectedProjectKey,
818 }),
819 [environments, options, projectFilterOptions, selectedProjectKey, setSelectedEnvironmentId],
820 );
821 const nativeHeaderItems = useMemo(
822 () =>
823 createSidebarHeaderItems({
824 filterIcon,
825 filterMenu,
826 onOpenSettings: props.onOpenSettings,
827 }),
828 [filterIcon, filterMenu, props.onOpenSettings],
829 );
830 // Snoozed threads need no special case: the shelf header is a list row
831 // even while collapsed.
832 const listEmpty = (
833 <Text
834 className={
835 Platform.OS === "android"
836 ? "px-4 py-4 text-center text-sm text-drawer-foreground-muted"
837 : "px-2 py-4 text-sm text-drawer-foreground-muted"
838 }
839 >
840 {catalogState.isLoadingConnections
841 ? "Loading threads…"
842 : Platform.OS === "android" && !catalogState.hasConnections
843 ? "No environments connected"
844 : props.searchQuery.trim().length > 0
845 ? threadSearch.isPending
846 ? "Searching thread messages…"
847 : "No matching threads"
848 : selectedProjectScope !== null
849 ? `No threads in ${selectedProjectScope.title}`
850 : "No threads yet"}
851 </Text>
852 );
853
854 if (props.nativeChrome) {
855 return (
856 <>
857 <NativeStackScreenOptions
858 optionsVersion={[nativeHeaderItems, props.width]}
859 options={{
860 // Re-applies the shell's static brand slot with the
861 // connection-status swap so reconnects surface in the header
862 // instead of shifting the list.
863 ...getConnectionAwareBrandHeaderOptions({
864 headerWidth: props.width,
865 trailingItemCount: nativeHeaderItems.length,
866 onOpenEnvironments: props.onOpenEnvironmentSettings,
867 fallbackTitleStyle: { fontSize: 18, fontWeight: "800" },
868 }),
869 headerSearchBarOptions: {
870 ref: searchBarRef,
871 autoCapitalize: "none",
872 hideNavigationBar: false,
873 // Keep the search bar pinned under the title — UIKit's default
874 // hidesSearchBarWhenScrolling collapses it on scroll.
875 hideWhenScrolling: false,
876 obscureBackground: false,
877 placeholder: "Search",
878 placement: "stacked",
879 onCancelButtonPress: () => {
880 props.onSearchQueryChange("");
881 },
882 onChangeText: (event) => {
883 props.onSearchQueryChange(event.nativeEvent.text);
884 },
885 },
886 unstable_headerRightItems: () => nativeHeaderItems,
887 }}
888 />
889 <View className="flex-1">
890 <SwipeableScrollGateProvider enabled={swipeEnabled}>
891 <GestureDetector gesture={sidebarScrollGesture}>
892 <LegendList
893 data={listItems}
894 drawDistance={500}
895 estimatedItemSize={64}
896 extraData={listExtraData}
897 getItemType={(item) => item.type}
898 itemsAreEqual={sidebarItemsAreEqual}
899 keyExtractor={(item) => item.key}
900 renderItem={renderListItem}
901 automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
902 contentInsetAdjustmentBehavior={
903 NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"
904 }
905 contentContainerStyle={[
906 styles.threadListContent,
907 Platform.OS === "android" ? { paddingHorizontal: 0 } : null,
908 {
909 paddingBottom: Math.max(insets.bottom, 16) + 16,
910 paddingTop: 6,
911 },
912 ]}
913 keyboardDismissMode="on-drag"
914 keyboardShouldPersistTaps="handled"
915 {...scrollGateHandlers}
916 recycleItems
917 scrollEventThrottle={16}
918 showsVerticalScrollIndicator={false}
919 style={styles.threadList}
920 ListEmptyComponent={listEmpty}
921 />
922 </GestureDetector>
923 </SwipeableScrollGateProvider>
924 </View>
925 </>
926 );
927 }
928
929 return (
930 <View
931 testID="thread-navigation-sidebar"
932 className={
933 Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 border-r border-border bg-drawer"
934 }
935 style={{ width: props.width }}
936 >
937 <View
938 className="flex-1"
939 style={
940 Platform.OS === "android"
941 ? {
942 marginTop: stickyHeaderHeight,
943 marginHorizontal: 4,
944 paddingBottom: insets.bottom,
945 backgroundColor: drawerColor,
946 borderTopLeftRadius: 28,
947 borderTopRightRadius: 28,
948 overflow: "hidden",
949 }
950 : { paddingBottom: insets.bottom }
951 }
952 >
953 {Platform.OS === "android" && listItems.length === 0 ? (
954 <View className="flex-1 items-center justify-center">{listEmpty}</View>
955 ) : (
956 <SwipeableScrollGateProvider enabled={swipeEnabled}>
957 <GestureDetector gesture={sidebarScrollGesture}>
958 <LegendList
959 data={listItems}
960 drawDistance={500}
961 estimatedItemSize={64}
962 extraData={listExtraData}
963 getItemType={(item) => item.type}
964 itemsAreEqual={sidebarItemsAreEqual}
965 keyExtractor={(item) => item.key}
966 renderItem={renderListItem}
967 contentContainerStyle={[
968 styles.threadListContent,
969 Platform.OS === "android" ? { paddingHorizontal: 0 } : null,
970 {
971 paddingBottom:
972 Platform.OS === "android"
973 ? Math.max(insets.bottom, 16) + 148 - insets.bottom
974 : 16 + insets.bottom,
975 paddingTop: Platform.OS === "android" ? 6 : topListInset,
976 },
977 ]}
978 keyboardDismissMode="on-drag"
979 keyboardShouldPersistTaps="handled"
980 {...scrollGateHandlers}
981 recycleItems
982 scrollEventThrottle={16}
983 showsVerticalScrollIndicator={false}
984 style={styles.threadList}
985 ListEmptyComponent={listEmpty}
986 />
987 </GestureDetector>
988 </SwipeableScrollGateProvider>
989 )}
990 </View>
991
992 {Platform.OS === "android" ? (
993 <MaterialThreadListToolbar
994 sidebar
995 onLayout={handleStickyHeaderLayout}
996 searchQuery={props.searchQuery}
997 onSearchQueryChange={props.onSearchQueryChange}
998 filterActions={listMenuActions}
999 filterCustomized={filterCustomized}
1000 onFilterAction={handleListMenuAction}
1001 onOpenSettings={props.onOpenSettings}
1002 onOpenEnvironments={props.onOpenEnvironmentSettings}
1003 onRequestVisibility={props.onRequestVisibility}
1004 />
1005 ) : (
1006 <View
1007 className="absolute inset-x-0 top-0 z-[4] bg-drawer"
1008 collapsable={false}
1009 onLayout={handleStickyHeaderLayout}
1010 pointerEvents="auto"
1011 style={{ paddingTop: insets.top }}
1012 >
1013 <View className="h-[50px] flex-row items-end gap-0.5 pr-2 pl-5">
1014 {/* Title slot doubles as the connection status surface: while an
1015 environment reconnects, the brand fades to a status label in
1016 place (no layout shift in the list below). */}
1017 <WorkspaceConnectionTitle
1018 grow
1019 onPress={props.onOpenEnvironmentSettings}
1020 size="pageTitle"
1021 brand={
1022 <View className="h-11 flex-1 justify-center">
1023 <CompactBrandTitle allowFontScaling={false} />
1024 </View>
1025 }
1026 />
1027 <View className="flex-row items-center gap-2.5">
1028 <ControlPillMenu actions={listMenuActions} onPressAction={handleListMenuAction}>
1029 <SidebarFilterButton accessibilityLabel="Filter threads" icon={filterIcon} />
1030 </ControlPillMenu>
1031 <SidebarHeaderActions onOpenSettings={props.onOpenSettings} />
1032 </View>
1033 </View>
1034
1035 <View className="mx-4 mt-[9px] h-[38px] flex-row items-center gap-1.5 rounded-xl bg-sidebar-search pr-2.5 pl-[11px]">
1036 <SymbolView
1037 name="magnifyingglass"
1038 size={15}
1039 tintColorClassName="accent-drawer-foreground-muted"
1040 type="monochrome"
1041 />
1042 <TextInput
1043 ref={searchInputRef}
1044 accessibilityLabel="Search threads"
1045 autoCapitalize="none"
1046 autoCorrect={false}
1047 clearButtonMode="while-editing"
1048 onChangeText={props.onSearchQueryChange}
1049 placeholder="Search"
1050 placeholderTextColorClassName="accent-placeholder"
1051 selectionColorClassName={undefined}
1052 cursorColorClassName={undefined}
1053 selectionHandleColorClassName={undefined}
1054 returnKeyType="search"
1055 className="h-[34px] flex-1 px-0 py-0 font-sans text-base text-drawer-foreground"
1056 value={props.searchQuery}
1057 />
1058 </View>
1059 </View>
1060 )}
1061 </View>
1062 );
1063}
1064
1065const styles = StyleSheet.create({
1066 threadList: {
1067 flex: 1,
1068 },
1069 threadListContent: {
1070 paddingHorizontal: 8,
1071 },
1072});