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

HomeScreen.tsx

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