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 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 serverConfigs = useAtomValue(environmentServerConfigsAtom);
310 const settlementEnvironmentIds = useMemo(() => {
311 const supported = new Set<EnvironmentId>();
312 for (const [environmentId, config] of serverConfigs) {
313 if (config.environment.capabilities.threadSettlement === true) {
314 supported.add(environmentId);
315 }
316 }
317 return supported;
318 }, [serverConfigs]);
319 const snoozeEnvironmentIds = useMemo(() => {
320 const supported = new Set<EnvironmentId>();
321 for (const [environmentId, config] of serverConfigs) {
322 if (config.environment.capabilities.threadSnooze === true) {
323 supported.add(environmentId);
324 }
325 }
326 return supported;
327 }, [serverConfigs]);
328 const pinningEnvironmentIds = useMemo(() => {
329 const supported = new Set<EnvironmentId>();
330 for (const [environmentId, config] of serverConfigs) {
331 if (config.environment.capabilities.threadPinning === true) {
332 supported.add(environmentId);
333 }
334 }
335 return supported;
336 }, [serverConfigs]);
337 const pinReorderEnvironmentIds = useMemo(() => {
338 const supported = new Set<EnvironmentId>();
339 for (const [environmentId, config] of serverConfigs) {
340 if (config.environment.capabilities.threadPinReorder === true) {
341 supported.add(environmentId);
342 }
343 }
344 return supported;
345 }, [serverConfigs]);
346 const activeReorderEnvironmentIds = useMemo(() => {
347 const supported = new Set<EnvironmentId>();
348 for (const [environmentId, config] of serverConfigs) {
349 if (config.environment.capabilities.threadActiveReorder === true) {
350 supported.add(environmentId);
351 }
352 }
353 return supported;
354 }, [serverConfigs]);
355 const titleRegenerationEnvironmentIds = useMemo(() => {
356 const supported = new Set<EnvironmentId>();
357 for (const [environmentId, config] of serverConfigs) {
358 if (config.environment.capabilities.threadTitleRegeneration === true) {
359 supported.add(environmentId);
360 }
361 }
362 return supported;
363 }, [serverConfigs]);
364 const machineByEnvironmentId = useMemo(
365 () =>
366 new Map(
367 [...serverConfigs].map(
368 ([environmentId, config]) =>
369 [environmentId, resolveEnvironmentMachineKind(config)] as const,
370 ),
371 ),
372 [serverConfigs],
373 );
374 // Reference-stable provider glyphs: a fresh object per render would break
375 // the memoized rows' props comparison on every parent render.
376 const resolveProviderInstance = useThreadRowProviderInstanceResolver(serverConfigs);
377 const pendingOrder = usePendingThreadOrder(nowMinute, snoozeWakeTick);
378 // Up/down menu availability for every card, computed once per section per
379 // rebuild (see computeThreadMoveAvailability): per-thread planner calls made
380 // list construction quadratic, and this list rebuilds on every minute tick.
381 const threadMoveAvailability = useMemo(() => {
382 const sectionAvailability = (section: "pinned" | "active") =>
383 computeThreadMoveAvailability({
384 allThreads: threads,
385 section,
386 pendingOrder,
387 reorderableEnvironmentIds: new Set(
388 [...serverConfigs].flatMap(([id, config]) =>
389 (section === "pinned"
390 ? config.environment.capabilities.threadPinReorder
391 : config.environment.capabilities.threadActiveReorder) === true
392 ? [id]
393 : [],
394 ),
395 ),
396 ordered: getThreadListV2OrderedSection({
397 threads,
398 section,
399 pendingOrder,
400 now: new Date().toISOString(),
401 settlementEnvironmentIds,
402 snoozeEnvironmentIds,
403 queuedThreadKeys,
404 }),
405 });
406 return new Map([...sectionAvailability("pinned"), ...sectionAvailability("active")]);
407 }, [
408 serverConfigs,
409 threads,
410 pendingOrder,
411 queuedThreadKeys,
412 settlementEnvironmentIds,
413 snoozeEnvironmentIds,
414 nowMinute,
415 snoozeWakeTick,
416 ]);
417 const threadListV2Layout = useMemo(() => {
418 return buildThreadListV2Items({
419 pendingOrder,
420 threads: threads.filter((thread) => thread.archivedAt === null),
421 environmentId: options.selectedEnvironmentId,
422 projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
423 searchQuery: props.searchQuery,
424 matchedThreadKeys,
425 settlementEnvironmentIds,
426 snoozeEnvironmentIds,
427 queuedThreadKeys,
428 settledLimit: settledVisibleCount,
429 now: new Date().toISOString(),
430 snoozedShelfExpanded,
431 settledShelfExpanded,
432 selectedThreadKey: props.selectedThreadKey ?? null,
433 });
434 }, [
435 pendingOrder,
436 queuedThreadKeys,
437 nowMinute,
438 snoozeWakeTick,
439 snoozedShelfExpanded,
440 settledShelfExpanded,
441 props.selectedThreadKey,
442 options.selectedEnvironmentId,
443 props.searchQuery,
444 matchedThreadKeys,
445 settledVisibleCount,
446 settlementEnvironmentIds,
447 snoozeEnvironmentIds,
448 threads,
449 selectedProjectScope,
450 ]);
451 // Re-partition the moment the earliest snooze expires (clamped to the
452 // signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
453 const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
454 useEffect(() => {
455 if (nextSnoozeWakeAt === null) return;
456 const wakeAtMs = Date.parse(nextSnoozeWakeAt);
457 if (Number.isNaN(wakeAtMs)) return;
458 const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
459 const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
460 return () => clearTimeout(id);
461 // snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
462 // unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
463 // range) the boundary string is identical and the chain would die.
464 }, [nextSnoozeWakeAt, snoozeWakeTick]);
465 const listItems = useMemo<readonly SidebarListItem[]>(() => {
466 // Queued offline tasks are not thread shells, so the v2 item builder
467 // never sees them; the shared splice puts them below the active block
468 // (mirrors the compact Home v2 list) where they stay visible and
469 // deletable while their environment is offline. Same environment scope
470 // and search filter as the list.
471 const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
472 const v2PendingTasks = pendingTasks.filter(
473 (pendingTask) =>
474 (options.selectedEnvironmentId === null ||
475 pendingTask.environmentId === options.selectedEnvironmentId) &&
476 (selectedProjectRefs === null ||
477 selectedProjectRefs.has(
478 scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),
479 )) &&
480 (v2SearchQuery.length === 0 ||
481 pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
482 );
483 const items: SidebarListItem[] = buildThreadListV2ListItems({
484 items: threadListV2Layout.items,
485 pendingTasks: v2PendingTasks,
486 snoozedCount: threadListV2Layout.snoozedCount,
487 snoozedShelfExpanded,
488 snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
489 settledCount: threadListV2Layout.settledCount,
490 settledShelfExpanded,
491 settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
492 snoozeLabelNow: `${nowMinute}:00.000Z`,
493 snoozeEnvironmentIds,
494 queuedThreadKeys,
495 moveAvailability: threadMoveAvailability,
496 shelfPreferencesLoading: !shelfPreferencesLoaded,
497 });
498 if (settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0) {
499 items.push({
500 type: "v2-show-more",
501 key: "v2-show-more",
502 hiddenCount: threadListV2Layout.hiddenSettledCount,
503 });
504 }
505 return items;
506 }, [
507 nowMinute,
508 options.selectedEnvironmentId,
509 pendingTasks,
510 props.searchQuery,
511 queuedThreadKeys,
512 threadMoveAvailability,
513 selectedProjectRefs,
514 settledShelfExpanded,
515 shelfPreferencesLoaded,
516 snoozedShelfExpanded,
517 snoozeEnvironmentIds,
518 threadListV2Layout,
519 ]);
520 const listMenuActions = useMemo<MenuAction[]>(
521 () => [
522 {
523 id: "environment",
524 title: "Environment",
525 subactions: [
526 {
527 id: "environment:all",
528 title: "All environments",
529 subtitle: "Show threads from every environment",
530 state: options.selectedEnvironmentId === null ? "on" : "off",
531 },
532 ...environments.map((environment) => ({
533 id: `environment:${environment.environmentId}`,
534 title: environment.label,
535 state:
536 options.selectedEnvironmentId === environment.environmentId
537 ? ("on" as const)
538 : ("off" as const),
539 })),
540 ],
541 },
542 ...(projectFilterOptions.length === 0
543 ? []
544 : ([
545 {
546 id: "project",
547 title: "Project",
548 subactions: [
549 {
550 id: "project:all",
551 title: "All projects",
552 subtitle: "Show threads from every project",
553 state: selectedProjectKey === null ? "on" : "off",
554 },
555 ...projectFilterOptions.map((project) => ({
556 id: `project:${project.key}`,
557 title: project.label,
558 state: selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
559 })),
560 ],
561 },
562 ] satisfies MenuAction[])),
563 ],
564 [environments, options, projectFilterOptions, selectedProjectKey],
565 );
566 const handleListMenuAction = useCallback(
567 ({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
568 const event = nativeEvent.event;
569 if (event === "environment:all") {
570 setSelectedEnvironmentId(null);
571 return;
572 }
573 if (event.startsWith("environment:")) {
574 const environment = environments.find(
575 (candidate) => String(candidate.environmentId) === event.slice("environment:".length),
576 );
577 if (environment) setSelectedEnvironmentId(environment.environmentId);
578 return;
579 }
580 if (event === "project:all") {
581 setSelectedProjectKey(null);
582 return;
583 }
584 if (event.startsWith("project:")) {
585 const projectKey = event.slice("project:".length);
586 if (projectFilterOptions.some((project) => project.key === projectKey)) {
587 setSelectedProjectKey(projectKey);
588 }
589 return;
590 }
591 },
592 [environments, projectFilterOptions, setSelectedEnvironmentId],
593 );
594
595 const [measuredHeaderHeight, setMeasuredHeaderHeight] = useState<number | null>(null);
596 const materialToolbarHeight = useMaterialToolbarHeight();
597 // The sticky header (title row, search field, optional connection status)
598 // is measured so the list inset always matches its real height — no
599 // hardcoded per-variant constants.
600 const stickyHeaderHeight =
601 measuredHeaderHeight ??
602 (Platform.OS === "android"
603 ? Math.max(insets.top, 12) + materialToolbarHeight + 8
604 : insets.top + SIDEBAR_STICKY_HEADER_HEIGHT);
605 const topListInset = stickyHeaderHeight + 6;
606 const handleStickyHeaderLayout = useCallback((event: LayoutChangeEvent) => {
607 const nextHeight = event.nativeEvent.layout.height;
608 setMeasuredHeaderHeight((current) => (current === nextHeight ? current : nextHeight));
609 }, []);
610 const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
611 if (openSwipeableRef.current !== methods) {
612 openSwipeableRef.current?.close();
613 openSwipeableRef.current = methods;
614 }
615 }, []);
616 const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
617 if (openSwipeableRef.current === methods) {
618 openSwipeableRef.current = null;
619 }
620 }, []);
621 const handleSelectThread = useCallback(
622 (thread: EnvironmentThreadShell) => {
623 props.onSelectThread(thread);
624 openSwipeableRef.current?.close();
625 },
626 [props.onSelectThread],
627 );
628 const handleScrollBeginDrag = useCallback(() => {
629 openSwipeableRef.current?.close();
630 }, []);
631 const onMaterialFabScroll = useMaterialFabScroll();
632 const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
633 onScroll: onMaterialFabScroll,
634 onScrollBeginDrag: handleScrollBeginDrag,
635 });
636 // The sticky header's project shells and search maps feed row props, so
637 // they have to bust the recycler's memoization — otherwise a row keeps the
638 // blank favicon and fallback title it was first rendered with. The minute
639 // clock deliberately stays out: its per-row text lives on the items, so a
640 // tick only re-renders rows whose displayed text actually moved.
641 const listExtraData = useMemo(
642 () => ({
643 selectedThreadKey: props.selectedThreadKey ?? "",
644 projectByKey,
645 projectTitleByProjectKey,
646 savedConnectionsById,
647 serverConfigs,
648 threadSearchMatchByKey,
649 }),
650 [
651 props.selectedThreadKey,
652 projectByKey,
653 projectTitleByProjectKey,
654 savedConnectionsById,
655 serverConfigs,
656 threadSearchMatchByKey,
657 ],
658 );
659 useThreadJumpShortcuts(listItems, handleSelectThread);
660 const sidebarItemsAreEqual = useCallback(
661 (previous: SidebarListItem, item: SidebarListItem): boolean => {
662 if (isThreadListV2ListItem(previous) && isThreadListV2ListItem(item)) {
663 return threadListV2ListItemsAreEqual(previous, item);
664 }
665 if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
666 return previous.hiddenCount === item.hiddenCount;
667 }
668 return false;
669 },
670 [],
671 );
672 const focusSearch = useCallback(() => {
673 if (Platform.OS === "android") return false;
674 const focus = () => {
675 if (props.nativeChrome) {
676 searchBarRef.current?.focus();
677 return;
678 }
679 searchInputRef.current?.focus();
680 };
681 if (!props.visible) {
682 props.onRequestVisibility();
683 setTimeout(focus, 240);
684 } else {
685 focus();
686 }
687 return true;
688 }, [props.nativeChrome, props.onRequestVisibility, props.visible]);
689 useHardwareKeyboardCommand("focusSearch", focusSearch);
690 const renderListItem = useCallback(
691 ({ item }: { readonly item: SidebarListItem }) => {
692 switch (item.type) {
693 case "v2-pending": {
694 const pendingScopeKey = scopedProjectKey(
695 item.pendingTask.environmentId,
696 item.pendingTask.projectId,
697 );
698 return (
699 <ThreadListV2PendingRow
700 pendingTask={item.pendingTask}
701 project={projectByKey.get(pendingScopeKey) ?? null}
702 projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}
703 environmentLabel={
704 Object.keys(savedConnectionsById).length > 1
705 ? (savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? null)
706 : null
707 }
708 environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
709 pane="sidebar"
710 showPendingDivider={item.showPendingDivider}
711 onSelectPendingTask={openPendingTask}
712 onDeletePendingTask={confirmDeletePendingTask}
713 />
714 );
715 }
716 case "v2-thread": {
717 const thread = item.item.thread;
718 const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId);
719 // Intentional difference from Home: the sidebar never passes
720 // `showTrailingDivider` because its rows render no Home-style row
721 // hairline at all — card rows carry tonal containers in this pane
722 // (the hairline branch is !sidebarPane-only) and slim rows have no
723 // hairline branch. The stamp still rides the shared list items
724 // because Home's boundary suppression consumes it; the sidebar's
725 // only cost is the occasional divider-only equality invalidation,
726 // which re-renders identically.
727 return (
728 <ThreadListV2Row
729 onNewThreadOnBranch={props.onNewThreadOnBranch}
730 thread={thread}
731 variant={item.item.variant}
732 hasQueuedMessages={item.hasQueuedMessages}
733 snoozed={item.item.snoozed}
734 pinned={item.item.pinned}
735 snoozePresetMinute={item.snoozePresetMinute ?? ""}
736 snoozeWakeLabelText={item.snoozeWakeLabelText}
737 timeLabel={item.timeLabel}
738 project={projectByKey.get(scopeKey) ?? null}
739 projectTitle={projectTitleByProjectKey.get(scopeKey)}
740 providerInstance={resolveProviderInstance(thread)}
741 environmentLabel={
742 Object.keys(savedConnectionsById).length > 1
743 ? (savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
744 : null
745 }
746 environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
747 searchMatch={threadSearchMatchByKey.get(
748 threadSearchMatchKey({
749 environmentId: thread.environmentId,
750 threadId: thread.id,
751 }),
752 )}
753 searchQuery={props.searchQuery}
754 pane="sidebar"
755 selected={
756 scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
757 }
758 fullSwipeWidth={props.width - 20}
759 onSelectThread={handleSelectThread}
760 onDeleteThread={confirmDeleteThread}
761 onArchiveThread={archiveThread}
762 onRenameThread={renameThread}
763 onRegenerateThreadTitle={regenerateThreadTitle}
764 titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
765 settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
766 onSettleThread={settleThread}
767 snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
768 pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
769 reorderSupported={
770 item.item.pinned
771 ? pinReorderEnvironmentIds.has(thread.environmentId)
772 : activeReorderEnvironmentIds.has(thread.environmentId)
773 }
774 canMoveUp={item.canMoveUp}
775 canMoveDown={item.canMoveDown}
776 onSnoozeThread={snoozeThread}
777 onUnsnoozeThread={unsnoozeThread}
778 onUnsettleThread={unsettleThread}
779 onPinThread={pinThread}
780 onUnpinThread={unpinThread}
781 onMoveThread={moveThread}
782 onSwipeableClose={handleSwipeableClose}
783 onSwipeableWillOpen={handleSwipeableWillOpen}
784 simultaneousSwipeGesture={sidebarScrollGesture}
785 />
786 );
787 }
788 case "v2-snoozed-shelf":
789 return (
790 <ThreadListV2SnoozedShelfHeader
791 count={item.count}
792 disabled={item.disabled}
793 expanded={item.expanded}
794 onToggle={toggleSnoozedShelf}
795 pane="sidebar"
796 />
797 );
798 case "v2-settled-shelf":
799 return (
800 <ThreadListV2SettledShelfHeader
801 count={item.count}
802 disabled={item.disabled}
803 expanded={item.expanded}
804 onToggle={toggleSettledShelf}
805 pane="sidebar"
806 />
807 );
808 case "v2-show-more":
809 return (
810 <ThreadListV2ShowMoreRow
811 pane="sidebar"
812 hiddenCount={item.hiddenCount}
813 onPress={showMoreSettled}
814 />
815 );
816 }
817 },
818 [
819 archiveThread,
820 activeReorderEnvironmentIds,
821 confirmDeletePendingTask,
822 confirmDeleteThread,
823 handleSelectThread,
824 handleSwipeableClose,
825 handleSwipeableWillOpen,
826 machineByEnvironmentId,
827 moveThread,
828 openPendingTask,
829 pinReorderEnvironmentIds,
830 pinThread,
831 pinningEnvironmentIds,
832 projectByKey,
833 projectTitleByProjectKey,
834 regenerateThreadTitle,
835 renameThread,
836 threadSearchMatchByKey,
837 props.onNewThreadInProject,
838 props.onNewThreadOnBranch,
839 props.searchQuery,
840 props.selectedThreadKey,
841 props.width,
842 savedConnectionsById,
843 titleRegenerationEnvironmentIds,
844 settleThread,
845 settlementEnvironmentIds,
846 showMoreSettled,
847 sidebarScrollGesture,
848 snoozeEnvironmentIds,
849 snoozeThread,
850 resolveProviderInstance,
851 toggleSettledShelf,
852 toggleSnoozedShelf,
853 unpinThread,
854 unsettleThread,
855 unsnoozeThread,
856 ],
857 );
858 // The list ignores sort/group options, so only the environment and project
859 // filters can light the "customized" state.
860 const filterCustomized = options.selectedEnvironmentId !== null || selectedProjectKey !== null;
861 const filterIcon = filterCustomized
862 ? "line.3.horizontal.decrease.circle.fill"
863 : "line.3.horizontal.decrease.circle";
864 const filterMenu = useMemo(
865 () =>
866 buildHomeListFilterMenu({
867 environments,
868 projects: projectFilterOptions,
869 selectedEnvironmentId: options.selectedEnvironmentId,
870 selectedProjectKey,
871 onEnvironmentChange: setSelectedEnvironmentId,
872 onProjectChange: setSelectedProjectKey,
873 }),
874 [environments, options, projectFilterOptions, selectedProjectKey, setSelectedEnvironmentId],
875 );
876 const nativeHeaderItems = useMemo(
877 () =>
878 createSidebarHeaderItems({
879 filterIcon,
880 filterMenu,
881 onOpenSettings: props.onOpenSettings,
882 }),
883 [filterIcon, filterMenu, props.onOpenSettings],
884 );
885 // Snoozed threads need no special case: the shelf header is a list row
886 // even while collapsed.
887 const listEmpty = (
888 <Text
889 className={
890 Platform.OS === "android"
891 ? "px-4 py-4 text-center text-sm text-drawer-foreground-muted"
892 : "px-2 py-4 text-sm text-drawer-foreground-muted"
893 }
894 >
895 {catalogState.isLoadingConnections
896 ? "Loading threads…"
897 : Platform.OS === "android" && !catalogState.hasConnections
898 ? "No environments connected"
899 : props.searchQuery.trim().length > 0
900 ? threadSearch.isPending
901 ? "Searching thread messages…"
902 : "No matching threads"
903 : selectedProjectScope !== null
904 ? `No threads in ${selectedProjectScope.title}`
905 : "No threads yet"}
906 </Text>
907 );
908
909 if (props.nativeChrome) {
910 return (
911 <>
912 <NativeStackScreenOptions
913 optionsVersion={[nativeHeaderItems, props.width]}
914 options={{
915 // Re-applies the shell's static brand slot with the
916 // connection-status swap so reconnects surface in the header
917 // instead of shifting the list.
918 ...getConnectionAwareBrandHeaderOptions({
919 headerWidth: props.width,
920 trailingItemCount: nativeHeaderItems.length,
921 onOpenEnvironments: props.onOpenEnvironmentSettings,
922 fallbackTitleStyle: { fontSize: 18, fontWeight: "800" },
923 }),
924 headerSearchBarOptions: {
925 ref: searchBarRef,
926 autoCapitalize: "none",
927 hideNavigationBar: false,
928 // Keep the search bar pinned under the title — UIKit's default
929 // hidesSearchBarWhenScrolling collapses it on scroll.
930 hideWhenScrolling: false,
931 obscureBackground: false,
932 placeholder: "Search",
933 placement: "stacked",
934 onCancelButtonPress: () => {
935 props.onSearchQueryChange("");
936 },
937 onChangeText: (event) => {
938 props.onSearchQueryChange(event.nativeEvent.text);
939 },
940 },
941 unstable_headerRightItems: () => nativeHeaderItems,
942 }}
943 />
944 <View className="flex-1">
945 <SwipeableScrollGateProvider enabled={swipeEnabled}>
946 <GestureDetector gesture={sidebarScrollGesture}>
947 <LegendList
948 data={listItems}
949 drawDistance={500}
950 estimatedItemSize={64}
951 extraData={listExtraData}
952 getItemType={(item) => item.type}
953 itemsAreEqual={sidebarItemsAreEqual}
954 keyExtractor={(item) => item.key}
955 renderItem={renderListItem}
956 automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
957 contentInsetAdjustmentBehavior={
958 NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"
959 }
960 contentContainerStyle={[
961 styles.threadListContent,
962 Platform.OS === "android" ? { paddingHorizontal: 0 } : null,
963 {
964 paddingBottom: Math.max(insets.bottom, 16) + 16,
965 paddingTop: 6,
966 },
967 ]}
968 keyboardDismissMode="on-drag"
969 keyboardShouldPersistTaps="handled"
970 {...scrollGateHandlers}
971 recycleItems
972 scrollEventThrottle={16}
973 showsVerticalScrollIndicator={false}
974 style={styles.threadList}
975 ListEmptyComponent={listEmpty}
976 />
977 </GestureDetector>
978 </SwipeableScrollGateProvider>
979 </View>
980 </>
981 );
982 }
983
984 return (
985 <View
986 testID="thread-navigation-sidebar"
987 className={
988 Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 border-r border-border bg-drawer"
989 }
990 style={{ width: props.width }}
991 >
992 <View
993 className="flex-1"
994 style={
995 Platform.OS === "android"
996 ? {
997 marginTop: stickyHeaderHeight,
998 marginHorizontal: 4,
999 paddingBottom: insets.bottom,
1000 backgroundColor: drawerColor,
1001 borderTopLeftRadius: 28,
1002 borderTopRightRadius: 28,
1003 overflow: "hidden",
1004 }
1005 : { paddingBottom: insets.bottom }
1006 }
1007 >
1008 {Platform.OS === "android" && listItems.length === 0 ? (
1009 <View className="flex-1 items-center justify-center">{listEmpty}</View>
1010 ) : (
1011 <SwipeableScrollGateProvider enabled={swipeEnabled}>
1012 <GestureDetector gesture={sidebarScrollGesture}>
1013 <LegendList
1014 data={listItems}
1015 drawDistance={500}
1016 estimatedItemSize={64}
1017 extraData={listExtraData}
1018 getItemType={(item) => item.type}
1019 itemsAreEqual={sidebarItemsAreEqual}
1020 keyExtractor={(item) => item.key}
1021 renderItem={renderListItem}
1022 contentContainerStyle={[
1023 styles.threadListContent,
1024 Platform.OS === "android" ? { paddingHorizontal: 0 } : null,
1025 {
1026 paddingBottom:
1027 Platform.OS === "android"
1028 ? Math.max(insets.bottom, 16) + 148 - insets.bottom
1029 : 16 + insets.bottom,
1030 paddingTop: Platform.OS === "android" ? 6 : topListInset,
1031 },
1032 ]}
1033 keyboardDismissMode="on-drag"
1034 keyboardShouldPersistTaps="handled"
1035 {...scrollGateHandlers}
1036 recycleItems
1037 scrollEventThrottle={16}
1038 showsVerticalScrollIndicator={false}
1039 style={styles.threadList}
1040 ListEmptyComponent={listEmpty}
1041 />
1042 </GestureDetector>
1043 </SwipeableScrollGateProvider>
1044 )}
1045 </View>
1046
1047 {Platform.OS === "android" ? (
1048 <MaterialThreadListToolbar
1049 sidebar
1050 onLayout={handleStickyHeaderLayout}
1051 searchQuery={props.searchQuery}
1052 onSearchQueryChange={props.onSearchQueryChange}
1053 filterActions={listMenuActions}
1054 filterCustomized={filterCustomized}
1055 onFilterAction={handleListMenuAction}
1056 onOpenSettings={props.onOpenSettings}
1057 onOpenEnvironments={props.onOpenEnvironmentSettings}
1058 onRequestVisibility={props.onRequestVisibility}
1059 />
1060 ) : (
1061 <View
1062 className="absolute inset-x-0 top-0 z-[4] bg-drawer"
1063 collapsable={false}
1064 onLayout={handleStickyHeaderLayout}
1065 pointerEvents="auto"
1066 style={{ paddingTop: insets.top }}
1067 >
1068 <View className="h-[50px] flex-row items-end gap-0.5 pr-2 pl-5">
1069 {/* Title slot doubles as the connection status surface: while an
1070 environment reconnects, the brand fades to a status label in
1071 place (no layout shift in the list below). */}
1072 <WorkspaceConnectionTitle
1073 grow
1074 onPress={props.onOpenEnvironmentSettings}
1075 size="pageTitle"
1076 brand={
1077 <View className="h-11 flex-1 justify-center">
1078 <CompactBrandTitle allowFontScaling={false} />
1079 </View>
1080 }
1081 />
1082 <View className="flex-row items-center gap-2.5">
1083 <ControlPillMenu actions={listMenuActions} onPressAction={handleListMenuAction}>
1084 <SidebarFilterButton accessibilityLabel="Filter threads" icon={filterIcon} />
1085 </ControlPillMenu>
1086 <SidebarHeaderActions onOpenSettings={props.onOpenSettings} />
1087 </View>
1088 </View>
1089
1090 <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]">
1091 <SymbolView
1092 name="magnifyingglass"
1093 size={15}
1094 tintColorClassName="accent-drawer-foreground-muted"
1095 type="monochrome"
1096 />
1097 <TextInput
1098 ref={searchInputRef}
1099 accessibilityLabel="Search threads"
1100 autoCapitalize="none"
1101 autoCorrect={false}
1102 clearButtonMode="while-editing"
1103 onChangeText={props.onSearchQueryChange}
1104 placeholder="Search"
1105 placeholderTextColorClassName="accent-placeholder"
1106 selectionColorClassName={undefined}
1107 cursorColorClassName={undefined}
1108 selectionHandleColorClassName={undefined}
1109 returnKeyType="search"
1110 className="h-[34px] flex-1 px-0 py-0 font-sans text-base text-drawer-foreground"
1111 value={props.searchQuery}
1112 />
1113 </View>
1114 </View>
1115 )}
1116 </View>
1117 );
1118}
1119
1120const styles = StyleSheet.create({
1121 threadList: {
1122 flex: 1,
1123 },
1124 threadListContent: {
1125 paddingHorizontal: 8,
1126 },
1127});