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

HomeScreen.tsx

911 lines36.6 KB

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