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