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