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