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

ThreadNavigationSidebar.tsx

1,277 lines47.1 KB

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