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