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