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