Open History to see the last commit
1import { usePaneRole } from "../../components/ui/Pane";
2import { ScreenContent } from "../../components/ui/ScreenContent";
3import { useActiveNewTask } from "../../state/active-new-task";
4import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
5import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";
6import type { ThreadMoveDestination } from "../threads/threadOrder";
7import type { LegendListRef } from "@legendapp/list/react-native";
8import { AnimatedLegendList } from "@legendapp/list/reanimated";
9import { THREAD_SIDEBAR_ROW_LAYOUT } from "../threads/threadListAnimations";
10import {
11 type EnvironmentProject,
12 type EnvironmentThreadShell,
13} from "@t3tools/client-runtime/state/shell";
14import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping";
15import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
16import { type EnvironmentId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
17import { useAtomValue } from "@effect/atom-react";
18import { use, useEffect, useMemo, useRef, useState, type ComponentProps } from "react";
19import {
20 Platform,
21 ScrollView,
22 useWindowDimensions,
23 View,
24 type ScrollViewProps,
25 type GestureResponderEvent,
26 type NativeScrollEvent,
27 type NativeSyntheticEvent,
28} from "react-native";
29import { NativeScrollViewMarker as ScrollViewMarker } from "../../native/NativeScrollViewMarker";
30import { GestureDetector, useNativeGesture } from "react-native-gesture-handler";
31import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
32import { useSafeAreaInsets } from "react-native-safe-area-context";
33
34import { cn } from "../../lib/cn";
35import {
36 ANDROID_READING_MAX_WIDTH,
37 deriveCenteredContentHorizontalPadding,
38} from "../../lib/layout";
39import { EmptyState } from "../../components/ui/EmptyState";
40import { FloatingActionButton } from "../../components/ui/FloatingActionButton";
41import type { WorkspaceEnvironment, WorkspaceState } from "../../state/workspaceModel";
42import type { SavedRemoteConnection } from "../../lib/connection";
43import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
44import { NativePrimaryColumnContext } from "../../native/v5-workspace-context";
45import { nativeHeaderScrollEdgeEffects } from "../../native/scrollEdgeEffects";
46import {
47 useNativeColumnLayoutMetrics,
48 useNativeLayoutMetrics,
49} from "../../native/native-layout-metrics";
50import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
51import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns";
52import { useThreadSearch } from "../../state/queries";
53import { requestThreadMessageJump } from "../threads/threadMessageJump";
54import { useThreadListSearchMatches } from "../threads/useThreadListSearchMatches";
55import { useThreadListV2 } from "../threads/useThreadListV2";
56import { useThreadListNow } from "../threads/use-thread-list-now";
57import { useSearchScrollRestoration } from "../workspace/useSearchScrollRestoration";
58import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts";
59import { usePendingThreadOrder } from "../../state/thread-order";
60import { threadListEnvironmentsAtom } from "../../state/presentation";
61import type { PendingNewTask } from "../../state/use-pending-new-tasks";
62import { useQueuedThreadKeys } from "../../state/use-thread-outbox";
63import {
64 ThreadListV2PendingRow,
65 ThreadListV2Row,
66 ThreadListV2SettledShelfHeader,
67 ThreadListV2ShowMoreRow,
68 ThreadListV2SnoozedShelfHeader,
69 ThreadListV2WorkingShelfHeader,
70} from "../threads/thread-list-v2-items";
71import { useThreadRowProviderInstanceResolver } from "../threads/thread-provider-instance";
72import { useOpenThreadPullRequests } from "../threads/use-open-thread-pull-requests";
73import type { ThreadPrPresentation } from "../../state/thread-pr-presentation";
74import {
75 threadListV2ListItemsAreEqual,
76 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
77 THREAD_LIST_V2_SETTLED_PAGE_COUNT,
78 type ThreadListV2ListItem,
79} from "../threads/threadListV2";
80import { useThreadListV2ShelfPreferences } from "../threads/use-thread-list-v2-shelf-preferences";
81import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
82import {
83 buildHomeProjectScopes,
84 findHomeProjectScope,
85 type HomeProjectSortOrder,
86} from "./homeThreadList";
87import { createSwipeRowActivation } from "./swipe-row-activation";
88import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
89import { useFabScroll } from "./FabScrollContext";
90import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";
91import { ThreadListFilters } from "./ThreadListFilters";
92
93interface HomeScreenProps {
94 readonly projects: ReadonlyArray<EnvironmentProject>;
95 readonly threads: ReadonlyArray<EnvironmentThreadShell>;
96 readonly pendingTasks: ReadonlyArray<PendingNewTask>;
97 readonly catalogState: WorkspaceState;
98 readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
99 readonly environments: ReadonlyArray<
100 HomeListFilterMenuEnvironment & Pick<WorkspaceEnvironment, "connectionState">
101 >;
102 readonly searchQuery: string;
103 readonly selectedEnvironmentId: EnvironmentId | null;
104 readonly selectedProjectKey: string | null;
105 readonly projectSortOrder: HomeProjectSortOrder;
106 readonly projectGroupingMode: SidebarProjectGroupingMode;
107 readonly onSearchQueryChange: (query: string) => void;
108 readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
109 readonly onProjectChange: (projectKey: string | null) => void;
110 readonly onAddConnection: () => void;
111 readonly onOpenSettings: () => void;
112 readonly onStartNewTask: () => void;
113 readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
114 readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
115 readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
116 readonly onSettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
117 readonly onSnoozeThread: (
118 thread: EnvironmentThreadShell,
119 snoozedUntil: string,
120 ) => Promise<boolean>;
121 readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
122 readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
123 readonly onPinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
124 readonly onUnpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
125 readonly onSetThreadAutoSettle: (
126 thread: EnvironmentThreadShell,
127 enabled: boolean,
128 ) => Promise<boolean>;
129 readonly onMoveThread: (
130 thread: EnvironmentThreadShell,
131 direction: ThreadMoveDestination,
132 ) => Promise<boolean>;
133 readonly onRenameThread: (thread: EnvironmentThreadShell) => void;
134 readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
135 readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
136 readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
137 readonly onNewThreadOnBranch: (thread: EnvironmentThreadShell) => void;
138 readonly onNewThreadInProject: (project: EnvironmentProject) => void;
139}
140
141const ESTIMATED_THREAD_LIST_V2_ROW_HEIGHT = 72;
142// Rows away from the viewport skip their swipe actions (see
143// swipe-row-activation), so render further ahead: a fast fling then reaches
144// rows that are already built instead of rows still being rebuilt.
145const THREAD_LIST_V2_DRAW_DISTANCE = 1_000;
146
147function deriveEmptyState(props: {
148 readonly catalogState: WorkspaceState;
149 readonly projectCount: number;
150}): { readonly title: string; readonly detail: string; readonly loading: boolean } {
151 const { catalogState } = props;
152 if (catalogState.isLoadingConnections) {
153 return {
154 title: "Loading environments",
155 detail: "Checking saved environments on this device.",
156 loading: true,
157 };
158 }
159
160 if (!catalogState.hasConnections) {
161 return {
162 title: "No environments connected",
163 detail: "Add an environment to load projects and start coding sessions.",
164 loading: false,
165 };
166 }
167
168 if (
169 (catalogState.connectionState === "available" ||
170 catalogState.connectionState === "offline" ||
171 catalogState.connectionState === "error" ||
172 catalogState.connectionState === "unsupported") &&
173 !catalogState.hasLoadedShellSnapshot
174 ) {
175 return {
176 title:
177 catalogState.connectionState === "unsupported"
178 ? "Client not supported"
179 : "Environment unavailable",
180 detail:
181 catalogState.connectionError ??
182 "The saved environment is offline. Check the URL or start the environment, then retry.",
183 loading: false,
184 };
185 }
186
187 if (
188 catalogState.hasConnectingEnvironment &&
189 !catalogState.hasLoadedShellSnapshot &&
190 catalogState.connectionError === null
191 ) {
192 return {
193 title: "Connecting to environment",
194 detail: "Loading projects and threads from the saved environment.",
195 loading: true,
196 };
197 }
198
199 if (props.projectCount === 0 && catalogState.hasLoadedShellSnapshot) {
200 return {
201 title: "No projects found",
202 detail: "The connected environment did not report any projects.",
203 loading: false,
204 };
205 }
206
207 return {
208 title: "No threads yet",
209 detail: "Create a task to start a new coding runtime in one of your connected projects.",
210 loading: false,
211 };
212}
213
214function HomeTopContentSpacer() {
215 return <View className="h-4" />;
216}
217
218function HomeScrollView(props: ComponentProps<typeof ScrollView>) {
219 const primaryColumn = use(NativePrimaryColumnContext);
220 const sidebarSurface = usePaneRole() === "sidebar" && primaryColumn !== null;
221 if (Platform.OS !== "ios") return <ScrollView {...props} />;
222
223 // Register the scroll view explicitly; layout and header siblings hide it from UIKit.
224 return (
225 <ScrollViewMarker
226 style={{ flex: 1 }}
227 scrollEdgeEffects={{
228 ...nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version),
229 top: Number.parseInt(String(Platform.Version), 10) >= 27 ? "automatic" : "soft",
230 }}
231 >
232 <ScrollView
233 {...props}
234 // UIKit's scroll-edge material needs the scroll view's own surface color.
235 className={cn(props.className, sidebarSurface ? "bg-drawer" : "bg-screen")}
236 />
237 </ScrollViewMarker>
238 );
239}
240
241function renderHomeScrollView(props: ScrollViewProps) {
242 // FlatList clones this with cells and ref; keep the marker inside their actual ScrollView.
243 return <HomeScrollView {...props} />;
244}
245
246export function HomeScreen(props: HomeScreenProps) {
247 const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();
248 const workspace = useWorkspaceTabs();
249 const [initialScrollOffset] = useState(() => workspace?.getScrollOffset("threads") ?? 0);
250 const primaryColumn = use(NativePrimaryColumnContext);
251 const sidebarSurface = usePaneRole() === "sidebar" && primaryColumn !== null;
252 const contentBackground = sidebarSurface ? "bg-drawer" : "bg-screen";
253 const containerClassName = cn(
254 "flex-1",
255 Platform.OS === "android" ? "bg-header" : contentBackground,
256 );
257 const columnMetrics = useNativeColumnLayoutMetrics();
258 const activeNewTask = useActiveNewTask();
259 const selectedThreadKey = activeNewTask ? null : (primaryColumn?.selectedThreadKey ?? null);
260 const fullSwipeWidth = primaryColumn && columnMetrics ? columnMetrics.width - 20 : undefined;
261 const queuedThreadKeys = useQueuedThreadKeys();
262 const openSwipeableRef = useRef<SwipeableMethods | null>(null);
263 const homeScrollGesture = useNativeGesture();
264 const insets = useSafeAreaInsets();
265 const { fabClearance } = useAndroidControlSizing();
266 const screenMetrics = useNativeLayoutMetrics();
267 const contentSideInsets = usesNativeWorkspaceColumns
268 ? (columnMetrics ?? screenMetrics)?.safeArea
269 : undefined;
270 // Wide Android lists need reading-width gutters to clear edges and camera cutouts.
271 const { width: windowWidth } = useWindowDimensions();
272 const androidListGutter =
273 Platform.OS === "android"
274 ? deriveCenteredContentHorizontalPadding({
275 viewportWidth: windowWidth,
276 maxContentWidth: ANDROID_READING_MAX_WIDTH,
277 minimumPadding: 0,
278 })
279 : 0;
280 const iosBottomClearance = Math.max(
281 columnMetrics?.safeArea.bottom ?? insets.bottom,
282 24,
283 workspace?.bottomClearance ?? 0,
284 );
285 const searchEnvironmentIds =
286 props.selectedEnvironmentId === null
287 ? props.environments
288 .filter((environment) => environment.connectionState === "connected")
289 .map((environment) => environment.environmentId)
290 : props.environments.some(
291 (environment) =>
292 environment.environmentId === props.selectedEnvironmentId &&
293 environment.connectionState === "connected",
294 )
295 ? [props.selectedEnvironmentId]
296 : [];
297 const handleSwipeableWillOpen = (methods: SwipeableMethods) => {
298 if (openSwipeableRef.current !== methods) {
299 openSwipeableRef.current?.close();
300 openSwipeableRef.current = methods;
301 }
302 };
303
304 const handleSwipeableClose = (methods: SwipeableMethods) => {
305 if (openSwipeableRef.current === methods) {
306 openSwipeableRef.current = null;
307 }
308 };
309
310 const handleScrollBeginDrag = () => {
311 openSwipeableRef.current?.close();
312 };
313 const openThreadPullRequests = useOpenThreadPullRequests();
314 const handleOpenThreadPullRequests = (
315 thread: EnvironmentThreadShell,
316 pr: ThreadPrPresentation,
317 ) => {
318 openSwipeableRef.current?.close();
319 openThreadPullRequests(thread, pr);
320 };
321 const onFabScroll = useFabScroll();
322 const listRef = useRef<LegendListRef>(null);
323 const searchMode = workspace?.state.tabs.threads.searchMode;
324 const restoredOffset = workspace?.state.tabs.threads.scrollOffset;
325 useSearchScrollRestoration(searchMode, () => {
326 if (restoredOffset === undefined) return;
327 void listRef.current?.scrollToOffset({
328 offset: restoredOffset - (Platform.OS === "ios" ? insets.top : 0),
329 animated: false,
330 });
331 });
332 const swipeRowActivation = createSwipeRowActivation();
333 const activateVisibleRows = (rows: ReadonlyArray<ThreadListV2ListItem>) => {
334 const state = listRef.current?.getState();
335 if (state === undefined || !(state.end >= 0)) return;
336 swipeRowActivation.activate(
337 rows.slice(Math.max(0, state.start - 2), state.end + 3).map((row) => row.key),
338 );
339 };
340 // Status-bar, accessibility and programmatic scrolls bypass the gate; activate visible rows after settling.
341 const activationTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
342 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the row activation timer on unmount
343 useEffect(() => () => clearTimeout(activationTimerRef.current), []);
344 const handleListScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
345 onFabScroll?.(event);
346 if (workspace)
347 workspace.recordScrollOffset(
348 "threads",
349 Math.max(0, event.nativeEvent.contentOffset.y + (Platform.OS === "ios" ? insets.top : 0)),
350 );
351 clearTimeout(activationTimerRef.current);
352 activationTimerRef.current = setTimeout(
353 () => activateVisibleRows(listRef.current?.getState().data ?? []),
354 200,
355 );
356 };
357 const trackListTouches = (event: GestureResponderEvent, started: boolean) => {
358 const { changedTouches, touches } = event.nativeEvent;
359 swipeRowActivation.trackTouches(
360 started ? changedTouches.map((touch) => String(touch.identifier)) : [],
361 touches.map((touch) => String(touch.identifier)),
362 );
363 };
364 const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
365 onScroll: handleListScroll,
366 onScrollBeginDrag: handleScrollBeginDrag,
367 });
368
369 const { projects, selectedEnvironmentId, projectGroupingMode } = props;
370 const projectScopes = useMemo(
371 () =>
372 buildHomeProjectScopes({
373 projects,
374 environmentId: selectedEnvironmentId,
375 projectGroupingMode,
376 }),
377 [projects, selectedEnvironmentId, projectGroupingMode],
378 );
379 const hasSearchQuery = props.searchQuery.trim().length > 0;
380 const projectByKey = (() => {
381 const map = new Map<string, EnvironmentProject>();
382 for (const project of props.projects) {
383 map.set(scopedProjectKey(project.environmentId, project.id), project);
384 }
385 return map;
386 })();
387
388 const v2ProjectScopeKey = props.selectedProjectKey;
389 // An archived project's filter reads as all projects, matching the filter menu.
390 const v2ScopedProjectGroup = findHomeProjectScope(
391 pickableProjectGroups(projectScopes),
392 v2ProjectScopeKey,
393 );
394 const threadSearch = useThreadSearch(
395 searchEnvironmentIds,
396 props.searchQuery,
397 v2ScopedProjectGroup === null
398 ? {}
399 : { projectIds: v2ScopedProjectGroup.projectRefs.map((ref) => ref.projectId) },
400 );
401 const threadSearchMatchByKey = useThreadListSearchMatches(props.threads, threadSearch);
402 const v2ProjectTitleByProjectKey = new Map(
403 projectScopes.flatMap((scope) =>
404 scope.projectRefs.map(
405 (projectRef) =>
406 [scopedProjectKey(projectRef.environmentId, projectRef.projectId), scope.title] as const,
407 ),
408 ),
409 );
410 const handleSettleThread = props.onSettleThread;
411 const handleSnoozeThread = props.onSnoozeThread;
412 const handleUnsnoozeThread = props.onUnsnoozeThread;
413 const handlePinThread = props.onPinThread;
414 const handleMoveThread = props.onMoveThread;
415 const handleUnpinThread = props.onUnpinThread;
416 const handleSetThreadAutoSettle = props.onSetThreadAutoSettle;
417 const handleRegenerateThreadTitle = props.onRegenerateThreadTitle;
418 const handleRenameThread = props.onRenameThread;
419 const handleDeleteThread = props.onDeleteThread;
420 const handleUnsettleThread = props.onUnsettleThread;
421 const [settledVisibleCount, setSettledVisibleCount] = useState(
422 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
423 );
424 const settledResetKey = `${props.selectedEnvironmentId ?? "all"}:${v2ProjectScopeKey ?? "all"}:${props.searchQuery.trim()}`;
425 const [lastSettledResetKey, setLastSettledResetKey] = useState(settledResetKey);
426 if (lastSettledResetKey !== settledResetKey) {
427 setLastSettledResetKey(settledResetKey);
428 setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
429 }
430 const showMoreSettled = () =>
431 setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT);
432 const {
433 loaded: shelfPreferencesLoaded,
434 settledShelfExpanded,
435 snoozedShelfExpanded,
436 workingShelfEnabled,
437 workingShelfExpanded,
438 toggleSettledShelf,
439 toggleSnoozedShelf,
440 toggleWorkingShelf,
441 } = useThreadListV2ShelfPreferences();
442 const now = useThreadListNow(props.threads);
443 const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
444 const {
445 providersByEnvironmentId,
446 machineByEnvironmentId,
447 settlementEnvironmentIds,
448 snoozeEnvironmentIds,
449 snoozePresetsByEnvironmentId,
450 pinningEnvironmentIds,
451 autoSettleOptOutEnvironmentIds,
452 pinReorderEnvironmentIds,
453 activeReorderEnvironmentIds,
454 titleRegenerationEnvironmentIds,
455 } = listEnvironments;
456 const resolveProviderInstance = useThreadRowProviderInstanceResolver(providersByEnvironmentId);
457 const pendingOrder = usePendingThreadOrder();
458 const {
459 layout: threadListV2Layout,
460 items: threadListV2Items,
461 contentOnlyThreadKeys,
462 olderSettledShelf,
463 } = useThreadListV2({
464 threads: props.threads,
465 pendingTasks: props.pendingTasks,
466 environmentId: props.selectedEnvironmentId,
467 projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
468 searchQuery: props.searchQuery,
469 searchMatches: threadSearchMatchByKey,
470 settlementEnvironmentIds,
471 snoozeEnvironmentIds,
472 pinReorderEnvironmentIds,
473 activeReorderEnvironmentIds,
474 queuedThreadKeys,
475 settledLimit: settledVisibleCount,
476 now,
477 pendingOrder,
478 shelfPreferencesLoaded,
479 workingShelfEnabled,
480 workingShelfExpanded,
481 snoozedShelfExpanded,
482 settledShelfExpanded,
483 selectedThreadKey,
484 });
485 // Called as `props.onSelectThread(...)`, the compiler would cache this handler on the whole
486 // props object, which is new on every render of Home's parent.
487 const { onSelectThread } = props;
488 // A row listed for a message match opens the thread at that message, by
489 // tap or by shortcut.
490 const selectThread = (thread: EnvironmentThreadShell) => {
491 const key = threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id });
492 const messageId = contentOnlyThreadKeys.has(key)
493 ? threadSearchMatchByKey.get(key)?.messageId
494 : undefined;
495 if (messageId) {
496 requestThreadMessageJump(scopedThreadKey(thread.environmentId, thread.id), messageId);
497 }
498 onSelectThread(thread);
499 };
500 useThreadJumpShortcuts(threadListV2Items, selectThread);
501 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reads the list's visible range after commit to enable swipe gestures on those rows
502 useEffect(() => {
503 if (swipeEnabled) activateVisibleRows(threadListV2Items);
504 }, [activateVisibleRows, swipeEnabled, threadListV2Items]);
505
506 const renderV2Item = ({ item }: { readonly item: ThreadListV2ListItem }) => {
507 if (item.type === "v2-pending") {
508 const pendingScopeKey = scopedProjectKey(
509 item.pendingTask.environmentId,
510 item.pendingTask.projectId,
511 );
512 return (
513 <ThreadListV2PendingRow
514 pane={sidebarSurface ? "sidebar" : "screen"}
515 pendingTask={item.pendingTask}
516 selected={
517 activeNewTask?.pendingKey === item.pendingTask.key ||
518 (item.pendingTask.kind === "pending" &&
519 scopedThreadKey(item.pendingTask.environmentId, item.pendingTask.message.threadId) ===
520 selectedThreadKey)
521 }
522 project={projectByKey.get(pendingScopeKey) ?? null}
523 projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}
524 environmentLabel={
525 Object.keys(props.savedConnectionsById).length > 1
526 ? (props.savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ??
527 null)
528 : null
529 }
530 environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
531 showPendingDivider={item.showPendingDivider}
532 showTrailingDivider={item.showTrailingDivider}
533 onSelectPendingTask={props.onSelectPendingTask}
534 onDeletePendingTask={props.onDeletePendingTask}
535 fullSwipeWidth={fullSwipeWidth}
536 onSwipeableClose={handleSwipeableClose}
537 onSwipeableWillOpen={handleSwipeableWillOpen}
538 simultaneousSwipeGesture={homeScrollGesture}
539 activationKey={item.key}
540 />
541 );
542 }
543 if (item.type === "v2-working-shelf") {
544 return (
545 <ThreadListV2WorkingShelfHeader
546 count={item.count}
547 disabled={item.disabled}
548 expanded={item.expanded}
549 onToggle={toggleWorkingShelf}
550 />
551 );
552 }
553 if (item.type === "v2-snoozed-shelf") {
554 return (
555 <ThreadListV2SnoozedShelfHeader
556 count={item.count}
557 disabled={item.disabled}
558 expanded={item.expanded}
559 onToggle={toggleSnoozedShelf}
560 />
561 );
562 }
563 if (item.type === "v2-settled-shelf") {
564 return (
565 <ThreadListV2SettledShelfHeader
566 count={item.count}
567 disabled={item.disabled}
568 expanded={item.expanded}
569 onToggle={toggleSettledShelf}
570 />
571 );
572 }
573 const thread = item.item.thread;
574 return (
575 <ThreadListV2Row
576 pane={sidebarSurface ? "sidebar" : "screen"}
577 selected={scopedThreadKey(thread.environmentId, thread.id) === selectedThreadKey}
578 fullSwipeWidth={fullSwipeWidth}
579 onNewThreadOnBranch={props.onNewThreadOnBranch}
580 thread={thread}
581 variant={item.item.variant}
582 hasQueuedMessages={item.hasQueuedMessages}
583 snoozed={item.item.snoozed}
584 pinned={item.item.pinned}
585 wokeAt={item.item.wokeAt}
586 snoozePresetMinute={item.snoozePresetMinute ?? ""}
587 snoozeWakeLabelText={item.snoozeWakeLabelText}
588 timeLabel={item.timeLabel}
589 showTrailingDivider={item.showTrailingDivider}
590 project={projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null}
591 providerInstance={resolveProviderInstance(thread)}
592 providers={providersByEnvironmentId.get(thread.environmentId)}
593 environmentLabel={
594 Object.keys(props.savedConnectionsById).length > 1
595 ? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
596 : null
597 }
598 environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
599 searchMatch={
600 // Only rows listed for their messages show one and open at it.
601 contentOnlyThreadKeys.has(
602 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
603 )
604 ? threadSearchMatchByKey.get(
605 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
606 )
607 : undefined
608 }
609 searchQuery={threadSearch.query}
610 onSelectThread={selectThread}
611 onOpenThreadPullRequests={handleOpenThreadPullRequests}
612 onDeleteThread={handleDeleteThread}
613 onArchiveThread={props.onArchiveThread}
614 onRenameThread={handleRenameThread}
615 onRegenerateThreadTitle={handleRegenerateThreadTitle}
616 titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
617 settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
618 onSettleThread={handleSettleThread}
619 snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
620 snoozePresets={snoozePresetsByEnvironmentId.get(thread.environmentId)}
621 pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
622 autoSettleOptOutSupported={autoSettleOptOutEnvironmentIds.has(thread.environmentId)}
623 reorderSupported={
624 item.item.pinned
625 ? pinReorderEnvironmentIds.has(thread.environmentId)
626 : !workingShelfEnabled && activeReorderEnvironmentIds.has(thread.environmentId)
627 }
628 canMoveUp={item.canMoveUp}
629 canMoveDown={item.canMoveDown}
630 onSnoozeThread={handleSnoozeThread}
631 onUnsnoozeThread={handleUnsnoozeThread}
632 onUnsettleThread={handleUnsettleThread}
633 onPinThread={handlePinThread}
634 onUnpinThread={handleUnpinThread}
635 onSetThreadAutoSettle={handleSetThreadAutoSettle}
636 onMoveThread={handleMoveThread}
637 onSwipeableClose={handleSwipeableClose}
638 onSwipeableWillOpen={handleSwipeableWillOpen}
639 simultaneousSwipeGesture={homeScrollGesture}
640 activationKey={item.key}
641 />
642 );
643 };
644 const v2KeyExtractor = (item: ThreadListV2ListItem) => item.key;
645
646 // extraData changes invalidate every visible row; put the minute clock on items to limit updates.
647 const v2ExtraData = {
648 activeNewTask,
649 projectByKey,
650 projectTitleByProjectKey: v2ProjectTitleByProjectKey,
651 listEnvironments,
652 savedConnectionsById: props.savedConnectionsById,
653 searchQuery: props.searchQuery,
654 selectedThreadKey,
655 threadSearchMatchByKey,
656 workingShelfEnabled,
657 };
658
659 const hasAnyThreads =
660 props.threads.some((thread) => thread.archivedAt === null) ||
661 props.pendingTasks.length > 0 ||
662 threadListV2Layout.settledCount > 0;
663 const selectedEnvironmentLabel =
664 props.selectedEnvironmentId === null
665 ? null
666 : (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
667 "this environment");
668 const emptyState = deriveEmptyState({
669 catalogState: props.catalogState,
670 projectCount: props.projects.length,
671 });
672
673 if (!hasAnyThreads) {
674 return (
675 <View className={containerClassName}>
676 <ScreenContent surface={sidebarSurface ? "drawer" : "screen"}>
677 <View
678 className={cn(
679 "flex-1 items-center justify-center px-8",
680 Platform.OS !== "android" && contentBackground,
681 )}
682 style={{
683 paddingBottom:
684 Platform.OS === "ios" ? iosBottomClearance : Math.max(insets.bottom, 24),
685 paddingTop: NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 72 : 0,
686 paddingLeft: 32 + (contentSideInsets?.left ?? 0),
687 paddingRight: 32 + (contentSideInsets?.right ?? 0),
688 }}
689 >
690 <View className="w-full max-w-[430px]">
691 <EmptyState
692 title={emptyState.title}
693 detail={emptyState.detail}
694 actionLabel={
695 !props.catalogState.hasReadyEnvironment ? "Add environment" : undefined
696 }
697 onAction={
698 !props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined
699 }
700 action={
701 Platform.OS === "android" && !props.catalogState.hasReadyEnvironment ? (
702 <FloatingActionButton
703 label="Add environment"
704 icon="plus"
705 variant="extended"
706 tone="primary"
707 onPress={props.onAddConnection}
708 />
709 ) : undefined
710 }
711 variant="plain"
712 />
713 {emptyState.loading ? (
714 <View className="mt-4 items-center">
715 <AppActivityIndicator colorClassName="accent-icon-muted" />
716 </View>
717 ) : null}
718 </View>
719 </View>
720 </ScreenContent>
721 </View>
722 );
723 }
724
725 const listHeader = Platform.OS === "ios" ? undefined : <HomeTopContentSpacer />;
726
727 const v2ListHeader = (
728 <>
729 {listHeader}
730 {Platform.OS === "ios" && workspace ? (
731 <ThreadListFilters
732 gutter={sidebarSurface ? 8 : 0}
733 environments={props.environments}
734 projects={pickableProjectGroups(projectScopes).map((scope) => ({
735 key: scope.key,
736 label: scope.title,
737 }))}
738 selectedEnvironmentId={props.selectedEnvironmentId}
739 selectedProjectKey={props.selectedProjectKey}
740 onEnvironmentChange={props.onEnvironmentChange}
741 onProjectChange={props.onProjectChange}
742 />
743 ) : null}
744 </>
745 );
746
747 const v2ListEmpty =
748 hasSearchQuery && threadSearch.isPending ? undefined : hasSearchQuery ? (
749 <EmptyState
750 title="No results"
751 detail={`No threads matching "${props.searchQuery}".`}
752 variant={Platform.OS === "android" ? "plain" : undefined}
753 />
754 ) : v2ScopedProjectGroup !== null ? (
755 <EmptyState
756 title={`No threads in ${v2ScopedProjectGroup.title}`}
757 detail="Choose another project or create a new task."
758 variant={Platform.OS === "android" ? "plain" : undefined}
759 />
760 ) : selectedEnvironmentLabel ? (
761 <EmptyState
762 title={`No threads in ${selectedEnvironmentLabel}`}
763 detail="Choose another environment or create a new task."
764 variant={Platform.OS === "android" ? "plain" : undefined}
765 />
766 ) : (
767 <EmptyState
768 title="No threads yet"
769 detail="Create a task to start a new coding session."
770 variant={Platform.OS === "android" ? "plain" : undefined}
771 />
772 );
773
774 if (Platform.OS === "android" && threadListV2Items.length === 0) {
775 return (
776 <ScreenContent surface="screen">
777 <View
778 className="flex-1 items-center justify-center px-4"
779 style={{ paddingBottom: insets.bottom }}
780 >
781 {v2ListEmpty}
782 </View>
783 </ScreenContent>
784 );
785 }
786
787 return (
788 <View className={containerClassName}>
789 <ScreenContent surface="screen">
790 <View className={cn("flex-1", Platform.OS !== "android" && contentBackground)}>
791 <SwipeableScrollGateProvider enabled={swipeEnabled} activation={swipeRowActivation}>
792 <GestureDetector gesture={homeScrollGesture}>
793 <AnimatedLegendList
794 itemLayoutAnimation={sidebarSurface ? THREAD_SIDEBAR_ROW_LAYOUT : undefined}
795 ref={listRef}
796 onLoad={() => activateVisibleRows(threadListV2Items)}
797 onTouchStart={(event) => trackListTouches(event, true)}
798 onTouchEnd={(event) => trackListTouches(event, false)}
799 onTouchCancel={(event) => trackListTouches(event, false)}
800 renderScrollComponent={Platform.OS === "ios" ? renderHomeScrollView : undefined}
801 data={threadListV2Items}
802 renderItem={renderV2Item}
803 keyExtractor={v2KeyExtractor}
804 getItemType={(item) => item.type}
805 itemsAreEqual={threadListV2ListItemsAreEqual}
806 estimatedItemSize={ESTIMATED_THREAD_LIST_V2_ROW_HEIGHT}
807 drawDistance={THREAD_LIST_V2_DRAW_DISTANCE}
808 recycleItems
809 extraData={v2ExtraData}
810 ListHeaderComponent={v2ListHeader}
811 ListFooterComponent={
812 settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? (
813 <ThreadListV2ShowMoreRow
814 hiddenCount={threadListV2Layout.hiddenSettledCount}
815 {...(olderSettledShelf.loading
816 ? { state: "loading" as const }
817 : olderSettledShelf.failed
818 ? { state: "failed" as const }
819 : {})}
820 onPress={() => {
821 olderSettledShelf.retry();
822 showMoreSettled();
823 }}
824 />
825 ) : null
826 }
827 ListEmptyComponent={v2ListEmpty}
828 style={{ flex: 1 }}
829 automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
830 // UIKit owns the bar's inset, so a minimizing bar and a resized column move
831 // the list in the same frame as the bar.
832 contentInsetAdjustmentBehavior="automatic"
833 contentInsetStartAdjustment={Platform.OS === "ios" ? insets.top : 0}
834 // RN scrollTo clamps against raw insets and ignores the automatic bar inset.
835 scrollToOverflowEnabled
836 initialScrollOffset={
837 initialScrollOffset > 0
838 ? initialScrollOffset - (Platform.OS === "ios" ? insets.top : 0)
839 : undefined
840 }
841 showsVerticalScrollIndicator={false}
842 keyboardDismissMode="on-drag"
843 keyboardShouldPersistTaps="handled"
844 {...scrollGateHandlers}
845 scrollEventThrottle={16}
846 contentContainerStyle={{
847 paddingLeft:
848 (contentSideInsets?.left ?? 0) + (sidebarSurface ? 8 : 0) + androidListGutter,
849 paddingRight:
850 (contentSideInsets?.right ?? 0) + (sidebarSurface ? 8 : 0) + androidListGutter,
851 paddingBottom:
852 Platform.OS === "ios"
853 ? iosBottomClearance - (columnMetrics?.safeArea.bottom ?? insets.bottom)
854 : (workspace?.bottomClearance ??
855 Math.max(insets.bottom, 16) +
856 (Platform.OS === "android" ? fabClearance : 88)),
857 }}
858 />
859 </GestureDetector>
860 </SwipeableScrollGateProvider>
861 </View>
862 </ScreenContent>
863 </View>
864 );
865}