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

HomeScreen.tsx

1,052 lines41.5 KB

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