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