Open History to see the last commit
1import { useAndroidControlSizing } from "../../components/useAndroidControlSizing";
2import type { ThreadMoveDestination } from "../threads/threadOrder";
3import { computeThreadMoveAvailability } from "../threads/threadOrder";
4import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
5import {
6 type EnvironmentProject,
7 type EnvironmentThreadShell,
8} from "@t3tools/client-runtime/state/shell";
9import {
10 threadSearchMatchKey,
11 type EnvironmentThreadSearchMatch,
12} 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 { useCallback, useEffect, useMemo, useRef, useState } from "react";
17import {
18 ActivityIndicator,
19 Platform,
20 View,
21 type GestureResponderEvent,
22 type NativeScrollEvent,
23 type NativeSyntheticEvent,
24} from "react-native";
25import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
26import { useSafeAreaInsets } from "react-native-safe-area-context";
27
28import { cn } from "../../lib/cn";
29import { EmptyState } from "../../components/EmptyState";
30import { MaterialFloatingActionButton } from "../../components/MaterialFloatingActionButton";
31import type { WorkspaceEnvironment, WorkspaceState } from "../../state/workspaceModel";
32import type { SavedRemoteConnection } from "../../lib/connection";
33import { scopedProjectKey } from "../../lib/scopedEntities";
34import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
35import { useThreadSearch } from "../../state/queries";
36import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts";
37import { usePendingThreadOrder } from "../../state/thread-order";
38import { threadListEnvironmentsAtom } from "../../state/server";
39import type { PendingNewTask } from "../../state/use-pending-new-tasks";
40import { useQueuedThreadKeys } from "../../state/use-thread-outbox";
41import {
42 ThreadListV2PendingRow,
43 ThreadListV2Row,
44 ThreadListV2SettledShelfHeader,
45 ThreadListV2ShowMoreRow,
46 ThreadListV2SnoozedShelfHeader,
47} from "../threads/thread-list-v2-items";
48import { useThreadRowProviderInstanceResolver } from "../threads/thread-provider-instance";
49import {
50 buildThreadListV2Items,
51 getThreadListV2OrderedSection,
52 buildThreadListV2ListItems,
53 threadListV2ListItemsAreEqual,
54 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
55 THREAD_LIST_V2_SETTLED_PAGE_COUNT,
56 type ThreadListV2ListItem,
57} from "../threads/threadListV2";
58import { useThreadListV2ShelfPreferences } from "../threads/use-thread-list-v2-shelf-preferences";
59import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
60import {
61 buildHomeProjectScopes,
62 sortHomeProjectScopes,
63 type HomeProjectSortOrder,
64} from "./homeThreadList";
65import { createSwipeRowActivation } from "./swipe-row-activation";
66import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
67import { useMaterialFabScroll } from "./MaterialFabScrollContext";
68
69/* ─── Types ──────────────────────────────────────────────────────────── */
70
71interface HomeScreenProps {
72 readonly projects: ReadonlyArray<EnvironmentProject>;
73 readonly threads: ReadonlyArray<EnvironmentThreadShell>;
74 readonly pendingTasks: ReadonlyArray<PendingNewTask>;
75 readonly catalogState: WorkspaceState;
76 readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
77 readonly environments: ReadonlyArray<
78 HomeListFilterMenuEnvironment & Pick<WorkspaceEnvironment, "connectionState">
79 >;
80 readonly searchQuery: string;
81 readonly selectedEnvironmentId: EnvironmentId | null;
82 readonly selectedProjectKey: string | null;
83 readonly projectSortOrder: HomeProjectSortOrder;
84 readonly projectGroupingMode: SidebarProjectGroupingMode;
85 readonly onSearchQueryChange: (query: string) => void;
86 readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
87 readonly onProjectChange: (projectKey: string | null) => void;
88 readonly onAddConnection: () => void;
89 readonly onOpenSettings: () => void;
90 readonly onStartNewTask: () => void;
91 readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
92 readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
93 readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
94 /** Resolves true iff the settle was dispatched and succeeded. */
95 readonly onSettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
96 readonly onSnoozeThread: (
97 thread: EnvironmentThreadShell,
98 snoozedUntil: string,
99 ) => Promise<boolean>;
100 readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
101 readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
102 readonly onPinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
103 readonly onUnpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
104 readonly onSetThreadAutoSettle: (
105 thread: EnvironmentThreadShell,
106 enabled: boolean,
107 ) => Promise<boolean>;
108 readonly onMoveThread: (
109 thread: EnvironmentThreadShell,
110 direction: ThreadMoveDestination,
111 ) => Promise<boolean>;
112 readonly onRenameThread: (thread: EnvironmentThreadShell) => void;
113 readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
114 readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
115 readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
116 readonly onNewThreadOnBranch: (thread: EnvironmentThreadShell) => void;
117 readonly onNewThreadInProject: (project: EnvironmentProject) => void;
118}
119
120/* ─── Layout constants ───────────────────────────────────────────────── */
121
122// v2 rows are mixed-height: settled slim rows run ~60dp, single-line cards
123// measured ~74dp on device (252px on the Pixel 10 Pro screenshot), two-line
124// cards ~94dp. The estimate seeds the recycler's initial container count,
125// `ceil((scrollLength + 2 * INITIAL_DRAW_DISTANCE) / estimate)` with the
126// initial draw distance capped at 50, so an estimate at or below the average
127// row height starts the pool at or above the item count for the short lists
128// that LegendList otherwise keeps pooling to exactly its item count — that is
129// what stopped the dev-mode "no unused container available" warning on the
130// seeded short-list device passes. It is a mitigation, not an elimination:
131// after first layout the full drawDistance applies, and a sudden expansion
132// past the pooled headroom (~25+ items appearing at once) still creates a
133// container on demand with the dev-only warning one pass ahead of the
134// measured-height pool expansion. The old tallest-card estimate (~92) fired
135// that warning on every ordinary shelf expand, so the average wins.
136const ESTIMATED_THREAD_LIST_V2_ROW_HEIGHT = 72;
137// Rows away from the viewport are cheap dormant frames (see
138// swipe-row-activation), so render further ahead: a fast fling then reaches
139// rows that are already built instead of rows still being rebuilt.
140const THREAD_LIST_V2_DRAW_DISTANCE = 1_000;
141const PRE_LIQUID_GLASS_BOTTOM_TOOLBAR_HEIGHT = 44;
142/**
143 * Top spacing between the list and the Android custom header. The Android
144 * header is rendered in-flow above this screen and
145 * already consumes the top safe-area inset, so the list only needs breathing
146 * room here.
147 */
148
149function deriveEmptyState(props: {
150 readonly catalogState: WorkspaceState;
151 readonly projectCount: number;
152}): { readonly title: string; readonly detail: string; readonly loading: boolean } {
153 const { catalogState } = props;
154 if (catalogState.isLoadingConnections) {
155 return {
156 title: "Loading environments",
157 detail: "Checking saved environments on this device.",
158 loading: true,
159 };
160 }
161
162 if (!catalogState.hasConnections) {
163 return {
164 title: "No environments connected",
165 detail: "Add an environment to load projects and start coding sessions.",
166 loading: false,
167 };
168 }
169
170 if (
171 (catalogState.connectionState === "available" ||
172 catalogState.connectionState === "offline" ||
173 catalogState.connectionState === "error" ||
174 catalogState.connectionState === "unsupported") &&
175 !catalogState.hasLoadedShellSnapshot
176 ) {
177 return {
178 title:
179 catalogState.connectionState === "unsupported"
180 ? "Client not supported"
181 : "Environment unavailable",
182 detail:
183 catalogState.connectionError ??
184 "The saved environment is offline. Check the URL or start the environment, then retry.",
185 loading: false,
186 };
187 }
188
189 if (
190 catalogState.hasConnectingEnvironment &&
191 !catalogState.hasLoadedShellSnapshot &&
192 catalogState.connectionError === null
193 ) {
194 return {
195 title: "Connecting to environment",
196 detail: "Loading projects and threads from the saved environment.",
197 loading: true,
198 };
199 }
200
201 if (props.projectCount === 0 && catalogState.hasLoadedShellSnapshot) {
202 return {
203 title: "No projects found",
204 detail: "The connected environment did not report any projects.",
205 loading: false,
206 };
207 }
208
209 return {
210 title: "No threads yet",
211 detail: "Create a task to start a new coding runtime in one of your connected projects.",
212 loading: false,
213 };
214}
215
216function HomeTopContentSpacer() {
217 return <View className="h-4" />;
218}
219
220/* ─── Main screen ────────────────────────────────────────────────────── */
221
222export function HomeScreen(props: HomeScreenProps) {
223 const queuedThreadKeys = useQueuedThreadKeys();
224 const openSwipeableRef = useRef<SwipeableMethods | null>(null);
225 const insets = useSafeAreaInsets();
226 const { fabClearance } = useAndroidControlSizing();
227 const iosBottomToolbarClearance =
228 Platform.OS === "ios" && !NATIVE_LIQUID_GLASS_SUPPORTED
229 ? PRE_LIQUID_GLASS_BOTTOM_TOOLBAR_HEIGHT
230 : 0;
231 const searchEnvironmentIds = useMemo(
232 () =>
233 props.selectedEnvironmentId === null
234 ? props.environments
235 .filter((environment) => environment.connectionState === "connected")
236 .map((environment) => environment.environmentId)
237 : props.environments.some(
238 (environment) =>
239 environment.environmentId === props.selectedEnvironmentId &&
240 environment.connectionState === "connected",
241 )
242 ? [props.selectedEnvironmentId]
243 : [],
244 [props.environments, props.selectedEnvironmentId],
245 );
246 const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery);
247 const threadSearchMatchByKey = useMemo(() => {
248 const matches = new Map<string, EnvironmentThreadSearchMatch>();
249 for (const match of threadSearch.matches) {
250 if (match.source === "user" || match.source === "assistant") {
251 matches.set(threadSearchMatchKey(match), match);
252 }
253 }
254 return matches;
255 }, [threadSearch.matches]);
256 const matchedThreadKeys = useMemo(
257 () => new Set(threadSearch.matches.map(threadSearchMatchKey)),
258 [threadSearch.matches],
259 );
260 const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
261 if (openSwipeableRef.current !== methods) {
262 openSwipeableRef.current?.close();
263 openSwipeableRef.current = methods;
264 }
265 }, []);
266
267 const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
268 if (openSwipeableRef.current === methods) {
269 openSwipeableRef.current = null;
270 }
271 }, []);
272
273 const handleScrollBeginDrag = useCallback(() => {
274 openSwipeableRef.current?.close();
275 }, []);
276 const onMaterialFabScroll = useMaterialFabScroll();
277 const listRef = useRef<LegendListRef>(null);
278 const swipeRowActivation = useMemo(() => createSwipeRowActivation(), []);
279 const activateVisibleRows = useCallback(
280 (rows: ReadonlyArray<ThreadListV2ListItem>) => {
281 const state = listRef.current?.getState();
282 if (state === undefined || !(state.end >= 0)) return;
283 swipeRowActivation.activate(
284 rows.slice(Math.max(0, state.start - 2), state.end + 3).map((row) => row.key),
285 );
286 },
287 [swipeRowActivation],
288 );
289 // Status-bar, accessibility and programmatic scrolls never arm the scroll
290 // gate, so every scroll also activates the visible rows once it settles.
291 const activationTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
292 useEffect(() => () => clearTimeout(activationTimerRef.current), []);
293 const handleListScroll = useCallback(
294 (event: NativeSyntheticEvent<NativeScrollEvent>) => {
295 onMaterialFabScroll?.(event);
296 clearTimeout(activationTimerRef.current);
297 activationTimerRef.current = setTimeout(
298 () => activateVisibleRows(listRef.current?.getState().data ?? []),
299 200,
300 );
301 },
302 [activateVisibleRows, onMaterialFabScroll],
303 );
304 const trackListTouches = useCallback(
305 (event: GestureResponderEvent, started: boolean) => {
306 const { changedTouches, touches } = event.nativeEvent;
307 swipeRowActivation.trackTouches(
308 started ? changedTouches.map((touch) => String(touch.identifier)) : [],
309 touches.map((touch) => String(touch.identifier)),
310 );
311 },
312 [swipeRowActivation],
313 );
314 const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
315 onScroll: handleListScroll,
316 onScrollBeginDrag: handleScrollBeginDrag,
317 });
318
319 const projectScopes = useMemo(
320 () =>
321 buildHomeProjectScopes({
322 projects: props.projects,
323 environmentId: props.selectedEnvironmentId,
324 projectGroupingMode: props.projectGroupingMode,
325 }),
326 [props.projectGroupingMode, props.projects, props.selectedEnvironmentId],
327 );
328 const hasSearchQuery = props.searchQuery.trim().length > 0;
329 const projectByKey = useMemo(() => {
330 const map = new Map<string, EnvironmentProject>();
331 for (const project of props.projects) {
332 map.set(scopedProjectKey(project.environmentId, project.id), project);
333 }
334 return map;
335 }, [props.projects]);
336
337 const v2ProjectScopeKey = props.selectedProjectKey;
338 const v2ScopeProjects = useMemo(
339 () =>
340 sortHomeProjectScopes({
341 scopes: projectScopes,
342 threads: props.threads,
343 pendingTasks: props.pendingTasks,
344 projectSortOrder: props.projectSortOrder,
345 }),
346 [
347 props.pendingTasks,
348 props.projects,
349 props.projectSortOrder,
350 props.selectedEnvironmentId,
351 props.threads,
352 projectScopes,
353 ],
354 );
355 const v2ScopedProjectGroup = useMemo(
356 () =>
357 v2ProjectScopeKey === null
358 ? null
359 : (v2ScopeProjects.find(
360 (scope) =>
361 scope.key === v2ProjectScopeKey ||
362 scope.projectRefs.some(
363 (projectRef) =>
364 scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
365 v2ProjectScopeKey,
366 ),
367 ) ?? null),
368 [v2ProjectScopeKey, v2ScopeProjects],
369 );
370 const v2ProjectTitleByProjectKey = useMemo(
371 () =>
372 new Map(
373 v2ScopeProjects.flatMap((scope) =>
374 scope.projectRefs.map(
375 (projectRef) =>
376 [
377 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
378 scope.title,
379 ] as const,
380 ),
381 ),
382 ),
383 [v2ScopeProjects],
384 );
385 const v2ScopedProjectKeys = useMemo(
386 () =>
387 v2ScopedProjectGroup === null
388 ? null
389 : new Set(
390 v2ScopedProjectGroup.projectRefs.map((projectRef) =>
391 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
392 ),
393 ),
394 [v2ScopedProjectGroup],
395 );
396 // Thread List v2 (beta): one flat list in creation order, no grouping.
397 // Settled threads collapse into a recency tail below the card block.
398 // Settled threads stay in the live shell stream (settled ≠ archived), so
399 // the partition works directly off live shells — no snapshot merging or
400 // optimistic holds.
401 const handleSettleThread = props.onSettleThread;
402 const handleSnoozeThread = useCallback(
403 (thread: EnvironmentThreadShell, snoozedUntil: string) => {
404 void props.onSnoozeThread(thread, snoozedUntil);
405 },
406 [props.onSnoozeThread],
407 );
408 const handleUnsnoozeThread = useCallback(
409 (thread: EnvironmentThreadShell) => {
410 void props.onUnsnoozeThread(thread);
411 },
412 [props.onUnsnoozeThread],
413 );
414 const handlePinThread = useCallback(
415 (thread: EnvironmentThreadShell) => {
416 void props.onPinThread(thread);
417 },
418 [props.onPinThread],
419 );
420 const handleMoveThread = useCallback(
421 (thread: EnvironmentThreadShell, direction: ThreadMoveDestination) => {
422 void props.onMoveThread(thread, direction);
423 },
424 [props.onMoveThread],
425 );
426 const handleUnpinThread = useCallback(
427 (thread: EnvironmentThreadShell) => {
428 void props.onUnpinThread(thread);
429 },
430 [props.onUnpinThread],
431 );
432 const handleSetThreadAutoSettle = useCallback(
433 (thread: EnvironmentThreadShell, enabled: boolean) => {
434 void props.onSetThreadAutoSettle(thread, enabled);
435 },
436 [props.onSetThreadAutoSettle],
437 );
438 const handleRegenerateThreadTitle = useCallback(
439 (thread: EnvironmentThreadShell) => {
440 void props.onRegenerateThreadTitle(thread);
441 },
442 [props.onRegenerateThreadTitle],
443 );
444 const handleRenameThread = useCallback(
445 (thread: EnvironmentThreadShell) => props.onRenameThread(thread),
446 [props.onRenameThread],
447 );
448 const handleDeleteThread = props.onDeleteThread;
449 const handleUnsettleThread = props.onUnsettleThread;
450 // The settled tail renders in pages; expansion resets when the filter
451 // context changes so environment/search flips never inherit a deep page.
452 const [settledVisibleCount, setSettledVisibleCount] = useState(
453 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
454 );
455 const settledResetKey = `${props.selectedEnvironmentId ?? "all"}:${v2ProjectScopeKey ?? "all"}:${props.searchQuery.trim()}`;
456 const lastSettledResetKeyRef = useRef(settledResetKey);
457 if (lastSettledResetKeyRef.current !== settledResetKey) {
458 lastSettledResetKeyRef.current = settledResetKey;
459 setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
460 }
461 const showMoreSettled = useCallback(
462 () => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
463 [],
464 );
465 const {
466 loaded: shelfPreferencesLoaded,
467 settledShelfExpanded,
468 snoozedShelfExpanded,
469 toggleSettledShelf,
470 toggleSnoozedShelf,
471 } = useThreadListV2ShelfPreferences();
472 // The queued-start and snooze helpers need a clock while the list stays open.
473 const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
474 // Snooze wake times are second-precise; a counter bumped exactly at the
475 // next wake boundary re-runs the partition with a fresh clock so a woken
476 // thread reappears immediately instead of on the next minute tick.
477 const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
478 useFocusEffect(
479 useCallback(() => {
480 // Refresh immediately on enable or focus because the previous value can be hours old.
481 setNowMinute(new Date().toISOString().slice(0, 16));
482 const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
483 return () => clearInterval(id);
484 }, []),
485 );
486 // Threads on servers without the settlement capability never classify as
487 // settled (the user could neither un-settle nor pin them).
488 const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
489 const {
490 providersByEnvironmentId,
491 machineByEnvironmentId,
492 settlementEnvironmentIds,
493 snoozeEnvironmentIds,
494 pinningEnvironmentIds,
495 autoSettleOptOutEnvironmentIds,
496 pinReorderEnvironmentIds,
497 activeReorderEnvironmentIds,
498 titleRegenerationEnvironmentIds,
499 } = listEnvironments;
500 const resolveProviderInstance = useThreadRowProviderInstanceResolver(providersByEnvironmentId);
501 const pendingOrder = usePendingThreadOrder(nowMinute, snoozeWakeTick);
502 // Up/down menu availability for every card, computed once per section per
503 // rebuild (see computeThreadMoveAvailability): per-thread planner calls made
504 // list construction quadratic, and this list rebuilds on every minute tick.
505 const threadMoveAvailability = useMemo(() => {
506 const sectionAvailability = (section: "pinned" | "active") =>
507 computeThreadMoveAvailability({
508 allThreads: props.threads,
509 section,
510 pendingOrder,
511 reorderableEnvironmentIds:
512 section === "pinned" ? pinReorderEnvironmentIds : activeReorderEnvironmentIds,
513 ordered: getThreadListV2OrderedSection({
514 threads: props.threads,
515 section,
516 pendingOrder,
517 now: new Date().toISOString(),
518 settlementEnvironmentIds,
519 snoozeEnvironmentIds,
520 queuedThreadKeys,
521 }),
522 });
523 return new Map([...sectionAvailability("pinned"), ...sectionAvailability("active")]);
524 }, [
525 pinReorderEnvironmentIds,
526 activeReorderEnvironmentIds,
527 props.threads,
528 pendingOrder,
529 queuedThreadKeys,
530 settlementEnvironmentIds,
531 snoozeEnvironmentIds,
532 nowMinute,
533 snoozeWakeTick,
534 ]);
535 const threadListV2Layout = useMemo(() => {
536 // Settled threads are live shells; archived threads keep their original
537 // "hidden from lists" meaning.
538 return buildThreadListV2Items({
539 pendingOrder,
540 threads: props.threads.filter((thread) => thread.archivedAt === null),
541 environmentId: props.selectedEnvironmentId,
542 projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
543 searchQuery: props.searchQuery,
544 matchedThreadKeys,
545 settlementEnvironmentIds,
546 snoozeEnvironmentIds,
547 queuedThreadKeys,
548 settledLimit: settledVisibleCount,
549 now: new Date().toISOString(),
550 snoozedShelfExpanded,
551 settledShelfExpanded,
552 selectedThreadKey: null,
553 });
554 }, [
555 pendingOrder,
556 queuedThreadKeys,
557 nowMinute,
558 snoozeWakeTick,
559 snoozedShelfExpanded,
560 settledShelfExpanded,
561 settledVisibleCount,
562 settlementEnvironmentIds,
563 snoozeEnvironmentIds,
564 props.searchQuery,
565 props.selectedEnvironmentId,
566 props.threads,
567 matchedThreadKeys,
568 v2ScopedProjectGroup,
569 ]);
570 // Re-partition the moment the earliest snooze expires (clamped to the
571 // signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
572 const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
573 useEffect(() => {
574 if (nextSnoozeWakeAt === null) return;
575 const wakeAtMs = Date.parse(nextSnoozeWakeAt);
576 if (Number.isNaN(wakeAtMs)) return;
577 const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
578 const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
579 return () => clearTimeout(id);
580 // snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
581 // unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
582 // range) the boundary string is identical and the chain would die.
583 }, [nextSnoozeWakeAt, snoozeWakeTick]);
584 // Queued tasks are not thread shells, so the v2 partition never sees them;
585 // they are spliced in below the active block and stay visible and deletable
586 // while their environment is offline. Same environment scope and search
587 // filter as the list itself.
588 const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
589 const v2PendingTasks = useMemo(
590 () =>
591 props.pendingTasks.filter(
592 (pendingTask) =>
593 (props.selectedEnvironmentId === null ||
594 pendingTask.environmentId === props.selectedEnvironmentId) &&
595 (v2ScopedProjectKeys === null ||
596 v2ScopedProjectKeys.has(
597 scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),
598 )) &&
599 (v2SearchQuery.length === 0 ||
600 pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
601 ),
602 [props.pendingTasks, props.selectedEnvironmentId, v2ScopedProjectKeys, v2SearchQuery],
603 );
604 const threadListV2Items = useMemo(
605 () =>
606 buildThreadListV2ListItems({
607 items: threadListV2Layout.items,
608 pendingTasks: v2PendingTasks,
609 snoozedCount: threadListV2Layout.snoozedCount,
610 snoozedShelfExpanded,
611 snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
612 settledCount: threadListV2Layout.settledCount,
613 settledShelfExpanded,
614 settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
615 snoozeLabelNow: `${nowMinute}:00.000Z`,
616 snoozeEnvironmentIds,
617 queuedThreadKeys,
618 moveAvailability: threadMoveAvailability,
619 shelfPreferencesLoading: !shelfPreferencesLoaded,
620 }),
621 [
622 nowMinute,
623 queuedThreadKeys,
624 threadMoveAvailability,
625 settledShelfExpanded,
626 shelfPreferencesLoaded,
627 snoozedShelfExpanded,
628 snoozeEnvironmentIds,
629 threadListV2Layout,
630 v2PendingTasks,
631 ],
632 );
633
634 useThreadJumpShortcuts(threadListV2Items, props.onSelectThread);
635 useEffect(() => {
636 if (swipeEnabled) activateVisibleRows(threadListV2Items);
637 }, [activateVisibleRows, swipeEnabled, threadListV2Items]);
638
639 const renderV2Item = useCallback(
640 ({ item }: { readonly item: ThreadListV2ListItem }) => {
641 if (item.type === "v2-pending") {
642 const pendingScopeKey = scopedProjectKey(
643 item.pendingTask.environmentId,
644 item.pendingTask.projectId,
645 );
646 return (
647 <ThreadListV2PendingRow
648 pendingTask={item.pendingTask}
649 project={projectByKey.get(pendingScopeKey) ?? null}
650 projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}
651 environmentLabel={
652 Object.keys(props.savedConnectionsById).length > 1
653 ? (props.savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ??
654 null)
655 : null
656 }
657 environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
658 showPendingDivider={item.showPendingDivider}
659 showTrailingDivider={item.showTrailingDivider}
660 onSelectPendingTask={props.onSelectPendingTask}
661 onDeletePendingTask={props.onDeletePendingTask}
662 />
663 );
664 }
665 if (item.type === "v2-snoozed-shelf") {
666 return (
667 <ThreadListV2SnoozedShelfHeader
668 count={item.count}
669 disabled={item.disabled}
670 expanded={item.expanded}
671 onToggle={toggleSnoozedShelf}
672 />
673 );
674 }
675 if (item.type === "v2-settled-shelf") {
676 return (
677 <ThreadListV2SettledShelfHeader
678 count={item.count}
679 disabled={item.disabled}
680 expanded={item.expanded}
681 onToggle={toggleSettledShelf}
682 />
683 );
684 }
685 const thread = item.item.thread;
686 return (
687 <ThreadListV2Row
688 onNewThreadOnBranch={props.onNewThreadOnBranch}
689 thread={thread}
690 variant={item.item.variant}
691 hasQueuedMessages={item.hasQueuedMessages}
692 snoozed={item.item.snoozed}
693 pinned={item.item.pinned}
694 snoozePresetMinute={item.snoozePresetMinute ?? ""}
695 snoozeWakeLabelText={item.snoozeWakeLabelText}
696 timeLabel={item.timeLabel}
697 showTrailingDivider={item.showTrailingDivider}
698 project={
699 projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
700 }
701 projectTitle={v2ProjectTitleByProjectKey.get(
702 scopedProjectKey(thread.environmentId, thread.projectId),
703 )}
704 providerInstance={resolveProviderInstance(thread)}
705 providers={providersByEnvironmentId.get(thread.environmentId)}
706 environmentLabel={
707 Object.keys(props.savedConnectionsById).length > 1
708 ? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
709 : null
710 }
711 environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
712 searchMatch={threadSearchMatchByKey.get(
713 threadSearchMatchKey({
714 environmentId: thread.environmentId,
715 threadId: thread.id,
716 }),
717 )}
718 searchQuery={props.searchQuery}
719 onSelectThread={props.onSelectThread}
720 onDeleteThread={handleDeleteThread}
721 onArchiveThread={props.onArchiveThread}
722 onRenameThread={handleRenameThread}
723 onRegenerateThreadTitle={handleRegenerateThreadTitle}
724 titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
725 settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
726 onSettleThread={handleSettleThread}
727 snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
728 pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
729 autoSettleOptOutSupported={autoSettleOptOutEnvironmentIds.has(thread.environmentId)}
730 reorderSupported={
731 item.item.pinned
732 ? pinReorderEnvironmentIds.has(thread.environmentId)
733 : activeReorderEnvironmentIds.has(thread.environmentId)
734 }
735 canMoveUp={item.canMoveUp}
736 canMoveDown={item.canMoveDown}
737 onSnoozeThread={handleSnoozeThread}
738 onUnsnoozeThread={handleUnsnoozeThread}
739 onUnsettleThread={handleUnsettleThread}
740 onPinThread={handlePinThread}
741 onUnpinThread={handleUnpinThread}
742 onSetThreadAutoSettle={handleSetThreadAutoSettle}
743 onMoveThread={handleMoveThread}
744 onSwipeableClose={handleSwipeableClose}
745 onSwipeableWillOpen={handleSwipeableWillOpen}
746 activationKey={item.key}
747 />
748 );
749 },
750 [
751 handleDeleteThread,
752 activeReorderEnvironmentIds,
753 handleMoveThread,
754 handlePinThread,
755 handleRegenerateThreadTitle,
756 handleRenameThread,
757 handleSettleThread,
758 handleSnoozeThread,
759 handleUnpinThread,
760 handleUnsnoozeThread,
761 handleSwipeableClose,
762 handleSwipeableWillOpen,
763 handleUnsettleThread,
764 handleSetThreadAutoSettle,
765 autoSettleOptOutEnvironmentIds,
766 pinningEnvironmentIds,
767 autoSettleOptOutEnvironmentIds,
768 machineByEnvironmentId,
769 pinReorderEnvironmentIds,
770 projectByKey,
771 props.onArchiveThread,
772 props.onDeletePendingTask,
773 props.onSelectPendingTask,
774 props.onSelectThread,
775 props.onNewThreadOnBranch,
776 props.savedConnectionsById,
777 resolveProviderInstance,
778 providersByEnvironmentId,
779 settlementEnvironmentIds,
780 snoozeEnvironmentIds,
781 threadSearchMatchByKey,
782 titleRegenerationEnvironmentIds,
783 toggleSettledShelf,
784 toggleSnoozedShelf,
785 v2ProjectTitleByProjectKey,
786 props.searchQuery,
787 ],
788 );
789 const v2KeyExtractor = useCallback((item: ThreadListV2ListItem) => item.key, []);
790
791 // FlatList/LegendList treat a changed extraData identity as "re-render every
792 // visible row", so an inline object literal would invalidate all rows on
793 // every HomeScreen render — and the minute clock must stay out of it for
794 // the same reason: the clock text is precomputed per item instead.
795 const v2ExtraData = useMemo(
796 () => ({
797 projectByKey,
798 projectTitleByProjectKey: v2ProjectTitleByProjectKey,
799 listEnvironments,
800 savedConnectionsById: props.savedConnectionsById,
801 searchQuery: props.searchQuery,
802 threadSearchMatchByKey,
803 }),
804 [
805 projectByKey,
806 props.searchQuery,
807 props.savedConnectionsById,
808 listEnvironments,
809 threadSearchMatchByKey,
810 v2ProjectTitleByProjectKey,
811 ],
812 );
813
814 /* Empty states */
815 // The signal must ignore the search/environment filters: an active query
816 // that matches nothing needs the in-list "No results" state, not the
817 // full-page "No threads yet". Settled threads are unarchived live shells,
818 // so the archived-at check already covers the settled shelf.
819 const hasAnyThreads =
820 props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
821 const selectedEnvironmentLabel =
822 props.selectedEnvironmentId === null
823 ? null
824 : (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
825 "this environment");
826 // Connection state surfaces in the header title slot
827 // (WorkspaceConnectionTitle) — nothing renders inside the list, so
828 // reconnects never shift the rows.
829 const emptyState = deriveEmptyState({
830 catalogState: props.catalogState,
831 projectCount: props.projects.length,
832 });
833
834 if (!hasAnyThreads) {
835 return (
836 <View className="flex-1 bg-screen android:bg-header">
837 <View
838 className={cn(
839 "flex-1 items-center justify-center bg-screen px-8",
840 Platform.OS === "android" && "overflow-hidden rounded-t-[28px]",
841 )}
842 style={{
843 paddingBottom: Math.max(insets.bottom, 24) + iosBottomToolbarClearance,
844 paddingTop: NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 72 : 0,
845 }}
846 >
847 <View className="w-full max-w-[430px]">
848 <EmptyState
849 title={emptyState.title}
850 detail={emptyState.detail}
851 actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
852 onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
853 action={
854 Platform.OS === "android" && !props.catalogState.hasReadyEnvironment ? (
855 <MaterialFloatingActionButton
856 label="Add environment"
857 icon="plus"
858 variant="extended"
859 tone="primary"
860 onPress={props.onAddConnection}
861 />
862 ) : undefined
863 }
864 variant="plain"
865 />
866 {emptyState.loading ? (
867 <View className="mt-4 items-center">
868 <ActivityIndicator colorClassName="accent-icon-muted" />
869 </View>
870 ) : null}
871 </View>
872 </View>
873 </View>
874 );
875 }
876
877 const listHeader = Platform.OS === "ios" ? undefined : <HomeTopContentSpacer />;
878
879 // Project scoping lives in the header filter menu (no inline chip row on
880 // mobile — the menu is the one filter surface).
881 const v2ListHeader = listHeader;
882
883 // Use the v2 project scope for its empty state. Snoozed threads need no
884 // special empty state: their shelf header is a list row even while collapsed.
885 const v2ListEmpty =
886 hasSearchQuery && threadSearch.isPending ? undefined : hasSearchQuery ? (
887 <EmptyState
888 title="No results"
889 detail={`No threads matching "${props.searchQuery}".`}
890 variant={Platform.OS === "android" ? "plain" : undefined}
891 />
892 ) : v2ScopedProjectGroup !== null ? (
893 <EmptyState
894 title={`No threads in ${v2ScopedProjectGroup.title}`}
895 detail="Choose another project or create a new task."
896 variant={Platform.OS === "android" ? "plain" : undefined}
897 />
898 ) : selectedEnvironmentLabel ? (
899 <EmptyState
900 title={`No threads in ${selectedEnvironmentLabel}`}
901 detail="Choose another environment or create a new task."
902 variant={Platform.OS === "android" ? "plain" : undefined}
903 />
904 ) : (
905 <EmptyState
906 title="No threads yet"
907 detail="Create a task to start a new coding session."
908 variant={Platform.OS === "android" ? "plain" : undefined}
909 />
910 );
911
912 if (Platform.OS === "android" && threadListV2Items.length === 0) {
913 return (
914 <View className="flex-1 bg-header">
915 <View
916 className="flex-1 items-center justify-center overflow-hidden rounded-t-[28px] bg-screen px-4"
917 style={{ paddingBottom: insets.bottom }}
918 >
919 {v2ListEmpty}
920 </View>
921 </View>
922 );
923 }
924
925 return (
926 <View className="flex-1 bg-screen android:bg-header">
927 <View
928 className={
929 Platform.OS === "android"
930 ? "flex-1 overflow-hidden rounded-t-[28px] bg-screen"
931 : "flex-1 bg-screen"
932 }
933 >
934 {/* Shared with the iPad sidebar: cells are reused across data
935 rebuilds and `itemsAreEqual` keeps a minute tick (or an unrelated
936 shell update) from re-rendering untouched rows. */}
937 <SwipeableScrollGateProvider enabled={swipeEnabled} activation={swipeRowActivation}>
938 <LegendList
939 ref={listRef}
940 onLoad={() => activateVisibleRows(threadListV2Items)}
941 onTouchStart={(event) => trackListTouches(event, true)}
942 onTouchEnd={(event) => trackListTouches(event, false)}
943 onTouchCancel={(event) => trackListTouches(event, false)}
944 data={threadListV2Items}
945 renderItem={renderV2Item}
946 keyExtractor={v2KeyExtractor}
947 getItemType={(item) => item.type}
948 itemsAreEqual={threadListV2ListItemsAreEqual}
949 estimatedItemSize={ESTIMATED_THREAD_LIST_V2_ROW_HEIGHT}
950 drawDistance={THREAD_LIST_V2_DRAW_DISTANCE}
951 recycleItems
952 extraData={v2ExtraData}
953 ListHeaderComponent={v2ListHeader}
954 ListFooterComponent={
955 settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? (
956 <ThreadListV2ShowMoreRow
957 hiddenCount={threadListV2Layout.hiddenSettledCount}
958 onPress={showMoreSettled}
959 />
960 ) : null
961 }
962 ListEmptyComponent={v2ListEmpty}
963 style={{ flex: 1 }}
964 automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
965 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
966 showsVerticalScrollIndicator={false}
967 keyboardDismissMode="on-drag"
968 keyboardShouldPersistTaps="handled"
969 {...scrollGateHandlers}
970 scrollEventThrottle={16}
971 contentContainerStyle={{
972 paddingBottom:
973 Platform.OS === "ios"
974 ? Math.max(insets.bottom, 24) + 96 + iosBottomToolbarClearance
975 : Math.max(insets.bottom, 16) + (Platform.OS === "android" ? fabClearance : 88),
976 }}
977 />
978 </SwipeableScrollGateProvider>
979 </View>
980 </View>
981 );
982}