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 { useWorkspaceListEmptyTopInset } from "../layout/workspace/workspace-list-insets";
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 "../layout/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 "../layout/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 emptyTopInset = useWorkspaceListEmptyTopInset();
266 const { fabClearance } = useAndroidControlSizing();
267 const screenMetrics = useNativeLayoutMetrics();
268 const contentSideInsets = usesNativeWorkspaceColumns
269 ? (columnMetrics ?? screenMetrics)?.safeArea
270 : undefined;
271 // Wide Android lists need reading-width gutters to clear edges and camera cutouts.
272 const { width: windowWidth } = useWindowDimensions();
273 const androidListGutter =
274 Platform.OS === "android"
275 ? deriveCenteredContentHorizontalPadding({
276 viewportWidth: windowWidth,
277 maxContentWidth: ANDROID_READING_MAX_WIDTH,
278 minimumPadding: 0,
279 })
280 : 0;
281 const iosBottomClearance = Math.max(
282 columnMetrics?.safeArea.bottom ?? insets.bottom,
283 24,
284 workspace?.bottomClearance ?? 0,
285 );
286 const searchEnvironmentIds =
287 props.selectedEnvironmentId === null
288 ? props.environments
289 .filter((environment) => environment.connectionState === "connected")
290 .map((environment) => environment.environmentId)
291 : props.environments.some(
292 (environment) =>
293 environment.environmentId === props.selectedEnvironmentId &&
294 environment.connectionState === "connected",
295 )
296 ? [props.selectedEnvironmentId]
297 : [];
298 const handleSwipeableWillOpen = (methods: SwipeableMethods) => {
299 if (openSwipeableRef.current !== methods) {
300 openSwipeableRef.current?.close();
301 openSwipeableRef.current = methods;
302 }
303 };
304
305 const handleSwipeableClose = (methods: SwipeableMethods) => {
306 if (openSwipeableRef.current === methods) {
307 openSwipeableRef.current = null;
308 }
309 };
310
311 const handleScrollBeginDrag = () => {
312 openSwipeableRef.current?.close();
313 };
314 const openThreadPullRequests = useOpenThreadPullRequests();
315 const handleOpenThreadPullRequests = (
316 thread: EnvironmentThreadShell,
317 pr: ThreadPrPresentation,
318 ) => {
319 openSwipeableRef.current?.close();
320 openThreadPullRequests(thread, pr);
321 };
322 const onFabScroll = useFabScroll();
323 const listRef = useRef<LegendListRef>(null);
324 const searchMode = workspace?.state.tabs.threads.searchMode;
325 const restoredOffset = workspace?.state.tabs.threads.scrollOffset;
326 useSearchScrollRestoration(searchMode, () => {
327 if (restoredOffset === undefined) return;
328 void listRef.current?.scrollToOffset({
329 offset: restoredOffset - (Platform.OS === "ios" ? insets.top : 0),
330 animated: false,
331 });
332 });
333 const swipeRowActivation = createSwipeRowActivation();
334 const activateVisibleRows = (rows: ReadonlyArray<ThreadListV2ListItem>) => {
335 const state = listRef.current?.getState();
336 if (state === undefined || !(state.end >= 0)) return;
337 swipeRowActivation.activate(
338 rows.slice(Math.max(0, state.start - 2), state.end + 3).map((row) => row.key),
339 );
340 };
341 // Status-bar, accessibility and programmatic scrolls bypass the gate; activate visible rows after settling.
342 const activationTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
343 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the row activation timer on unmount
344 useEffect(() => () => clearTimeout(activationTimerRef.current), []);
345 const handleListScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
346 onFabScroll?.(event);
347 if (workspace)
348 workspace.recordScrollOffset(
349 "threads",
350 Math.max(0, event.nativeEvent.contentOffset.y + (Platform.OS === "ios" ? insets.top : 0)),
351 );
352 clearTimeout(activationTimerRef.current);
353 activationTimerRef.current = setTimeout(
354 () => activateVisibleRows(listRef.current?.getState().data ?? []),
355 200,
356 );
357 };
358 const trackListTouches = (event: GestureResponderEvent, started: boolean) => {
359 const { changedTouches, touches } = event.nativeEvent;
360 swipeRowActivation.trackTouches(
361 started ? changedTouches.map((touch) => String(touch.identifier)) : [],
362 touches.map((touch) => String(touch.identifier)),
363 );
364 };
365 const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
366 onScroll: handleListScroll,
367 onScrollBeginDrag: handleScrollBeginDrag,
368 });
369
370 const { projects, selectedEnvironmentId, projectGroupingMode } = props;
371 const projectScopes = useMemo(
372 () =>
373 buildHomeProjectScopes({
374 projects,
375 environmentId: selectedEnvironmentId,
376 projectGroupingMode,
377 }),
378 [projects, selectedEnvironmentId, projectGroupingMode],
379 );
380 const hasSearchQuery = props.searchQuery.trim().length > 0;
381 const projectByKey = (() => {
382 const map = new Map<string, EnvironmentProject>();
383 for (const project of props.projects) {
384 map.set(scopedProjectKey(project.environmentId, project.id), project);
385 }
386 return map;
387 })();
388
389 const v2ProjectScopeKey = props.selectedProjectKey;
390 // An archived project's filter reads as all projects, matching the filter menu.
391 const v2ScopedProjectGroup = findHomeProjectScope(
392 pickableProjectGroups(projectScopes),
393 v2ProjectScopeKey,
394 );
395 const threadSearch = useThreadSearch(
396 searchEnvironmentIds,
397 props.searchQuery,
398 v2ScopedProjectGroup === null
399 ? {}
400 : { projectIds: v2ScopedProjectGroup.projectRefs.map((ref) => ref.projectId) },
401 );
402 const threadSearchMatchByKey = useThreadListSearchMatches(props.threads, threadSearch);
403 const v2ProjectTitleByProjectKey = new Map(
404 projectScopes.flatMap((scope) =>
405 scope.projectRefs.map(
406 (projectRef) =>
407 [scopedProjectKey(projectRef.environmentId, projectRef.projectId), scope.title] as const,
408 ),
409 ),
410 );
411 const handleSettleThread = props.onSettleThread;
412 const handleSnoozeThread = props.onSnoozeThread;
413 const handleUnsnoozeThread = props.onUnsnoozeThread;
414 const handlePinThread = props.onPinThread;
415 const handleMoveThread = props.onMoveThread;
416 const handleUnpinThread = props.onUnpinThread;
417 const handleSetThreadAutoSettle = props.onSetThreadAutoSettle;
418 const handleRegenerateThreadTitle = props.onRegenerateThreadTitle;
419 const handleRenameThread = props.onRenameThread;
420 const handleDeleteThread = props.onDeleteThread;
421 const handleUnsettleThread = props.onUnsettleThread;
422 const [settledVisibleCount, setSettledVisibleCount] = useState(
423 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
424 );
425 const settledResetKey = `${props.selectedEnvironmentId ?? "all"}:${v2ProjectScopeKey ?? "all"}:${props.searchQuery.trim()}`;
426 const [lastSettledResetKey, setLastSettledResetKey] = useState(settledResetKey);
427 if (lastSettledResetKey !== settledResetKey) {
428 setLastSettledResetKey(settledResetKey);
429 setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
430 }
431 const showMoreSettled = () =>
432 setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT);
433 const {
434 loaded: shelfPreferencesLoaded,
435 settledShelfExpanded,
436 snoozedShelfExpanded,
437 workingShelfEnabled,
438 workingShelfExpanded,
439 toggleSettledShelf,
440 toggleSnoozedShelf,
441 toggleWorkingShelf,
442 } = useThreadListV2ShelfPreferences();
443 const now = useThreadListNow(props.threads);
444 const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
445 const {
446 providersByEnvironmentId,
447 machineByEnvironmentId,
448 settlementEnvironmentIds,
449 snoozeEnvironmentIds,
450 snoozePresetsByEnvironmentId,
451 pinningEnvironmentIds,
452 autoSettleOptOutEnvironmentIds,
453 pinReorderEnvironmentIds,
454 activeReorderEnvironmentIds,
455 titleRegenerationEnvironmentIds,
456 } = listEnvironments;
457 const resolveProviderInstance = useThreadRowProviderInstanceResolver(providersByEnvironmentId);
458 const pendingOrder = usePendingThreadOrder();
459 const {
460 layout: threadListV2Layout,
461 items: threadListV2Items,
462 contentOnlyThreadKeys,
463 olderSettledShelf,
464 } = useThreadListV2({
465 threads: props.threads,
466 pendingTasks: props.pendingTasks,
467 environmentId: props.selectedEnvironmentId,
468 projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
469 searchQuery: props.searchQuery,
470 searchMatches: threadSearchMatchByKey,
471 settlementEnvironmentIds,
472 snoozeEnvironmentIds,
473 pinReorderEnvironmentIds,
474 activeReorderEnvironmentIds,
475 queuedThreadKeys,
476 settledLimit: settledVisibleCount,
477 now,
478 pendingOrder,
479 shelfPreferencesLoaded,
480 workingShelfEnabled,
481 workingShelfExpanded,
482 snoozedShelfExpanded,
483 settledShelfExpanded,
484 selectedThreadKey,
485 });
486 // Called as `props.onSelectThread(...)`, the compiler would cache this handler on the whole
487 // props object, which is new on every render of Home's parent.
488 const { onSelectThread } = props;
489 // A row listed for a message match opens the thread at that message, by
490 // tap or by shortcut.
491 const selectThread = (thread: EnvironmentThreadShell) => {
492 const key = threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id });
493 const messageId = contentOnlyThreadKeys.has(key)
494 ? threadSearchMatchByKey.get(key)?.messageId
495 : undefined;
496 if (messageId) {
497 requestThreadMessageJump(scopedThreadKey(thread.environmentId, thread.id), messageId);
498 }
499 onSelectThread(thread);
500 };
501 useThreadJumpShortcuts(threadListV2Items, selectThread);
502 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reads the list's visible range after commit to enable swipe gestures on those rows
503 useEffect(() => {
504 if (swipeEnabled) activateVisibleRows(threadListV2Items);
505 }, [activateVisibleRows, swipeEnabled, threadListV2Items]);
506
507 const renderV2Item = ({ item }: { readonly item: ThreadListV2ListItem }) => {
508 if (item.type === "v2-pending") {
509 const pendingScopeKey = scopedProjectKey(
510 item.pendingTask.environmentId,
511 item.pendingTask.projectId,
512 );
513 return (
514 <ThreadListV2PendingRow
515 pane={sidebarSurface ? "sidebar" : "screen"}
516 pendingTask={item.pendingTask}
517 selected={
518 activeNewTask?.pendingKey === item.pendingTask.key ||
519 (item.pendingTask.kind === "pending" &&
520 scopedThreadKey(item.pendingTask.environmentId, item.pendingTask.message.threadId) ===
521 selectedThreadKey)
522 }
523 project={projectByKey.get(pendingScopeKey) ?? null}
524 projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}
525 environmentLabel={
526 Object.keys(props.savedConnectionsById).length > 1
527 ? (props.savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ??
528 null)
529 : null
530 }
531 environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
532 showPendingDivider={item.showPendingDivider}
533 showTrailingDivider={item.showTrailingDivider}
534 onSelectPendingTask={props.onSelectPendingTask}
535 onDeletePendingTask={props.onDeletePendingTask}
536 fullSwipeWidth={fullSwipeWidth}
537 onSwipeableClose={handleSwipeableClose}
538 onSwipeableWillOpen={handleSwipeableWillOpen}
539 simultaneousSwipeGesture={homeScrollGesture}
540 activationKey={item.key}
541 />
542 );
543 }
544 if (item.type === "v2-working-shelf") {
545 return (
546 <ThreadListV2WorkingShelfHeader
547 count={item.count}
548 disabled={item.disabled}
549 expanded={item.expanded}
550 onToggle={toggleWorkingShelf}
551 />
552 );
553 }
554 if (item.type === "v2-snoozed-shelf") {
555 return (
556 <ThreadListV2SnoozedShelfHeader
557 count={item.count}
558 disabled={item.disabled}
559 expanded={item.expanded}
560 onToggle={toggleSnoozedShelf}
561 />
562 );
563 }
564 if (item.type === "v2-settled-shelf") {
565 return (
566 <ThreadListV2SettledShelfHeader
567 count={item.count}
568 disabled={item.disabled}
569 expanded={item.expanded}
570 onToggle={toggleSettledShelf}
571 />
572 );
573 }
574 const thread = item.item.thread;
575 return (
576 <ThreadListV2Row
577 pane={sidebarSurface ? "sidebar" : "screen"}
578 selected={scopedThreadKey(thread.environmentId, thread.id) === selectedThreadKey}
579 fullSwipeWidth={fullSwipeWidth}
580 onNewThreadOnBranch={props.onNewThreadOnBranch}
581 thread={thread}
582 variant={item.item.variant}
583 hasQueuedMessages={item.hasQueuedMessages}
584 snoozed={item.item.snoozed}
585 pinned={item.item.pinned}
586 wokeAt={item.item.wokeAt}
587 snoozePresetMinute={item.snoozePresetMinute ?? ""}
588 snoozeWakeLabelText={item.snoozeWakeLabelText}
589 timeLabel={item.timeLabel}
590 showTrailingDivider={item.showTrailingDivider}
591 project={projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null}
592 providerInstance={resolveProviderInstance(thread)}
593 providers={providersByEnvironmentId.get(thread.environmentId)}
594 environmentLabel={
595 Object.keys(props.savedConnectionsById).length > 1
596 ? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
597 : null
598 }
599 environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
600 searchMatch={
601 // Only rows listed for their messages show one and open at it.
602 contentOnlyThreadKeys.has(
603 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
604 )
605 ? threadSearchMatchByKey.get(
606 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
607 )
608 : undefined
609 }
610 searchQuery={threadSearch.query}
611 onSelectThread={selectThread}
612 onOpenThreadPullRequests={handleOpenThreadPullRequests}
613 onDeleteThread={handleDeleteThread}
614 onArchiveThread={props.onArchiveThread}
615 onRenameThread={handleRenameThread}
616 onRegenerateThreadTitle={handleRegenerateThreadTitle}
617 titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
618 settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
619 onSettleThread={handleSettleThread}
620 snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
621 snoozePresets={snoozePresetsByEnvironmentId.get(thread.environmentId)}
622 pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
623 autoSettleOptOutSupported={autoSettleOptOutEnvironmentIds.has(thread.environmentId)}
624 reorderSupported={
625 item.item.pinned
626 ? pinReorderEnvironmentIds.has(thread.environmentId)
627 : !workingShelfEnabled && activeReorderEnvironmentIds.has(thread.environmentId)
628 }
629 canMoveUp={item.canMoveUp}
630 canMoveDown={item.canMoveDown}
631 onSnoozeThread={handleSnoozeThread}
632 onUnsnoozeThread={handleUnsnoozeThread}
633 onUnsettleThread={handleUnsettleThread}
634 onPinThread={handlePinThread}
635 onUnpinThread={handleUnpinThread}
636 onSetThreadAutoSettle={handleSetThreadAutoSettle}
637 onMoveThread={handleMoveThread}
638 onSwipeableClose={handleSwipeableClose}
639 onSwipeableWillOpen={handleSwipeableWillOpen}
640 simultaneousSwipeGesture={homeScrollGesture}
641 activationKey={item.key}
642 />
643 );
644 };
645 const v2KeyExtractor = (item: ThreadListV2ListItem) => item.key;
646
647 // extraData changes invalidate every visible row; put the minute clock on items to limit updates.
648 const v2ExtraData = {
649 activeNewTask,
650 projectByKey,
651 projectTitleByProjectKey: v2ProjectTitleByProjectKey,
652 listEnvironments,
653 savedConnectionsById: props.savedConnectionsById,
654 searchQuery: props.searchQuery,
655 selectedThreadKey,
656 threadSearchMatchByKey,
657 workingShelfEnabled,
658 };
659
660 const hasAnyThreads =
661 props.threads.some((thread) => thread.archivedAt === null) ||
662 props.pendingTasks.length > 0 ||
663 threadListV2Layout.settledCount > 0;
664 const selectedEnvironmentLabel =
665 props.selectedEnvironmentId === null
666 ? null
667 : (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
668 "this environment");
669 const emptyState = deriveEmptyState({
670 catalogState: props.catalogState,
671 projectCount: props.projects.length,
672 });
673
674 if (!hasAnyThreads) {
675 return (
676 <View className={containerClassName}>
677 <ScreenContent surface={sidebarSurface ? "drawer" : "screen"}>
678 <View
679 className={cn(
680 "flex-1 items-center justify-center px-8",
681 Platform.OS !== "android" && contentBackground,
682 )}
683 style={{
684 paddingBottom:
685 Platform.OS === "ios" ? iosBottomClearance : Math.max(insets.bottom, 24),
686 paddingTop: emptyTopInset,
687 paddingLeft: 32 + (contentSideInsets?.left ?? 0),
688 paddingRight: 32 + (contentSideInsets?.right ?? 0),
689 }}
690 >
691 <View className="w-full max-w-[430px]">
692 <EmptyState
693 title={emptyState.title}
694 detail={emptyState.detail}
695 actionLabel={
696 !props.catalogState.hasReadyEnvironment ? "Add environment" : undefined
697 }
698 onAction={
699 !props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined
700 }
701 action={
702 Platform.OS === "android" && !props.catalogState.hasReadyEnvironment ? (
703 <FloatingActionButton
704 label="Add environment"
705 icon="plus"
706 variant="extended"
707 tone="primary"
708 onPress={props.onAddConnection}
709 />
710 ) : undefined
711 }
712 variant="plain"
713 />
714 {emptyState.loading ? (
715 <View className="mt-4 items-center">
716 <AppActivityIndicator colorClassName="accent-icon-muted" />
717 </View>
718 ) : null}
719 </View>
720 </View>
721 </ScreenContent>
722 </View>
723 );
724 }
725
726 const listHeader = Platform.OS === "ios" ? undefined : <HomeTopContentSpacer />;
727
728 const v2ListHeader = (
729 <>
730 {listHeader}
731 {Platform.OS === "ios" && workspace ? (
732 <ThreadListFilters
733 gutter={sidebarSurface ? 8 : 0}
734 environments={props.environments}
735 projects={pickableProjectGroups(projectScopes).map((scope) => ({
736 key: scope.key,
737 label: scope.title,
738 }))}
739 selectedEnvironmentId={props.selectedEnvironmentId}
740 selectedProjectKey={props.selectedProjectKey}
741 onEnvironmentChange={props.onEnvironmentChange}
742 onProjectChange={props.onProjectChange}
743 />
744 ) : null}
745 </>
746 );
747
748 const v2ListEmpty =
749 hasSearchQuery && threadSearch.isPending ? undefined : hasSearchQuery ? (
750 <EmptyState
751 title="No results"
752 detail={`No threads matching "${props.searchQuery}".`}
753 variant={Platform.OS === "android" ? "plain" : undefined}
754 />
755 ) : v2ScopedProjectGroup !== null ? (
756 <EmptyState
757 title={`No threads in ${v2ScopedProjectGroup.title}`}
758 detail="Choose another project or create a new task."
759 variant={Platform.OS === "android" ? "plain" : undefined}
760 />
761 ) : selectedEnvironmentLabel ? (
762 <EmptyState
763 title={`No threads in ${selectedEnvironmentLabel}`}
764 detail="Choose another environment or create a new task."
765 variant={Platform.OS === "android" ? "plain" : undefined}
766 />
767 ) : (
768 <EmptyState
769 title="No threads yet"
770 detail="Create a task to start a new coding session."
771 variant={Platform.OS === "android" ? "plain" : undefined}
772 />
773 );
774
775 if (Platform.OS === "android" && threadListV2Items.length === 0) {
776 return (
777 <ScreenContent surface="screen">
778 <View
779 className="flex-1 items-center justify-center px-4"
780 style={{ paddingBottom: insets.bottom }}
781 >
782 {v2ListEmpty}
783 </View>
784 </ScreenContent>
785 );
786 }
787
788 return (
789 <View className={containerClassName}>
790 <ScreenContent surface="screen">
791 <View className={cn("flex-1", Platform.OS !== "android" && contentBackground)}>
792 <SwipeableScrollGateProvider enabled={swipeEnabled} activation={swipeRowActivation}>
793 <GestureDetector gesture={homeScrollGesture}>
794 <AnimatedLegendList
795 itemLayoutAnimation={sidebarSurface ? THREAD_SIDEBAR_ROW_LAYOUT : undefined}
796 ref={listRef}
797 onLoad={() => activateVisibleRows(threadListV2Items)}
798 onTouchStart={(event) => trackListTouches(event, true)}
799 onTouchEnd={(event) => trackListTouches(event, false)}
800 onTouchCancel={(event) => trackListTouches(event, false)}
801 renderScrollComponent={renderHomeScrollView}
802 data={threadListV2Items}
803 renderItem={renderV2Item}
804 keyExtractor={v2KeyExtractor}
805 getItemType={(item) => item.type}
806 itemsAreEqual={threadListV2ListItemsAreEqual}
807 estimatedItemSize={ESTIMATED_THREAD_LIST_V2_ROW_HEIGHT}
808 drawDistance={THREAD_LIST_V2_DRAW_DISTANCE}
809 recycleItems
810 extraData={v2ExtraData}
811 ListHeaderComponent={v2ListHeader}
812 ListFooterComponent={
813 settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? (
814 <ThreadListV2ShowMoreRow
815 hiddenCount={threadListV2Layout.hiddenSettledCount}
816 {...(olderSettledShelf.loading
817 ? { state: "loading" as const }
818 : olderSettledShelf.failed
819 ? { state: "failed" as const }
820 : {})}
821 onPress={() => {
822 olderSettledShelf.retry();
823 showMoreSettled();
824 }}
825 />
826 ) : null
827 }
828 ListEmptyComponent={v2ListEmpty}
829 style={{ flex: 1 }}
830 automaticallyAdjustsScrollIndicatorInsets
831 // UIKit owns the bar's inset, so a minimizing bar and a resized column move
832 // the list in the same frame as the bar.
833 contentInsetAdjustmentBehavior="automatic"
834 contentInsetStartAdjustment={Platform.OS === "ios" ? insets.top : 0}
835 // RN scrollTo clamps against raw insets and ignores the automatic bar inset.
836 scrollToOverflowEnabled
837 initialScrollOffset={
838 initialScrollOffset > 0
839 ? initialScrollOffset - (Platform.OS === "ios" ? insets.top : 0)
840 : undefined
841 }
842 showsVerticalScrollIndicator={false}
843 keyboardDismissMode="on-drag"
844 keyboardShouldPersistTaps="handled"
845 {...scrollGateHandlers}
846 scrollEventThrottle={16}
847 contentContainerStyle={{
848 paddingLeft:
849 (contentSideInsets?.left ?? 0) + (sidebarSurface ? 8 : 0) + androidListGutter,
850 paddingRight:
851 (contentSideInsets?.right ?? 0) + (sidebarSurface ? 8 : 0) + androidListGutter,
852 paddingBottom:
853 Platform.OS === "ios"
854 ? iosBottomClearance - (columnMetrics?.safeArea.bottom ?? insets.bottom)
855 : (workspace?.bottomClearance ??
856 Math.max(insets.bottom, 16) +
857 (Platform.OS === "android" ? fabClearance : 88)),
858 }}
859 />
860 </GestureDetector>
861 </SwipeableScrollGateProvider>
862 </View>
863 </ScreenContent>
864 </View>
865 );
866}