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

ThreadNavigationSidebar.tsx

1,206 lines44.7 KB

1import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
2import type {
3 EnvironmentProject,
4 EnvironmentThreadShell,
5} from "@t3tools/client-runtime/state/shell";
6import { LegendList } from "@legendapp/list/react-native";
7import type { MenuAction } from "@react-native-menu/menu";
8import { useAtomValue } from "@effect/atom-react";
9import { AsyncResult } from "effect/unstable/reactivity";
10import type { EnvironmentId } from "@t3tools/contracts";
11import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
12import type { LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent } from "react-native";
13import { Platform, Pressable, StyleSheet, TextInput, View, useColorScheme } from "react-native";
14import { Gesture, GestureDetector } from "react-native-gesture-handler";
15import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
16import { useSafeAreaInsets } from "react-native-safe-area-context";
17import type { SearchBarCommands } from "react-native-screens";
18import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
19​
20import { AppText as Text } from "../../components/AppText";
21import { ControlPillMenu } from "../../components/ControlPill";
22import { SymbolView } from "../../components/AppSymbol";
23import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
24import { NativeStackScreenOptions } from "../../native/StackHeader";
25import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
26import { useThemeColor } from "../../lib/useThemeColor";
27import { useProjects, useThreadShells } from "../../state/entities";
28import { mobilePreferencesAtom } from "../../state/preferences";
29import { environmentServerConfigsAtom } from "../../state/server";
30import { usePendingNewTasks, type PendingNewTask } from "../../state/use-pending-new-tasks";
31import { useWorkspaceState } from "../../state/workspace";
32import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
33import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
34import {
35 hasCustomHomeListOptions,
36 PROJECT_SORT_OPTIONS,
37 THREAD_SORT_OPTIONS,
38 useHomeListOptions,
39} from "../home/home-list-options";
40import { buildHomeListFilterMenu } from "../home/home-list-filter-menu";
41import {
42 buildHomeListLayout,
43 DEFAULT_GROUP_DISPLAY_STATE,
44 homeListItemsAreEqual,
45 nextGroupDisplayState,
46 type HomeGroupDisplayAction,
47 type HomeGroupDisplayState,
48 type HomeListItem,
49} from "../home/homeListItems";
50import { buildHomeProjectScopes, buildHomeThreadGroups } from "../home/homeThreadList";
51import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
52import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
53import { useThreadListActions } from "../home/useThreadListActions";
54import { WorkspaceConnectionStatus } from "../home/WorkspaceConnectionStatus";
55import { shouldShowWorkspaceConnectionStatus } from "../home/workspace-connection-status";
56import { SidebarHeaderActions } from "./sidebar-header-actions";
57import { SidebarFilterButton } from "./sidebar-filter-button";
58import { createSidebarHeaderItems } from "./sidebar-native-header-items";
59import { SidebarNavigationShell } from "./sidebar-navigation-shell";
60import {
61 PendingTaskListRow,
62 ThreadListGroupHeader,
63 ThreadListRow,
64 ThreadListShowMoreRow,
65} from "./thread-list-items";
66import { ThreadListV2Row } from "./thread-list-v2-items";
67import {
68 buildThreadListV2Items,
69 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
70 THREAD_LIST_V2_SETTLED_PAGE_COUNT,
71 type ThreadListV2Item,
72} from "./threadListV2";
73​
74/** The sidebar list serves both lists: v1 grouped items or, when the Thread
75 List v2 beta is on, queued offline tasks, flat v2 rows, and a settled
76 "Show more" pager. */
77type SidebarListItem =
78 | HomeListItem
79 | {
80 readonly type: "v2-pending-task";
81 readonly key: string;
82 readonly pendingTask: PendingNewTask;
83 readonly isLast: boolean;
84 }
85 | { readonly type: "v2-thread"; readonly key: string; readonly item: ThreadListV2Item }
86 | { readonly type: "v2-show-more"; readonly key: string; readonly hiddenCount: number };
87​
88/**
89 * Shared capsule behind the sidebar header buttons — a native liquid-glass
90 * surface on iOS 26+, a tinted pill everywhere else.
91 */
92function SidebarHeaderButtonGroup(props: {
93 readonly children: ReactNode;
94 readonly colorScheme: "light" | "dark";
95}) {
96 if (isLiquidGlassSupported) {
97 return (
98 <LiquidGlassView
99 colorScheme={props.colorScheme}
100 effect="regular"
101 interactive
102 style={styles.headerButtonGroup}
103 >
104 {props.children}
105 </LiquidGlassView>
106 );
107 }
108​
109 return (
110 <View
111 style={[
112 styles.headerButtonGroup,
113 props.colorScheme === "dark"
114 ? { backgroundColor: "rgba(118,118,128,0.24)", borderColor: "rgba(255,255,255,0.08)" }
115 : { backgroundColor: "rgba(255,255,255,0.72)", borderColor: "rgba(0,0,0,0.08)" },
116 { borderWidth: StyleSheet.hairlineWidth },
117 ]}
118 >
119 {props.children}
120 </View>
121 );
123​
124const SIDEBAR_STICKY_HEADER_HEIGHT = 106;
125const SIDEBAR_STICKY_HEADER_FADE_HEIGHT = 44;
126const SIDEBAR_HEADER_WASH_OPACITY = {
127 dark: [0.22, 0.14, 0.04],
128 light: [0.46, 0.3, 0.08],
129} as const;
130​
131interface ThreadNavigationSidebarProps {
132 readonly width: number;
133 readonly visible: boolean;
134 readonly selectedThreadKey: string | null;
135 readonly onOpenSettings: () => void;
136 readonly onOpenEnvironmentSettings: () => void;
137 readonly onNewThreadInProject: (project: EnvironmentProject) => void;
138 readonly onSearchQueryChange: (query: string) => void;
139 readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
140 readonly onRequestVisibility: () => void;
141 readonly searchQuery: string;
143​
144/**
145 * iPad/large-width sidebar column.
146 *
147 * On iOS the pane is hosted inside its own navigation-inert single-screen
148 * native stack (SidebarNavigationShell) so the header is a real
149 * UINavigationBar: large title, native bar-button items, and a
150 * UISearchController search field — the same chrome a UISplitViewController
151 * column gets. Other platforms keep the custom header chrome.
152 */
153export function ThreadNavigationSidebar(props: ThreadNavigationSidebarProps) {
154 if (Platform.OS !== "ios") {
155 return <ThreadNavigationSidebarPane {...props} nativeChrome={false} />;
156 }
157 return <NativeSidebarContainer {...props} />;
159​
160function NativeSidebarContainer(props: ThreadNavigationSidebarProps) {
161 const backgroundColor = useThemeColor("--color-drawer");
162 const borderColor = useThemeColor("--color-border");
163​
164 return (
165 <View
166 testID="thread-navigation-sidebar"
167 className="flex-1"
168 style={{
169 width: props.width,
170 backgroundColor,
171 borderRightColor: borderColor,
172 borderRightWidth: StyleSheet.hairlineWidth,
173 }}
174 >
175 <SidebarNavigationShell>
176 <ThreadNavigationSidebarPane {...props} nativeChrome />
177 </SidebarNavigationShell>
178 </View>
179 );
181​
182function ThreadNavigationSidebarPane(
183 props: ThreadNavigationSidebarProps & { readonly nativeChrome: boolean },
184) {
185 const insets = useSafeAreaInsets();
186 const colorScheme = useColorScheme() === "dark" ? "dark" : "light";
187 const projects = useProjects();
188 const threads = useThreadShells();
189 const { state: catalogState } = useWorkspaceState();
190 const { savedConnectionsById } = useSavedRemoteConnections();
191 const [headerIsOverContent, setHeaderIsOverContent] = useState(false);
192 const searchInputRef = useRef<TextInput>(null);
193 const searchBarRef = useRef<SearchBarCommands>(null);
194 const openSwipeableRef = useRef<SwipeableMethods | null>(null);
195 const headerIsOverContentRef = useRef(false);
196 const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
197 const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
198 useThreadListActions();
199 const preferencesResult = useAtomValue(mobilePreferencesAtom);
200 const threadListV2Enabled =
201 AsyncResult.isSuccess(preferencesResult) &&
202 preferencesResult.value.threadListV2Enabled === true;
203 const pendingTasks = usePendingNewTasks();
204 const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
205 const environments = useMemo(
206 () =>
207 Object.values(savedConnectionsById)
208 .map((connection) => ({
209 environmentId: connection.environmentId,
210 label: connection.environmentLabel,
211 }))
212 .sort((left, right) => left.label.localeCompare(right.label)),
213 [savedConnectionsById],
214 );
215 const availableEnvironmentIds = useMemo(
216 () => new Set(environments.map((environment) => environment.environmentId)),
217 [environments],
218 );
219 const { options, setSelectedEnvironmentId, setProjectSortOrder, setThreadSortOrder } =
220 useHomeListOptions(availableEnvironmentIds);
221 const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
222 const projectScopes = useMemo(
223 () =>
224 buildHomeProjectScopes({
225 projects,
226 environmentId: options.selectedEnvironmentId,
227 projectGroupingMode: options.projectGroupingMode,
228 }),
229 [options.projectGroupingMode, options.selectedEnvironmentId, projects],
230 );
231 const projectFilterOptions = useMemo(
232 () =>
233 projectScopes.map((scope) => ({
234 key: scope.key,
235 label: scope.title,
236 })),
237 [projectScopes],
238 );
239 const projectTitleByProjectKey = useMemo(
240 () =>
241 new Map(
242 projectScopes.flatMap((scope) =>
243 scope.projectRefs.map(
244 (projectRef) =>
245 [
246 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
247 scope.title,
248 ] as const,
249 ),
250 ),
251 ),
252 [projectScopes],
253 );
254 const selectedProjectScope = useMemo(
255 () =>
256 selectedProjectKey === null
257 ? null
258 : (projectScopes.find((scope) => scope.key === selectedProjectKey) ?? null),
259 [projectScopes, selectedProjectKey],
260 );
261 useEffect(() => {
262 if (
263 selectedProjectKey !== null &&
264 !projectFilterOptions.some((project) => project.key === selectedProjectKey)
265 ) {
266 setSelectedProjectKey(null);
267 }
268 }, [projectFilterOptions, selectedProjectKey]);
269 const selectedProjectRefs = useMemo(
270 () =>
271 selectedProjectScope === null
272 ? null
273 : new Set(
274 selectedProjectScope.projectRefs.map((projectRef) =>
275 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
276 ),
277 ),
278 [selectedProjectScope],
279 );
280 const scopedProjects = useMemo(
281 () =>
282 selectedProjectRefs === null
283 ? projects
284 : projects.filter((project) =>
285 selectedProjectRefs.has(scopedProjectKey(project.environmentId, project.id)),
286 ),
287 [projects, selectedProjectRefs],
288 );
289 const scopedThreads = useMemo(
290 () =>
291 selectedProjectRefs === null
292 ? threads
293 : threads.filter((thread) =>
294 selectedProjectRefs.has(scopedProjectKey(thread.environmentId, thread.projectId)),
295 ),
296 [selectedProjectRefs, threads],
297 );
298 const scopedPendingTasks = useMemo(
299 () =>
300 selectedProjectRefs === null
301 ? pendingTasks
302 : pendingTasks.filter((pendingTask) =>
303 selectedProjectRefs.has(
304 scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
305 ),
306 ),
307 [pendingTasks, selectedProjectRefs],
308 );
309 const groups = useMemo(
310 () =>
311 buildHomeThreadGroups({
312 projects: scopedProjects,
313 threads: scopedThreads,
314 pendingTasks: scopedPendingTasks,
315 environmentId: options.selectedEnvironmentId,
316 searchQuery: props.searchQuery,
317 projectSortOrder: options.projectSortOrder,
318 threadSortOrder: options.threadSortOrder,
319 projectGroupingMode: options.projectGroupingMode,
320 }),
321 [options, props.searchQuery, scopedPendingTasks, scopedProjects, scopedThreads],
322 );
323 const [groupDisplayStates, setGroupDisplayStates] = useState<
324 ReadonlyMap<string, HomeGroupDisplayState>
325 >(() => new Map());
326 const updateGroupDisplay = useCallback((key: string, action: HomeGroupDisplayAction) => {
327 setGroupDisplayStates((previous) => {
328 const next = new Map(previous);
329 next.set(
330 key,
331 nextGroupDisplayState(previous.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action),
332 );
333 return next;
334 });
335 }, []);
336 const hasSearchQuery = props.searchQuery.trim().length > 0;
337 const listLayout = useMemo(
338 () =>
339 buildHomeListLayout({
340 groups,
341 displayStates: groupDisplayStates,
342 showAllThreads: hasSearchQuery,
343 }),
344 [groups, groupDisplayStates, hasSearchQuery],
345 );
346 const projectCwdByKey = useMemo(() => {
347 const map = new Map<string, string>();
348 for (const project of projects) {
349 map.set(scopedProjectKey(project.environmentId, project.id), project.workspaceRoot);
350 }
351 return map;
352 }, [projects]);
353 const projectByKey = useMemo(() => {
354 const map = new Map<string, EnvironmentProject>();
355 for (const project of projects) {
356 map.set(scopedProjectKey(project.environmentId, project.id), project);
357 }
358 return map;
359 }, [projects]);
360​
361 // Thread List v2 (beta) support — same model as the compact Home list
362 // (HomeScreen.tsx): flat creation-order card block + settled recency tail.
363 // PR states stream in per-row; merged/closed PRs auto-settle their thread
364 // on the next partition.
365 const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
366 ReadonlyMap<string, "open" | "closed" | "merged">
367 >(() => new Map());
368 const handleChangeRequestState = useCallback(
369 (threadKey: string, state: "open" | "closed" | "merged" | null) => {
370 setChangeRequestStateByKey((current) => {
371 if ((current.get(threadKey) ?? null) === state) return current;
372 const next = new Map(current);
373 if (state === null) {
374 next.delete(threadKey);
375 } else {
376 next.set(threadKey, state);
377 }
378 return next;
379 });
380 },
381 [],
382 );
383 // The settled tail renders in pages; expansion resets when the filter
384 // context changes so environment/search flips never inherit a deep page.
385 const [settledVisibleCount, setSettledVisibleCount] = useState(
386 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
387 );
388 const settledResetKey = `${options.selectedEnvironmentId ?? "all"}:${selectedProjectKey ?? "all"}:${props.searchQuery.trim()}`;
389 const lastSettledResetKeyRef = useRef(settledResetKey);
390 if (lastSettledResetKeyRef.current !== settledResetKey) {
391 lastSettledResetKeyRef.current = settledResetKey;
392 setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
393 }
394 const showMoreSettled = useCallback(
395 () => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
396 [],
397 );
398 // now ticks per minute so the inactivity auto-settle boundary is actually
399 // crossed while the pane stays open; without a clock dependency the
400 // partition memoizes a frozen "now".
401 const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
402 // Snooze wake times are second-precise; a counter bumped exactly at the
403 // next wake boundary re-runs the partition with a fresh clock so a woken
404 // thread reappears immediately instead of on the next minute tick.
405 const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
406 useEffect(() => {
407 if (!threadListV2Enabled) return;
408 // Refresh immediately on enable: the mount-time value can be hours old
409 // by the time the beta is switched on, which would misclassify the
410 // inactivity auto-settle boundary until the first tick.
411 setNowMinute(new Date().toISOString().slice(0, 16));
412 const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
413 return () => clearInterval(id);
414 }, [threadListV2Enabled]);
415 // Threads on servers without the settlement capability never classify as
416 // settled (the user could neither un-settle nor pin them).
417 const serverConfigs = useAtomValue(environmentServerConfigsAtom);
418 const settlementEnvironmentIds = useMemo(() => {
419 const supported = new Set<EnvironmentId>();
420 for (const [environmentId, config] of serverConfigs) {
421 if (config.environment.capabilities.threadSettlement === true) {
422 supported.add(environmentId);
423 }
424 }
425 return supported;
426 }, [serverConfigs]);
427 const snoozeEnvironmentIds = useMemo(() => {
428 const supported = new Set<EnvironmentId>();
429 for (const [environmentId, config] of serverConfigs) {
430 if (config.environment.capabilities.threadSnooze === true) {
431 supported.add(environmentId);
432 }
433 }
434 return supported;
435 }, [serverConfigs]);
436 const threadListV2Layout = useMemo(() => {
437 if (!threadListV2Enabled)
438 return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
439 return buildThreadListV2Items({
440 threads: threads.filter((thread) => thread.archivedAt === null),
441 environmentId: options.selectedEnvironmentId,
442 projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
443 searchQuery: props.searchQuery,
444 changeRequestStateByKey,
445 settlementEnvironmentIds,
446 snoozeEnvironmentIds,
447 settledLimit: settledVisibleCount,
448 now: `${nowMinute}:00.000Z`,
449 snoozeNow: new Date().toISOString(),
450 });
451 }, [
452 changeRequestStateByKey,
453 nowMinute,
454 snoozeWakeTick,
455 options.selectedEnvironmentId,
456 props.searchQuery,
457 settledVisibleCount,
458 settlementEnvironmentIds,
459 snoozeEnvironmentIds,
460 threadListV2Enabled,
461 threads,
462 selectedProjectScope,
463 ]);
464 // Re-partition the moment the earliest snooze expires (clamped to the
465 // signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
466 const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
467 useEffect(() => {
468 if (nextSnoozeWakeAt === null) return;
469 const wakeAtMs = Date.parse(nextSnoozeWakeAt);
470 if (Number.isNaN(wakeAtMs)) return;
471 const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
472 const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
473 return () => clearTimeout(id);
474 // snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
475 // unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
476 // range) the boundary string is identical and the chain would die.
477 }, [nextSnoozeWakeAt, snoozeWakeTick]);
478 const listItems = useMemo<readonly SidebarListItem[]>(() => {
479 if (!threadListV2Enabled) return listLayout.items;
480 // Queued offline tasks render above the thread rows (mirrors the
481 // compact Home v2 list): they are not thread shells, so the v2 item
482 // builder never sees them, but they must stay visible and deletable
483 // while their environment is offline. Same environment scope and
484 // search filter as the list.
485 const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
486 const v2PendingTasks = pendingTasks.filter(
487 (pendingTask) =>
488 (options.selectedEnvironmentId === null ||
489 pendingTask.message.environmentId === options.selectedEnvironmentId) &&
490 (selectedProjectRefs === null ||
491 selectedProjectRefs.has(
492 scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
493 )) &&
494 (v2SearchQuery.length === 0 ||
495 pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
496 );
497 const items: SidebarListItem[] = v2PendingTasks.map((pendingTask, index) => ({
498 type: "v2-pending-task" as const,
499 key: `v2-pending:${pendingTask.message.messageId}`,
500 pendingTask,
501 isLast: index === v2PendingTasks.length - 1,
502 }));
503 for (const item of threadListV2Layout.items) {
504 items.push({
505 type: "v2-thread" as const,
506 key: scopedThreadKey(item.thread.environmentId, item.thread.id),
507 item,
508 });
509 }
510 if (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 listLayout.items,
520 options.selectedEnvironmentId,
521 pendingTasks,
522 props.searchQuery,
523 selectedProjectRefs,
524 threadListV2Enabled,
525 threadListV2Layout,
526 ]);
527 const showsConnectionStatus = shouldShowWorkspaceConnectionStatus(catalogState);
528 const listMenuActions = useMemo<MenuAction[]>(
529 () => [
530 {
531 id: "environment",
532 title: "Environment",
533 subactions: [
534 {
535 id: "environment:all",
536 title: "All environments",
537 subtitle: "Show threads from every environment",
538 state: options.selectedEnvironmentId === null ? "on" : "off",
539 },
540 ...environments.map((environment) => ({
541 id: `environment:${environment.environmentId}`,
542 title: environment.label,
543 state:
544 options.selectedEnvironmentId === environment.environmentId
545 ? ("on" as const)
546 : ("off" as const),
547 })),
548 ],
549 },
550 ...(projectFilterOptions.length === 0
551 ? []
552 : ([
553 {
554 id: "project",
555 title: "Project",
556 subactions: [
557 {
558 id: "project:all",
559 title: "All projects",
560 subtitle: "Show threads from every project",
561 state: selectedProjectKey === null ? "on" : "off",
562 },
563 ...projectFilterOptions.map((project) => ({
564 id: `project:${project.key}`,
565 title: project.label,
566 state: selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
567 })),
568 ],
569 },
570 ] satisfies MenuAction[])),
571 // v2 lays the list out in fixed creation order — offering sort/group
572 // controls it silently ignores would be a lie. Environment still
573 // scopes the v2 partition, so it stays.
574 ...(threadListV2Enabled
575 ? []
576 : ([
577 {
578 id: "project-sort",
579 title: "Sort projects",
580 subactions: PROJECT_SORT_OPTIONS.map((option) => ({
581 id: `project-sort:${option.value}`,
582 title: option.label,
583 state: options.projectSortOrder === option.value ? "on" : "off",
584 })),
585 },
586 {
587 id: "thread-sort",
588 title: "Sort threads",
589 subactions: THREAD_SORT_OPTIONS.map((option) => ({
590 id: `thread-sort:${option.value}`,
591 title: option.label,
592 state: options.threadSortOrder === option.value ? "on" : "off",
593 })),
594 },
595 ] satisfies MenuAction[])),
596 ],
597 [environments, options, projectFilterOptions, selectedProjectKey, threadListV2Enabled],
598 );
599 const handleListMenuAction = useCallback(
600 ({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
601 const event = nativeEvent.event;
602 if (event === "environment:all") {
603 setSelectedEnvironmentId(null);
604 return;
605 }
606 if (event.startsWith("environment:")) {
607 const environment = environments.find(
608 (candidate) => String(candidate.environmentId) === event.slice("environment:".length),
609 );
610 if (environment) setSelectedEnvironmentId(environment.environmentId);
611 return;
612 }
613 if (event === "project:all") {
614 setSelectedProjectKey(null);
615 return;
616 }
617 if (event.startsWith("project:")) {
618 const projectKey = event.slice("project:".length);
619 if (projectFilterOptions.some((project) => project.key === projectKey)) {
620 setSelectedProjectKey(projectKey);
621 }
622 return;
623 }
624 const projectSort = PROJECT_SORT_OPTIONS.find(
625 (option) => `project-sort:${option.value}` === event,
626 );
627 if (projectSort) {
628 setProjectSortOrder(projectSort.value);
629 return;
630 }
631 const threadSort = THREAD_SORT_OPTIONS.find(
632 (option) => `thread-sort:${option.value}` === event,
633 );
634 if (threadSort) {
635 setThreadSortOrder(threadSort.value);
636 return;
637 }
638 },
639 [
640 environments,
641 projectFilterOptions,
642 setProjectSortOrder,
643 setSelectedEnvironmentId,
644 setThreadSortOrder,
645 ],
646 );
647​
648 const backgroundColor = useThemeColor("--color-drawer");
649 const borderColor = useThemeColor("--color-border");
650 const mutedColor = useThemeColor("--color-foreground-muted");
651 const placeholderColor = useThemeColor("--color-placeholder");
652 const headerFadeColor = String(backgroundColor);
653 const headerWashOpacity = SIDEBAR_HEADER_WASH_OPACITY[colorScheme];
654 const [measuredHeaderHeight, setMeasuredHeaderHeight] = useState<number | null>(null);
655 // The sticky header (title row, search field, optional connection status)
656 // is measured so the list inset always matches its real height — no
657 // hardcoded per-variant constants.
658 const stickyHeaderHeight = measuredHeaderHeight ?? insets.top + SIDEBAR_STICKY_HEADER_HEIGHT;
659 const topListInset = stickyHeaderHeight + 6;
660 const handleStickyHeaderLayout = useCallback((event: LayoutChangeEvent) => {
661 const nextHeight = Math.round(event.nativeEvent.layout.height);
662 setMeasuredHeaderHeight((current) => (current === nextHeight ? current : nextHeight));
663 }, []);
664 const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
665 if (openSwipeableRef.current !== methods) {
666 openSwipeableRef.current?.close();
667 openSwipeableRef.current = methods;
668 }
669 }, []);
670 const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
671 if (openSwipeableRef.current === methods) {
672 openSwipeableRef.current = null;
673 }
674 }, []);
675 const handleSelectThread = useCallback(
676 (thread: EnvironmentThreadShell) => {
677 props.onSelectThread(thread);
678 openSwipeableRef.current?.close();
679 },
680 [props.onSelectThread],
681 );
682 const handleScroll = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
683 const next = event.nativeEvent.contentOffset.y > 6;
684 if (headerIsOverContentRef.current === next) {
685 return;
686 }
687 headerIsOverContentRef.current = next;
688 setHeaderIsOverContent(next);
689 }, []);
690 const handleScrollBeginDrag = useCallback(() => {
691 openSwipeableRef.current?.close();
692 }, []);
693 const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
694 onScroll: handleScroll,
695 onScrollBeginDrag: handleScrollBeginDrag,
696 });
697 const listExtraData = useMemo(
698 () => ({
699 selectedThreadKey: props.selectedThreadKey ?? "",
700 savedConnectionsById,
701 serverConfigs,
702 }),
703 [props.selectedThreadKey, savedConnectionsById, serverConfigs],
704 );
705 const sidebarItemsAreEqual = useCallback(
706 (previous: SidebarListItem, item: SidebarListItem): boolean => {
707 if (previous.type === "v2-thread" && item.type === "v2-thread") {
708 return (
709 previous.key === item.key &&
710 previous.item.thread === item.item.thread &&
711 previous.item.variant === item.item.variant &&
712 previous.item.showSettledDivider === item.item.showSettledDivider
713 );
714 }
715 if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
716 return previous.hiddenCount === item.hiddenCount;
717 }
718 if (previous.type === "v2-pending-task" && item.type === "v2-pending-task") {
719 return previous.pendingTask === item.pendingTask && previous.isLast === item.isLast;
720 }
721 if (
722 previous.type === "v2-thread" ||
723 previous.type === "v2-show-more" ||
724 previous.type === "v2-pending-task" ||
725 item.type === "v2-thread" ||
726 item.type === "v2-show-more" ||
727 item.type === "v2-pending-task"
728 ) {
729 return false;
730 }
731 return homeListItemsAreEqual(previous, item);
732 },
733 [],
734 );
735 const focusSearch = useCallback(() => {
736 const focus = () => {
737 if (props.nativeChrome) {
738 searchBarRef.current?.focus();
739 return;
740 }
741 searchInputRef.current?.focus();
742 };
743 if (!props.visible) {
744 props.onRequestVisibility();
745 setTimeout(focus, 240);
746 } else {
747 focus();
748 }
749 return true;
750 }, [props.nativeChrome, props.onRequestVisibility, props.visible]);
751 useHardwareKeyboardCommand("focusSearch", focusSearch);
752 const renderListItem = useCallback(
753 ({ item }: { readonly item: SidebarListItem }) => {
754 switch (item.type) {
755 case "v2-pending-task":
756 return (
757 <PendingTaskListRow
758 variant="sidebar"
759 pendingTask={item.pendingTask}
760 environmentLabel={
761 savedConnectionsById[item.pendingTask.message.environmentId]?.environmentLabel ??
762 null
763 }
764 isLast={item.isLast}
765 onSelectPendingTask={openPendingTask}
766 onDeletePendingTask={confirmDeletePendingTask}
767 />
768 );
769 case "v2-thread": {
770 const thread = item.item.thread;
771 const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId);
772 return (
773 <ThreadListV2Row
774 thread={thread}
775 variant={item.item.variant}
776 showSettledDivider={item.item.showSettledDivider}
777 project={projectByKey.get(scopeKey) ?? null}
778 projectTitle={projectTitleByProjectKey.get(scopeKey)}
779 providerDriver={
780 serverConfigs
781 .get(thread.environmentId)
782 ?.providers.find(
783 (provider) =>
784 provider.instanceId ===
785 (thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
786 )?.driver ?? null
787 }
788 environmentLabel={
789 Object.keys(savedConnectionsById).length > 1
790 ? (savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
791 : null
792 }
793 pane="sidebar"
794 selected={
795 scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
796 }
797 fullSwipeWidth={props.width - 20}
798 onSelectThread={handleSelectThread}
799 onDeleteThread={confirmDeleteThread}
800 onArchiveThread={archiveThread}
801 settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
802 onSettleThread={settleThread}
803 onUnsettleThread={unsettleThread}
804 onChangeRequestState={handleChangeRequestState}
805 projectCwd={projectCwdByKey.get(scopeKey) ?? null}
806 onSwipeableClose={handleSwipeableClose}
807 onSwipeableWillOpen={handleSwipeableWillOpen}
808 simultaneousSwipeGesture={sidebarScrollGesture}
809 />
810 );
811 }
812 case "v2-show-more":
813 return (
814 <Pressable
815 accessibilityRole="button"
816 accessibilityLabel={`Show ${Math.min(item.hiddenCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
817 onPress={showMoreSettled}
818 className="mx-4 mt-2 items-center rounded-lg border border-dashed border-border py-2.5"
819 style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
820 >
821 <Text className="text-xs font-t3-medium text-foreground-muted">
822 Show more ({item.hiddenCount} settled hidden)
823 </Text>
824 </Pressable>
825 );
826 case "header":
827 return (
828 <ThreadListGroupHeader
829 variant="sidebar"
830 collapsed={item.collapsed}
831 isFirst={item.isFirst}
832 groupKey={item.group.key}
833 onGroupAction={updateGroupDisplay}
834 // Same gating as the compact Home list: aggregated groups have no
835 // single target project, and pending-project groups hold a
836 // placeholder shell rather than a real project.
837 newThreadTarget={item.group.newThreadTarget}
838 onNewThread={props.onNewThreadInProject}
839 project={item.group.representative}
840 threadCount={item.group.threads.length + item.group.pendingTasks.length}
841 title={item.group.title}
842 />
843 );
844 case "pending-task":
845 return (
846 <PendingTaskListRow
847 variant="sidebar"
848 pendingTask={item.pendingTask}
849 environmentLabel={
850 savedConnectionsById[item.pendingTask.message.environmentId]?.environmentLabel ??
851 null
852 }
853 isLast={item.isLast}
854 onSelectPendingTask={openPendingTask}
855 onDeletePendingTask={confirmDeletePendingTask}
856 />
857 );
858 case "thread": {
859 const thread = item.thread;
860 return (
861 <ThreadListRow
862 variant="sidebar"
863 thread={thread}
864 environmentLabel={
865 savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
866 }
867 projectCwd={
868 projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ??
869 null
870 }
871 isLast={item.isLast}
872 selected={
873 scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
874 }
875 fullSwipeWidth={props.width - 20}
876 onArchiveThread={archiveThread}
877 onDeleteThread={confirmDeleteThread}
878 onSelectThread={handleSelectThread}
879 onSwipeableClose={handleSwipeableClose}
880 onSwipeableWillOpen={handleSwipeableWillOpen}
881 simultaneousSwipeGesture={sidebarScrollGesture}
882 />
883 );
884 }
885 case "show-more":
886 return (
887 <ThreadListShowMoreRow
888 variant="sidebar"
889 hiddenCount={item.hiddenCount}
890 canShowLess={item.canShowLess}
891 groupKey={item.groupKey}
892 onGroupAction={updateGroupDisplay}
893 />
894 );
895 }
896 },
897 [
898 archiveThread,
899 confirmDeletePendingTask,
900 confirmDeleteThread,
901 handleChangeRequestState,
902 handleSelectThread,
903 handleSwipeableClose,
904 handleSwipeableWillOpen,
905 openPendingTask,
906 projectByKey,
907 projectCwdByKey,
908 projectTitleByProjectKey,
909 props.onNewThreadInProject,
910 props.selectedThreadKey,
911 props.width,
912 savedConnectionsById,
913 serverConfigs,
914 settleThread,
915 settlementEnvironmentIds,
916 showMoreSettled,
917 sidebarScrollGesture,
918 unsettleThread,
919 updateGroupDisplay,
920 ],
921 );
922 // v2 ignores the sort/group options, so only the environment filter can
923 // light the "customized" state while the beta is on.
924 const filterCustomized = threadListV2Enabled
925 ? options.selectedEnvironmentId !== null || selectedProjectKey !== null
926 : hasCustomHomeListOptions({ ...options, selectedProjectKey });
927 const filterIcon = filterCustomized
928 ? "line.3.horizontal.decrease.circle.fill"
929 : "line.3.horizontal.decrease.circle";
930 const filterMenu = useMemo(
931 () =>
932 buildHomeListFilterMenu({
933 environments,
934 projects: projectFilterOptions,
935 selectedEnvironmentId: options.selectedEnvironmentId,
936 selectedProjectKey,
937 projectSortOrder: options.projectSortOrder,
938 threadSortOrder: options.threadSortOrder,
939 onEnvironmentChange: setSelectedEnvironmentId,
940 onProjectChange: setSelectedProjectKey,
941 onProjectSortOrderChange: setProjectSortOrder,
942 onThreadSortOrderChange: setThreadSortOrder,
943 listOrganization: !threadListV2Enabled,
944 }),
945 [
946 environments,
947 options,
948 projectFilterOptions,
949 selectedProjectKey,
950 setProjectSortOrder,
951 setSelectedEnvironmentId,
952 setThreadSortOrder,
953 threadListV2Enabled,
954 ],
955 );
956 const nativeHeaderItems = useMemo(
957 () =>
958 createSidebarHeaderItems({
959 filterIcon,
960 filterMenu,
961 onOpenSettings: props.onOpenSettings,
962 }),
963 [filterIcon, filterMenu, props.onOpenSettings],
964 );
965 // "No threads yet" over an inbox that is merely all-snoozed reads as
966 // data loss; name the snoozed threads instead.
967 const snoozedCount = threadListV2Layout.snoozedCount;
968 const listEmpty = (
969 <Text className="px-2 py-4 text-sm text-foreground-muted">
970 {catalogState.isLoadingConnections
971 ? "Loading threads…"
972 : props.searchQuery.trim().length > 0
973 ? snoozedCount > 0
974 ? // Snoozed matches passed this same search filter — "No
975 // matching threads" would misreport them as nonexistent.
976 snoozedCount === 1
977 ? "1 matching thread snoozed"
978 : "All matching threads snoozed"
979 : "No matching threads"
980 : snoozedCount > 0
981 ? snoozedCount === 1
982 ? "1 thread snoozed"
983 : `${snoozedCount} threads snoozed`
984 : selectedProjectScope !== null
985 ? `No threads in ${selectedProjectScope.title}`
986 : "No threads yet"}
987 </Text>
988 );
989​
990 if (props.nativeChrome) {
991 return (
992 <>
993 <NativeStackScreenOptions
994 optionsVersion={nativeHeaderItems}
995 options={{
996 headerSearchBarOptions: {
997 ref: searchBarRef,
998 autoCapitalize: "none",
999 hideNavigationBar: false,
1000 // Keep the search bar pinned under the title — UIKit's default
1001 // hidesSearchBarWhenScrolling collapses it on scroll.
1002 hideWhenScrolling: false,
1003 obscureBackground: false,
1004 placeholder: "Search",
1005 placement: "stacked",
1006 onCancelButtonPress: () => {
1007 props.onSearchQueryChange("");
1008 },
1009 onChangeText: (event) => {
1010 props.onSearchQueryChange(event.nativeEvent.text);
1011 },
1012 },
1013 unstable_headerRightItems: () => nativeHeaderItems,
1014 }}
1015 />
1016 <View className="flex-1">
1017 <SwipeableScrollGateProvider enabled={swipeEnabled}>
1018 <GestureDetector gesture={sidebarScrollGesture}>
1019 <LegendList
1020 data={listItems}
1021 drawDistance={500}
1022 estimatedItemSize={64}
1023 extraData={listExtraData}
1024 getItemType={(item) => item.type}
1025 itemsAreEqual={sidebarItemsAreEqual}
1026 keyExtractor={(item) => item.key}
1027 renderItem={renderListItem}
1028 automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
1029 contentInsetAdjustmentBehavior={
1030 NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"
1032 contentContainerStyle={[
1033 styles.threadListContent,
1035 paddingBottom: Math.max(insets.bottom, 16) + 16,
1036 paddingTop: 6,
1037 },
1038 ]}
1039 keyboardDismissMode="on-drag"
1040 keyboardShouldPersistTaps="handled"
1041 {...scrollGateHandlers}
1042 recycleItems
1043 scrollEventThrottle={16}
1044 showsVerticalScrollIndicator={false}
1045 style={styles.threadList}
1046 ListHeaderComponent={
1047 showsConnectionStatus ? (
1048 <View className="px-1.5 pt-0.5 pb-2">
1049 <WorkspaceConnectionStatus
1050 onPress={props.onOpenEnvironmentSettings}
1051 state={catalogState}
1052 variant="sidebar"
1053 />
1054 </View>
1055 ) : null
1057 ListEmptyComponent={listEmpty}
1058 />
1059 </GestureDetector>
1060 </SwipeableScrollGateProvider>
1061 </View>
1062 </>
1063 );
1065​
1066 return (
1067 <View
1068 testID="thread-navigation-sidebar"
1069 className="flex-1"
1070 style={{
1071 width: props.width,
1072 backgroundColor,
1073 borderRightColor: borderColor,
1074 borderRightWidth: StyleSheet.hairlineWidth,
1075 }}
1077 <View className="flex-1" style={{ paddingBottom: insets.bottom }}>
1078 <SwipeableScrollGateProvider enabled={swipeEnabled}>
1079 <GestureDetector gesture={sidebarScrollGesture}>
1080 <LegendList
1081 data={listItems}
1082 drawDistance={500}
1083 estimatedItemSize={64}
1084 extraData={listExtraData}
1085 getItemType={(item) => item.type}
1086 itemsAreEqual={sidebarItemsAreEqual}
1087 keyExtractor={(item) => item.key}
1088 renderItem={renderListItem}
1089 contentContainerStyle={[
1090 styles.threadListContent,
1092 paddingBottom: 16 + insets.bottom,
1093 paddingTop: topListInset,
1094 },
1095 ]}
1096 keyboardDismissMode="on-drag"
1097 keyboardShouldPersistTaps="handled"
1098 {...scrollGateHandlers}
1099 recycleItems
1100 scrollEventThrottle={16}
1101 showsVerticalScrollIndicator={false}
1102 style={styles.threadList}
1103 ListEmptyComponent={listEmpty}
1104 />
1105 </GestureDetector>
1106 </SwipeableScrollGateProvider>
1107 </View>
1108​
1109 <View
1110 className="absolute inset-x-0 top-0 z-[4]"
1111 onLayout={handleStickyHeaderLayout}
1112 pointerEvents="box-none"
1113 style={{ paddingTop: insets.top }}
1115 <View
1116 className="absolute inset-x-0 top-0"
1117 pointerEvents="none"
1118 accessibilityElementsHidden
1119 importantForAccessibility="no-hide-descendants"
1120 style={{ height: stickyHeaderHeight + SIDEBAR_STICKY_HEADER_FADE_HEIGHT }}
1122 <Svg width="100%" height="100%">
1123 <Defs>
1124 <LinearGradient id="sidebar-header-wash" x1="0%" x2="0%" y1="0%" y2="100%">
1125 <Stop
1126 offset="0%"
1127 stopColor={headerFadeColor}
1128 stopOpacity={headerIsOverContent ? headerWashOpacity[0] : 0}
1129 />
1130 <Stop
1131 offset="58%"
1132 stopColor={headerFadeColor}
1133 stopOpacity={headerIsOverContent ? headerWashOpacity[1] : 0}
1134 />
1135 <Stop
1136 offset="88%"
1137 stopColor={headerFadeColor}
1138 stopOpacity={headerIsOverContent ? headerWashOpacity[2] : 0}
1139 />
1140 <Stop offset="100%" stopColor={headerFadeColor} stopOpacity={0} />
1141 </LinearGradient>
1142 </Defs>
1143 <Rect width="100%" height="100%" fill="url(#sidebar-header-wash)" />
1144 </Svg>
1145 </View>
1146 <View className="h-[50px] flex-row items-end gap-0.5 pr-2 pl-5">
1147 <Text className="flex-1 text-[34px] font-t3-bold text-foreground" numberOfLines={1}>
1148 Threads
1149 </Text>
1150 <SidebarHeaderButtonGroup colorScheme={colorScheme}>
1151 <ControlPillMenu actions={listMenuActions} onPressAction={handleListMenuAction}>
1152 <SidebarFilterButton
1153 grouped
1154 accessibilityLabel="Filter and sort threads"
1155 icon={filterIcon}
1156 />
1157 </ControlPillMenu>
1158 <SidebarHeaderActions grouped onOpenSettings={props.onOpenSettings} />
1159 </SidebarHeaderButtonGroup>
1160 </View>
1161​
1162 <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]">
1163 <SymbolView name="magnifyingglass" size={15} tintColor={mutedColor} type="monochrome" />
1164 <TextInput
1165 ref={searchInputRef}
1166 accessibilityLabel="Search threads"
1167 autoCapitalize="none"
1168 autoCorrect={false}
1169 clearButtonMode="while-editing"
1170 onChangeText={props.onSearchQueryChange}
1171 placeholder="Search"
1172 placeholderTextColor={placeholderColor}
1173 returnKeyType="search"
1174 className="h-[34px] flex-1 px-0 py-0 font-sans text-base text-foreground"
1175 value={props.searchQuery}
1176 />
1177 </View>
1178​
1179 {showsConnectionStatus ? (
1180 <View className="px-3.5 pt-2.5">
1181 <WorkspaceConnectionStatus
1182 onPress={props.onOpenEnvironmentSettings}
1183 state={catalogState}
1184 variant="sidebar"
1185 />
1186 </View>
1187 ) : null}
1188 </View>
1189 </View>
1190 );
1192​
1193const styles = StyleSheet.create({
1194 headerButtonGroup: {
1195 alignItems: "center",
1196 borderRadius: 22,
1197 flexDirection: "row",
1198 overflow: "hidden",
1199 },
1200 threadList: {
1201 flex: 1,
1202 },
1203 threadListContent: {
1204 paddingHorizontal: 8,
1205 },
1206});