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