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