Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

HomeScreen.tsx

906 lines36.3 KB

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