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