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

HomeScreen.tsx

922 lines35.5 KB

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