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