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

ThreadNavigationSidebar.tsx

1,074 lines41.2 KB

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