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