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 skip their swipe actions (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 wokeAt={item.item.wokeAt}
640 snoozePresetMinute={item.snoozePresetMinute ?? ""}
641 snoozeWakeLabelText={item.snoozeWakeLabelText}
642 timeLabel={item.timeLabel}
643 showTrailingDivider={item.showTrailingDivider}
644 project={projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null}
645 projectTitle={v2ProjectTitleByProjectKey.get(
646 scopedProjectKey(thread.environmentId, thread.projectId),
647 )}
648 providerInstance={resolveProviderInstance(thread)}
649 providers={providersByEnvironmentId.get(thread.environmentId)}
650 environmentLabel={
651 Object.keys(props.savedConnectionsById).length > 1
652 ? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
653 : null
654 }
655 environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
656 searchMatch={threadSearchMatchByKey.get(
657 threadSearchMatchKey({
658 environmentId: thread.environmentId,
659 threadId: thread.id,
660 }),
661 )}
662 searchQuery={props.searchQuery}
663 onSelectThread={props.onSelectThread}
664 onOpenThreadPullRequests={handleOpenThreadPullRequests}
665 onDeleteThread={handleDeleteThread}
666 onArchiveThread={props.onArchiveThread}
667 onRenameThread={handleRenameThread}
668 onRegenerateThreadTitle={handleRegenerateThreadTitle}
669 titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
670 settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
671 onSettleThread={handleSettleThread}
672 snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
673 pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
674 autoSettleOptOutSupported={autoSettleOptOutEnvironmentIds.has(thread.environmentId)}
675 reorderSupported={
676 item.item.pinned
677 ? pinReorderEnvironmentIds.has(thread.environmentId)
678 : !workingShelfEnabled && activeReorderEnvironmentIds.has(thread.environmentId)
679 }
680 canMoveUp={item.canMoveUp}
681 canMoveDown={item.canMoveDown}
682 onSnoozeThread={handleSnoozeThread}
683 onUnsnoozeThread={handleUnsnoozeThread}
684 onUnsettleThread={handleUnsettleThread}
685 onPinThread={handlePinThread}
686 onUnpinThread={handleUnpinThread}
687 onSetThreadAutoSettle={handleSetThreadAutoSettle}
688 onMoveThread={handleMoveThread}
689 onSwipeableClose={handleSwipeableClose}
690 onSwipeableWillOpen={handleSwipeableWillOpen}
691 simultaneousSwipeGesture={homeScrollGesture}
692 activationKey={item.key}
693 />
694 );
695 };
696 const v2KeyExtractor = (item: ThreadListV2ListItem) => item.key;
697
698 // FlatList/LegendList treat a changed extraData identity as "re-render every
699 // visible row", so an inline object literal would invalidate all rows on
700 // every HomeScreen render — and the minute clock must stay out of it for
701 // the same reason: the clock text is precomputed per item instead.
702 const v2ExtraData = {
703 projectByKey,
704 projectTitleByProjectKey: v2ProjectTitleByProjectKey,
705 listEnvironments,
706 savedConnectionsById: props.savedConnectionsById,
707 searchQuery: props.searchQuery,
708 selectedThreadKey,
709 threadSearchMatchByKey,
710 workingShelfEnabled,
711 };
712
713 const hasAnyThreads =
714 props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
715 const selectedEnvironmentLabel =
716 props.selectedEnvironmentId === null
717 ? null
718 : (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
719 "this environment");
720 const emptyState = deriveEmptyState({
721 catalogState: props.catalogState,
722 projectCount: props.projects.length,
723 });
724
725 if (!hasAnyThreads) {
726 return (
727 <View className={containerClassName}>
728 <View
729 className={cn(
730 "flex-1 items-center justify-center px-8",
731 contentBackground,
732 Platform.OS === "android" && "overflow-hidden rounded-t-[28px]",
733 )}
734 style={{
735 paddingBottom: Platform.OS === "ios" ? iosBottomClearance : Math.max(insets.bottom, 24),
736 paddingTop: NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 72 : 0,
737 paddingLeft: 32 + (contentSideInsets?.left ?? 0),
738 paddingRight: 32 + (contentSideInsets?.right ?? 0),
739 }}
740 >
741 <View className="w-full max-w-[430px]">
742 <EmptyState
743 title={emptyState.title}
744 detail={emptyState.detail}
745 actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
746 onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
747 action={
748 Platform.OS === "android" && !props.catalogState.hasReadyEnvironment ? (
749 <FloatingActionButton
750 label="Add environment"
751 icon="plus"
752 variant="extended"
753 tone="primary"
754 onPress={props.onAddConnection}
755 />
756 ) : undefined
757 }
758 variant="plain"
759 />
760 {emptyState.loading ? (
761 <View className="mt-4 items-center">
762 <AppActivityIndicator colorClassName="accent-icon-muted" />
763 </View>
764 ) : null}
765 </View>
766 </View>
767 </View>
768 );
769 }
770
771 const listHeader = Platform.OS === "ios" ? undefined : <HomeTopContentSpacer />;
772
773 const v2ListHeader = (
774 <>
775 {listHeader}
776 {Platform.OS === "ios" && workspace ? (
777 <ThreadListFilters
778 environments={props.environments}
779 projects={projectScopes.map((scope) => ({ key: scope.key, label: scope.title }))}
780 selectedEnvironmentId={props.selectedEnvironmentId}
781 selectedProjectKey={props.selectedProjectKey}
782 onEnvironmentChange={props.onEnvironmentChange}
783 onProjectChange={props.onProjectChange}
784 />
785 ) : null}
786 </>
787 );
788
789 const v2ListEmpty =
790 hasSearchQuery && threadSearch.isPending ? undefined : hasSearchQuery ? (
791 <EmptyState
792 title="No results"
793 detail={`No threads matching "${props.searchQuery}".`}
794 variant={Platform.OS === "android" ? "plain" : undefined}
795 />
796 ) : v2ScopedProjectGroup !== null ? (
797 <EmptyState
798 title={`No threads in ${v2ScopedProjectGroup.title}`}
799 detail="Choose another project or create a new task."
800 variant={Platform.OS === "android" ? "plain" : undefined}
801 />
802 ) : selectedEnvironmentLabel ? (
803 <EmptyState
804 title={`No threads in ${selectedEnvironmentLabel}`}
805 detail="Choose another environment or create a new task."
806 variant={Platform.OS === "android" ? "plain" : undefined}
807 />
808 ) : (
809 <EmptyState
810 title="No threads yet"
811 detail="Create a task to start a new coding session."
812 variant={Platform.OS === "android" ? "plain" : undefined}
813 />
814 );
815
816 if (Platform.OS === "android" && threadListV2Items.length === 0) {
817 return (
818 <View className="flex-1 bg-header">
819 <View
820 className="flex-1 items-center justify-center overflow-hidden rounded-t-[28px] bg-screen px-4"
821 style={{ paddingBottom: insets.bottom }}
822 >
823 {v2ListEmpty}
824 </View>
825 </View>
826 );
827 }
828
829 return (
830 <View className={containerClassName}>
831 <View
832 className={
833 Platform.OS === "android"
834 ? "flex-1 overflow-hidden rounded-t-[28px] bg-screen"
835 : cn("flex-1", contentBackground)
836 }
837 >
838 <SwipeableScrollGateProvider enabled={swipeEnabled} activation={swipeRowActivation}>
839 <GestureDetector gesture={homeScrollGesture}>
840 <LegendList
841 ref={listRef}
842 onLoad={() => activateVisibleRows(threadListV2Items)}
843 onTouchStart={(event) => trackListTouches(event, true)}
844 onTouchEnd={(event) => trackListTouches(event, false)}
845 onTouchCancel={(event) => trackListTouches(event, false)}
846 renderScrollComponent={Platform.OS === "ios" ? renderHomeScrollView : undefined}
847 data={threadListV2Items}
848 renderItem={renderV2Item}
849 keyExtractor={v2KeyExtractor}
850 getItemType={(item) => item.type}
851 itemsAreEqual={threadListV2ListItemsAreEqual}
852 estimatedItemSize={ESTIMATED_THREAD_LIST_V2_ROW_HEIGHT}
853 drawDistance={THREAD_LIST_V2_DRAW_DISTANCE}
854 recycleItems
855 extraData={v2ExtraData}
856 ListHeaderComponent={v2ListHeader}
857 ListFooterComponent={
858 settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? (
859 <ThreadListV2ShowMoreRow
860 hiddenCount={threadListV2Layout.hiddenSettledCount}
861 onPress={showMoreSettled}
862 />
863 ) : null
864 }
865 ListEmptyComponent={v2ListEmpty}
866 style={{ flex: 1 }}
867 automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
868 contentInsetAdjustmentBehavior="never"
869 contentInset={Platform.OS === "ios" ? { top: insets.top } : undefined}
870 contentInsetStartAdjustment={Platform.OS === "ios" ? insets.top : 0}
871 initialScrollOffset={
872 initialScrollOffset > 0
873 ? initialScrollOffset - (Platform.OS === "ios" ? insets.top : 0)
874 : undefined
875 }
876 showsVerticalScrollIndicator={false}
877 keyboardDismissMode="on-drag"
878 keyboardShouldPersistTaps="handled"
879 {...scrollGateHandlers}
880 scrollEventThrottle={16}
881 contentContainerStyle={{
882 paddingLeft:
883 (contentSideInsets?.left ?? 0) + (primaryColumn ? 8 : 0) + androidListGutter,
884 paddingRight:
885 (contentSideInsets?.right ?? 0) + (primaryColumn ? 8 : 0) + androidListGutter,
886 paddingBottom:
887 Platform.OS === "ios"
888 ? iosBottomClearance
889 : (workspace?.bottomClearance ??
890 Math.max(insets.bottom, 16) +
891 (Platform.OS === "android" ? fabClearance : 88)),
892 }}
893 />
894 </GestureDetector>
895 </SwipeableScrollGateProvider>
896 </View>
897 </View>
898 );
899}