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

HomeScreen.tsx

1,224 lines45.6 KB

1import {
2 LegendList,
3 type LegendListRef,
4 type LegendListRenderItemProps,
5} from "@legendapp/list/react-native";
6import {
7 type EnvironmentProject,
8 type EnvironmentThreadShell,
9} from "@t3tools/client-runtime/state/shell";
10import {
11 threadSearchMatchKey,
12 type EnvironmentThreadSearchMatch,
13} from "@t3tools/client-runtime/state/thread-search";
14import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
15import {
16 type EnvironmentId,
17 resolveEnvironmentMachineKind,
18 type SidebarProjectGroupingMode,
19 type SidebarThreadSortOrder,
20} from "@t3tools/contracts";
21import { useAtomSet, useAtomValue } from "@effect/atom-react";
22import { AsyncResult } from "effect/unstable/reactivity";
23import { useFocusEffect } from "@react-navigation/native";
24import { useCallback, useEffect, useMemo, useRef, useState } from "react";
25import { ActivityIndicator, FlatList, Platform, Pressable, View } from "react-native";
26import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
27import { useSafeAreaInsets } from "react-native-safe-area-context";
28​
29import { AppText as Text } from "../../components/AppText";
30import { EmptyState } from "../../components/EmptyState";
31import type { WorkspaceEnvironment, WorkspaceState } from "../../state/workspaceModel";
32import type { SavedRemoteConnection } from "../../lib/connection";
33import { scopedProjectKey } from "../../lib/scopedEntities";
34import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
35import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
36import { useThreadSearch } from "../../state/queries";
37import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
38import { environmentServerConfigsAtom } from "../../state/server";
39import type { PendingNewTask } from "../../state/use-pending-new-tasks";
40import {
41 PendingTaskListRow,
42 ThreadListGroupHeader,
43 ThreadListRow,
44 ThreadListShowMoreRow,
45} from "../threads/thread-list-items";
46import {
47 ThreadListV2PendingRow,
48 ThreadListV2Row,
49 ThreadListV2SettledShelfHeader,
50 ThreadListV2SnoozedShelfHeader,
51} from "../threads/thread-list-v2-items";
52import {
53 buildThreadListV2Items,
54 buildThreadListV2ListItems,
55 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
56 THREAD_LIST_V2_SETTLED_PAGE_COUNT,
57 type ThreadListV2ListItem,
58} from "../threads/threadListV2";
59import { useThreadListV2ShelfPreferences } from "../threads/use-thread-list-v2-shelf-preferences";
60import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
61import {
62 buildHomeListLayout,
63 DEFAULT_GROUP_DISPLAY_STATE,
64 EMPTY_HOME_LIST_LAYOUT,
65 homeListItemsAreEqual,
66 nextGroupDisplayState,
67 type HomeGroupDisplayAction,
68 type HomeGroupDisplayState,
69 type HomeListItem,
70} from "./homeListItems";
71import {
72 buildHomeProjectScopes,
73 buildHomeThreadGroups,
74 sortHomeProjectScopes,
75 type HomeProjectSortOrder,
76} from "./homeThreadList";
77import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
78​
79/* ─── Types ──────────────────────────────────────────────────────────── */
80​
81interface HomeScreenProps {
82 readonly projects: ReadonlyArray<EnvironmentProject>;
83 readonly threads: ReadonlyArray<EnvironmentThreadShell>;
84 readonly pendingTasks: ReadonlyArray<PendingNewTask>;
85 readonly catalogState: WorkspaceState;
86 readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
87 readonly environments: ReadonlyArray<
88 HomeListFilterMenuEnvironment & Pick<WorkspaceEnvironment, "connectionState">
89 >;
90 readonly searchQuery: string;
91 readonly selectedEnvironmentId: EnvironmentId | null;
92 readonly selectedProjectKey: string | null;
93 readonly projectSortOrder: HomeProjectSortOrder;
94 readonly threadSortOrder: SidebarThreadSortOrder;
95 readonly projectGroupingMode: SidebarProjectGroupingMode;
96 readonly onSearchQueryChange: (query: string) => void;
97 readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
98 readonly onProjectChange: (projectKey: string | null) => void;
99 readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
100 readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
101 readonly onAddConnection: () => void;
102 readonly onOpenSettings: () => void;
103 readonly onStartNewTask: () => void;
104 readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
105 readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
106 readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
107 /** Resolves true iff the settle was dispatched and succeeded. */
108 readonly onSettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
109 readonly onSnoozeThread: (
110 thread: EnvironmentThreadShell,
111 snoozedUntil: string,
112 ) => Promise<boolean>;
113 readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
114 readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
115 readonly onPinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
116 readonly onUnpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
117 readonly onMovePinnedThread: (
118 thread: EnvironmentThreadShell,
119 direction: "up" | "down",
120 ) => Promise<boolean>;
121 readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
122 readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
123 readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
124 readonly onNewThreadInProject: (project: EnvironmentProject) => void;
126​
127/* ─── Layout constants ───────────────────────────────────────────────── */
128​
129const ESTIMATED_THREAD_ROW_HEIGHT = 72;
130const PRE_LIQUID_GLASS_BOTTOM_TOOLBAR_HEIGHT = 44;
131/**
132 * Top spacing between the list and the Android custom header. The Android
133 * header (AndroidHomeHeader) is rendered in-flow above this screen and
134 * already consumes the top safe-area inset, so the list only needs breathing
135 * room here.
136 */
137​
138function deriveEmptyState(props: {
139 readonly catalogState: WorkspaceState;
140 readonly projectCount: number;
141}): { readonly title: string; readonly detail: string; readonly loading: boolean } {
142 const { catalogState } = props;
143 if (catalogState.isLoadingConnections) {
144 return {
145 title: "Loading environments",
146 detail: "Checking saved environments on this device.",
147 loading: true,
148 };
149 }
150​
151 if (!catalogState.hasConnections) {
152 return {
153 title: "No environments connected",
154 detail: "Add an environment to load projects and start coding sessions.",
155 loading: false,
156 };
157 }
158​
159 if (
160 (catalogState.connectionState === "available" ||
161 catalogState.connectionState === "offline" ||
162 catalogState.connectionState === "error") &&
163 !catalogState.hasLoadedShellSnapshot
164 ) {
165 return {
166 title: "Environment unavailable",
167 detail:
168 catalogState.connectionError ??
169 "The saved environment is offline. Check the URL or start the environment, then retry.",
170 loading: false,
171 };
172 }
173​
174 if (
175 catalogState.hasConnectingEnvironment &&
176 !catalogState.hasLoadedShellSnapshot &&
177 catalogState.connectionError === null
178 ) {
179 return {
180 title: "Connecting to environment",
181 detail: "Loading projects and threads from the saved environment.",
182 loading: true,
183 };
184 }
185​
186 if (props.projectCount === 0 && catalogState.hasLoadedShellSnapshot) {
187 return {
188 title: "No projects found",
189 detail: "The connected environment did not report any projects.",
190 loading: false,
191 };
192 }
193​
194 return {
195 title: "No threads yet",
196 detail: "Create a task to start a new coding session in one of your connected projects.",
197 loading: false,
198 };
200​
201function HomeTopContentSpacer() {
202 return <View className="h-4" />;
204​
205/* ─── Main screen ────────────────────────────────────────────────────── */
206​
207export function HomeScreen(props: HomeScreenProps) {
208 const [groupDisplayStates, setGroupDisplayStates] = useState<
209 ReadonlyMap<string, HomeGroupDisplayState>
210 >(() => new Map());
211 const preferencesResult = useAtomValue(mobilePreferencesAtom);
212 const threadListV2Enabled = useThreadListV2Enabled();
213 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
214 const openSwipeableRef = useRef<SwipeableMethods | null>(null);
215 const listRef = useRef<LegendListRef | null>(null);
216 const insets = useSafeAreaInsets();
217 const iosBottomToolbarClearance =
218 Platform.OS === "ios" && !NATIVE_LIQUID_GLASS_SUPPORTED
219 ? PRE_LIQUID_GLASS_BOTTOM_TOOLBAR_HEIGHT
220 : 0;
221 const searchEnvironmentIds = useMemo(
222 () =>
223 props.selectedEnvironmentId === null
224 ? props.environments
225 .filter((environment) => environment.connectionState === "connected")
226 .map((environment) => environment.environmentId)
227 : props.environments.some(
228 (environment) =>
229 environment.environmentId === props.selectedEnvironmentId &&
230 environment.connectionState === "connected",
231 )
232 ? [props.selectedEnvironmentId]
233 : [],
234 [props.environments, props.selectedEnvironmentId],
235 );
236 const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery);
237 const threadSearchMatchByKey = useMemo(() => {
238 const matches = new Map<string, EnvironmentThreadSearchMatch>();
239 for (const match of threadSearch.matches) {
240 if (match.source === "user" || match.source === "assistant") {
241 matches.set(threadSearchMatchKey(match), match);
242 }
243 }
244 return matches;
245 }, [threadSearch.matches]);
246 const matchedThreadKeys = useMemo(
247 () => new Set(threadSearch.matches.map(threadSearchMatchKey)),
248 [threadSearch.matches],
249 );
250 const effectiveGroupDisplayStates = useMemo(() => {
251 const next = new Map(groupDisplayStates);
252 if (!AsyncResult.isSuccess(preferencesResult)) {
253 return next;
254 }
255 for (const key of preferencesResult.value.collapsedProjectGroups ?? []) {
256 const existing = next.get(key);
257 next.set(key, {
258 ...(existing ?? DEFAULT_GROUP_DISPLAY_STATE),
259 collapsed: true,
260 });
261 }
262 return next;
263 }, [groupDisplayStates, preferencesResult]);
264 const effectiveGroupDisplayStatesRef = useRef(effectiveGroupDisplayStates);
265 effectiveGroupDisplayStatesRef.current = effectiveGroupDisplayStates;
266​
267 const updateGroupDisplay = useCallback(
268 (key: string, action: HomeGroupDisplayAction) => {
269 const next = new Map(effectiveGroupDisplayStatesRef.current);
270 next.set(key, nextGroupDisplayState(next.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action));
271 effectiveGroupDisplayStatesRef.current = next;
272 setGroupDisplayStates(next);
273 if (action === "toggle-collapsed") {
274 const collapsedProjectGroups: string[] = [];
275 for (const [groupKey, state] of next) {
276 if (state.collapsed) {
277 collapsedProjectGroups.push(groupKey);
278 }
279 }
280 savePreferences({ collapsedProjectGroups });
281 }
282 },
283 [savePreferences],
284 );
285​
286 const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
287 if (openSwipeableRef.current !== methods) {
288 openSwipeableRef.current?.close();
289 openSwipeableRef.current = methods;
290 }
291 }, []);
292​
293 const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
294 if (openSwipeableRef.current === methods) {
295 openSwipeableRef.current = null;
296 }
297 }, []);
298​
299 const handleScrollBeginDrag = useCallback(() => {
300 openSwipeableRef.current?.close();
301 }, []);
302 const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
303 onScrollBeginDrag: handleScrollBeginDrag,
304 });
305​
306 const projectScopes = useMemo(
307 () =>
308 buildHomeProjectScopes({
309 projects: props.projects,
310 environmentId: props.selectedEnvironmentId,
311 projectGroupingMode: props.projectGroupingMode,
312 }),
313 [props.projectGroupingMode, props.projects, props.selectedEnvironmentId],
314 );
315 const selectedProjectScope = useMemo(
316 () =>
317 props.selectedProjectKey === null
318 ? null
319 : (projectScopes.find(
320 (scope) =>
321 scope.key === props.selectedProjectKey ||
322 scope.projectRefs.some(
323 (projectRef) =>
324 scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
325 props.selectedProjectKey,
326 ),
327 ) ?? null),
328 [projectScopes, props.selectedProjectKey],
329 );
330 const selectedProjectRefKeys = useMemo(
331 () =>
332 selectedProjectScope === null
333 ? null
334 : new Set(
335 selectedProjectScope.projectRefs.map((projectRef) =>
336 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
337 ),
338 ),
339 [selectedProjectScope],
340 );
341 const scopedProjects = useMemo(
342 () =>
343 threadListV2Enabled
344 ? []
345 : selectedProjectRefKeys === null
346 ? props.projects
347 : props.projects.filter((project) =>
348 selectedProjectRefKeys.has(scopedProjectKey(project.environmentId, project.id)),
349 ),
350 [threadListV2Enabled, props.projects, selectedProjectRefKeys],
351 );
352 const scopedThreads = useMemo(
353 () =>
354 threadListV2Enabled
355 ? []
356 : selectedProjectRefKeys === null
357 ? props.threads
358 : props.threads.filter((thread) =>
359 selectedProjectRefKeys.has(scopedProjectKey(thread.environmentId, thread.projectId)),
360 ),
361 [threadListV2Enabled, props.threads, selectedProjectRefKeys],
362 );
363 const scopedPendingTasks = useMemo(
364 () =>
365 threadListV2Enabled
366 ? []
367 : selectedProjectRefKeys === null
368 ? props.pendingTasks
369 : props.pendingTasks.filter((pendingTask) =>
370 selectedProjectRefKeys.has(
371 scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
372 ),
373 ),
374 [threadListV2Enabled, props.pendingTasks, selectedProjectRefKeys],
375 );
376​
377 const projectGroups = useMemo(
378 () =>
379 threadListV2Enabled
380 ? []
381 : buildHomeThreadGroups({
382 projects: scopedProjects,
383 threads: scopedThreads,
384 pendingTasks: scopedPendingTasks,
385 environmentId: props.selectedEnvironmentId,
386 searchQuery: props.searchQuery,
387 matchedThreadKeys,
388 projectSortOrder: props.projectSortOrder,
389 threadSortOrder: props.threadSortOrder,
390 projectGroupingMode: props.projectGroupingMode,
391 }),
392 [
393 threadListV2Enabled,
394 props.projectGroupingMode,
395 props.projectSortOrder,
396 props.searchQuery,
397 props.selectedEnvironmentId,
398 props.threadSortOrder,
399 matchedThreadKeys,
400 scopedPendingTasks,
401 scopedProjects,
402 scopedThreads,
403 ],
404 );
405​
406 const hasSearchQuery = props.searchQuery.trim().length > 0;
407 const listLayout = useMemo(
408 () =>
409 threadListV2Enabled
410 ? EMPTY_HOME_LIST_LAYOUT
411 : buildHomeListLayout({
412 groups: projectGroups,
413 displayStates: effectiveGroupDisplayStates,
414 showAllThreads: hasSearchQuery,
415 }),
416 [threadListV2Enabled, projectGroups, effectiveGroupDisplayStates, hasSearchQuery],
417 );
418​
419 const projectCwdByKey = useMemo(() => {
420 const map = new Map<string, string>();
421 for (const project of props.projects) {
422 map.set(scopedProjectKey(project.environmentId, project.id), project.workspaceRoot);
423 }
424 return map;
425 }, [props.projects]);
426​
427 const projectByKey = useMemo(() => {
428 const map = new Map<string, EnvironmentProject>();
429 for (const project of props.projects) {
430 map.set(scopedProjectKey(project.environmentId, project.id), project);
431 }
432 return map;
433 }, [props.projects]);
434​
435 const v2ProjectScopeKey = props.selectedProjectKey;
436 const v2ScopeProjects = useMemo(
437 () =>
438 sortHomeProjectScopes({
439 scopes: projectScopes,
440 threads: props.threads,
441 pendingTasks: props.pendingTasks,
442 projectSortOrder: props.projectSortOrder,
443 }),
444 [
445 props.pendingTasks,
446 props.projects,
447 props.projectSortOrder,
448 props.selectedEnvironmentId,
449 props.threads,
450 projectScopes,
451 ],
452 );
453 const v2ScopedProjectGroup = useMemo(
454 () =>
455 v2ProjectScopeKey === null
456 ? null
457 : (v2ScopeProjects.find(
458 (scope) =>
459 scope.key === v2ProjectScopeKey ||
460 scope.projectRefs.some(
461 (projectRef) =>
462 scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
463 v2ProjectScopeKey,
464 ),
465 ) ?? null),
466 [v2ProjectScopeKey, v2ScopeProjects],
467 );
468 const v2ProjectTitleByProjectKey = useMemo(
469 () =>
470 new Map(
471 v2ScopeProjects.flatMap((scope) =>
472 scope.projectRefs.map(
473 (projectRef) =>
474 [
475 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
476 scope.title,
477 ] as const,
478 ),
479 ),
480 ),
481 [v2ScopeProjects],
482 );
483 const v2ScopedProjectKeys = useMemo(
484 () =>
485 v2ScopedProjectGroup === null
486 ? null
487 : new Set(
488 v2ScopedProjectGroup.projectRefs.map((projectRef) =>
489 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
490 ),
491 ),
492 [v2ScopedProjectGroup],
493 );
494 // Thread List v2 (beta): one flat list in creation order, no grouping.
495 // Settled threads collapse into a recency tail below the card block.
496 // Settled threads stay in the live shell stream (settled ≠ archived), so
497 // the partition works directly off live shells — no snapshot merging or
498 // optimistic holds.
499 const handleSettleThread = useCallback(
500 (thread: EnvironmentThreadShell) => {
501 void props.onSettleThread(thread);
502 },
503 [props.onSettleThread],
504 );
505 const handleSnoozeThread = useCallback(
506 (thread: EnvironmentThreadShell, snoozedUntil: string) => {
507 void props.onSnoozeThread(thread, snoozedUntil);
508 },
509 [props.onSnoozeThread],
510 );
511 const handleUnsnoozeThread = useCallback(
512 (thread: EnvironmentThreadShell) => {
513 void props.onUnsnoozeThread(thread);
514 },
515 [props.onUnsnoozeThread],
516 );
517 const handlePinThread = useCallback(
518 (thread: EnvironmentThreadShell) => {
519 void props.onPinThread(thread);
520 },
521 [props.onPinThread],
522 );
523 const handleMovePinnedThread = useCallback(
524 (thread: EnvironmentThreadShell, direction: "up" | "down") => {
525 void props.onMovePinnedThread(thread, direction);
526 },
527 [props.onMovePinnedThread],
528 );
529 const handleUnpinThread = useCallback(
530 (thread: EnvironmentThreadShell) => {
531 void props.onUnpinThread(thread);
532 },
533 [props.onUnpinThread],
534 );
535 const handleRegenerateThreadTitle = useCallback(
536 (thread: EnvironmentThreadShell) => {
537 void props.onRegenerateThreadTitle(thread);
538 },
539 [props.onRegenerateThreadTitle],
540 );
541 const handleDeleteThread = props.onDeleteThread;
542 const handleUnsettleThread = props.onUnsettleThread;
543 // The settled tail renders in pages; expansion resets when the filter
544 // context changes so environment/search flips never inherit a deep page.
545 const [settledVisibleCount, setSettledVisibleCount] = useState(
546 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
547 );
548 const settledResetKey = `${props.selectedEnvironmentId ?? "all"}:${v2ProjectScopeKey ?? "all"}:${props.searchQuery.trim()}`;
549 const lastSettledResetKeyRef = useRef(settledResetKey);
550 if (lastSettledResetKeyRef.current !== settledResetKey) {
551 lastSettledResetKeyRef.current = settledResetKey;
552 setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
553 }
554 const showMoreSettled = useCallback(
555 () => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
556 [],
557 );
558 const {
559 loaded: shelfPreferencesLoaded,
560 settledShelfExpanded,
561 snoozedShelfExpanded,
562 toggleSettledShelf,
563 toggleSnoozedShelf,
564 } = useThreadListV2ShelfPreferences();
565 // The queued-start and snooze helpers need a clock while the list stays open.
566 const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
567 // Snooze wake times are second-precise; a counter bumped exactly at the
568 // next wake boundary re-runs the partition with a fresh clock so a woken
569 // thread reappears immediately instead of on the next minute tick.
570 const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
571 useFocusEffect(
572 useCallback(() => {
573 if (!threadListV2Enabled) return;
574 // Refresh immediately on enable or focus because the previous value can be hours old.
575 setNowMinute(new Date().toISOString().slice(0, 16));
576 const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
577 return () => clearInterval(id);
578 }, [threadListV2Enabled]),
579 );
580 // Threads on servers without the settlement capability never classify as
581 // settled (the user could neither un-settle nor pin them).
582 const serverConfigs = useAtomValue(environmentServerConfigsAtom);
583 const settlementEnvironmentIds = useMemo(() => {
584 const supported = new Set<EnvironmentId>();
585 for (const [environmentId, config] of serverConfigs) {
586 if (config.environment.capabilities.threadSettlement === true) {
587 supported.add(environmentId);
588 }
589 }
590 return supported;
591 }, [serverConfigs]);
592 const snoozeEnvironmentIds = useMemo(() => {
593 const supported = new Set<EnvironmentId>();
594 for (const [environmentId, config] of serverConfigs) {
595 if (config.environment.capabilities.threadSnooze === true) {
596 supported.add(environmentId);
597 }
598 }
599 return supported;
600 }, [serverConfigs]);
601 const pinningEnvironmentIds = useMemo(() => {
602 const supported = new Set<EnvironmentId>();
603 for (const [environmentId, config] of serverConfigs) {
604 if (config.environment.capabilities.threadPinning === true) {
605 supported.add(environmentId);
606 }
607 }
608 return supported;
609 }, [serverConfigs]);
610 const pinReorderEnvironmentIds = useMemo(() => {
611 const supported = new Set<EnvironmentId>();
612 for (const [environmentId, config] of serverConfigs) {
613 if (config.environment.capabilities.threadPinReorder === true) {
614 supported.add(environmentId);
615 }
616 }
617 return supported;
618 }, [serverConfigs]);
619 const titleRegenerationEnvironmentIds = useMemo(() => {
620 const supported = new Set<EnvironmentId>();
621 for (const [environmentId, config] of serverConfigs) {
622 if (config.environment.capabilities.threadTitleRegeneration === true) {
623 supported.add(environmentId);
624 }
625 }
626 return supported;
627 }, [serverConfigs]);
628 const machineByEnvironmentId = useMemo(
629 () =>
630 new Map(
631 [...serverConfigs].map(
632 ([environmentId, config]) =>
633 [environmentId, resolveEnvironmentMachineKind(config)] as const,
634 ),
635 ),
636 [serverConfigs],
637 );
638 // Canonical arranged pinned order (reorder-capable threads only) for the
639 // Move up/down position flags. Computed from all shells, not the rendered
640 // list, so search/scope filtering never disables or misdirects a move.
641 const arrangedPinnedKeys = useMemo(() => {
642 const pinned = sortPinnedThreadsByOrderKey(
643 props.threads.filter(
644 (thread) =>
645 thread.pinnedAt != null &&
646 thread.archivedAt === null &&
647 pinReorderEnvironmentIds.has(thread.environmentId),
648 ),
649 );
650 return pinned.map((thread) => `${thread.environmentId}:${thread.id}`);
651 }, [pinReorderEnvironmentIds, props.threads]);
652 const threadListV2Layout = useMemo(() => {
653 if (!threadListV2Enabled)
654 return {
655 items: [],
656 hiddenSettledCount: 0,
657 snoozedCount: 0,
658 snoozedShelfHeaderIndex: null,
659 settledCount: 0,
660 settledShelfHeaderIndex: null,
661 nextSnoozeWakeAt: null,
662 };
663 // Settled threads are live shells; archived threads keep their original
664 // "hidden from lists" meaning.
665 return buildThreadListV2Items({
666 threads: props.threads.filter((thread) => thread.archivedAt === null),
667 environmentId: props.selectedEnvironmentId,
668 projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
669 searchQuery: props.searchQuery,
670 matchedThreadKeys,
671 settlementEnvironmentIds,
672 snoozeEnvironmentIds,
673 settledLimit: settledVisibleCount,
674 now: new Date().toISOString(),
675 snoozedShelfExpanded,
676 settledShelfExpanded,
677 selectedThreadKey: null,
678 });
679 }, [
680 nowMinute,
681 snoozeWakeTick,
682 snoozedShelfExpanded,
683 settledShelfExpanded,
684 settledVisibleCount,
685 settlementEnvironmentIds,
686 snoozeEnvironmentIds,
687 props.searchQuery,
688 props.selectedEnvironmentId,
689 props.threads,
690 matchedThreadKeys,
691 threadListV2Enabled,
692 v2ScopedProjectGroup,
693 ]);
694 // Re-partition the moment the earliest snooze expires (clamped to the
695 // signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
696 const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
697 useEffect(() => {
698 if (nextSnoozeWakeAt === null) return;
699 const wakeAtMs = Date.parse(nextSnoozeWakeAt);
700 if (Number.isNaN(wakeAtMs)) return;
701 const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
702 const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
703 return () => clearTimeout(id);
704 // snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
705 // unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
706 // range) the boundary string is identical and the chain would die.
707 }, [nextSnoozeWakeAt, snoozeWakeTick]);
708 // Queued tasks are not thread shells, so the v2 partition never sees them;
709 // they are spliced in below the active block and stay visible and deletable
710 // while their environment is offline. Same environment scope and search
711 // filter as the list itself.
712 const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
713 const v2PendingTasks = useMemo(
714 () =>
715 props.pendingTasks.filter(
716 (pendingTask) =>
717 (props.selectedEnvironmentId === null ||
718 pendingTask.message.environmentId === props.selectedEnvironmentId) &&
719 (v2ScopedProjectKeys === null ||
720 v2ScopedProjectKeys.has(
721 scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
722 )) &&
723 (v2SearchQuery.length === 0 ||
724 pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
725 ),
726 [props.pendingTasks, props.selectedEnvironmentId, v2ScopedProjectKeys, v2SearchQuery],
727 );
728 const threadListV2Items = useMemo(
729 () =>
730 buildThreadListV2ListItems({
731 items: threadListV2Layout.items,
732 pendingTasks: v2PendingTasks,
733 snoozedCount: threadListV2Layout.snoozedCount,
734 snoozedShelfExpanded,
735 snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
736 settledCount: threadListV2Layout.settledCount,
737 settledShelfExpanded,
738 settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
739 snoozeLabelNow: `${nowMinute}:00.000Z`,
740 }),
741 [settledShelfExpanded, snoozedShelfExpanded, threadListV2Layout, v2PendingTasks],
742 );
743​
744 const renderV2Item = useCallback(
745 ({ item, index }: { readonly item: ThreadListV2ListItem; readonly index: number }) => {
746 const nextItem = threadListV2Items[index + 1];
747 const showTrailingDivider =
748 nextItem?.type === "v2-thread" ||
749 (nextItem?.type === "v2-pending" && !nextItem.showPendingDivider);
750 if (item.type === "v2-pending") {
751 const pendingScopeKey = scopedProjectKey(
752 item.pendingTask.message.environmentId,
753 item.pendingTask.creation.projectId,
754 );
755 return (
756 <ThreadListV2PendingRow
757 pendingTask={item.pendingTask}
758 project={projectByKey.get(pendingScopeKey) ?? null}
759 projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}
760 environmentLabel={
761 Object.keys(props.savedConnectionsById).length > 1
762 ? (props.savedConnectionsById[item.pendingTask.message.environmentId]
763 ?.environmentLabel ?? null)
764 : null
765 }
766 environmentMachine={machineByEnvironmentId.get(item.pendingTask.message.environmentId)}
767 showPendingDivider={item.showPendingDivider}
768 showTrailingDivider={showTrailingDivider}
769 onSelectPendingTask={props.onSelectPendingTask}
770 onDeletePendingTask={props.onDeletePendingTask}
771 />
772 );
773 }
774 if (item.type === "v2-snoozed-shelf") {
775 return (
776 <ThreadListV2SnoozedShelfHeader
777 count={item.count}
778 disabled={!shelfPreferencesLoaded}
779 expanded={item.expanded}
780 onToggle={toggleSnoozedShelf}
781 />
782 );
783 }
784 if (item.type === "v2-settled-shelf") {
785 return (
786 <ThreadListV2SettledShelfHeader
787 count={item.count}
788 disabled={!shelfPreferencesLoaded}
789 expanded={item.expanded}
790 onToggle={toggleSettledShelf}
791 />
792 );
793 }
794 const thread = item.item.thread;
795 return (
796 <ThreadListV2Row
797 thread={thread}
798 variant={item.item.variant}
799 snoozed={item.item.snoozed}
800 pinned={item.item.pinned}
801 snoozePresetMinute={nowMinute}
802 snoozeWakeLabelText={item.snoozeWakeLabelText}
803 showTrailingDivider={showTrailingDivider}
804 project={
805 projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
806 }
807 projectTitle={v2ProjectTitleByProjectKey.get(
808 scopedProjectKey(thread.environmentId, thread.projectId),
809 )}
810 providerDriver={
811 serverConfigs
812 .get(thread.environmentId)
813 ?.providers.find(
814 (provider) =>
815 provider.instanceId ===
816 (thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
817 )?.driver ?? null
818 }
819 environmentLabel={
820 Object.keys(props.savedConnectionsById).length > 1
821 ? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
822 : null
823 }
824 environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
825 searchMatch={threadSearchMatchByKey.get(
826 threadSearchMatchKey({
827 environmentId: thread.environmentId,
828 threadId: thread.id,
829 }),
830 )}
831 searchQuery={props.searchQuery}
832 onSelectThread={props.onSelectThread}
833 onDeleteThread={handleDeleteThread}
834 onArchiveThread={props.onArchiveThread}
835 onRegenerateThreadTitle={handleRegenerateThreadTitle}
836 titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
837 settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
838 onSettleThread={handleSettleThread}
839 snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
840 pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
841 pinReorderSupported={pinReorderEnvironmentIds.has(thread.environmentId)}
842 canMovePinnedUp={arrangedPinnedKeys.indexOf(`${thread.environmentId}:${thread.id}`) > 0}
843 canMovePinnedDown={(() => {
844 const index = arrangedPinnedKeys.indexOf(`${thread.environmentId}:${thread.id}`);
845 return index !== -1 && index < arrangedPinnedKeys.length - 1;
846 })()}
847 onSnoozeThread={handleSnoozeThread}
848 onUnsnoozeThread={handleUnsnoozeThread}
849 onUnsettleThread={handleUnsettleThread}
850 onPinThread={handlePinThread}
851 onUnpinThread={handleUnpinThread}
852 onMovePinnedThread={handleMovePinnedThread}
853 projectCwd={
854 projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
855 }
856 onSwipeableClose={handleSwipeableClose}
857 onSwipeableWillOpen={handleSwipeableWillOpen}
858 />
859 );
860 },
861 [
862 handleDeleteThread,
863 arrangedPinnedKeys,
864 handleMovePinnedThread,
865 handlePinThread,
866 handleRegenerateThreadTitle,
867 handleSettleThread,
868 handleSnoozeThread,
869 handleUnpinThread,
870 handleUnsnoozeThread,
871 handleSwipeableClose,
872 handleSwipeableWillOpen,
873 handleUnsettleThread,
874 pinningEnvironmentIds,
875 machineByEnvironmentId,
876 pinReorderEnvironmentIds,
877 projectByKey,
878 projectCwdByKey,
879 props.onArchiveThread,
880 props.onDeletePendingTask,
881 props.onSelectPendingTask,
882 props.onSelectThread,
883 props.savedConnectionsById,
884 serverConfigs,
885 shelfPreferencesLoaded,
886 settlementEnvironmentIds,
887 snoozeEnvironmentIds,
888 threadListV2Items,
889 threadSearchMatchByKey,
890 titleRegenerationEnvironmentIds,
891 toggleSettledShelf,
892 toggleSnoozedShelf,
893 v2ProjectTitleByProjectKey,
894 props.searchQuery,
895 nowMinute,
896 ],
897 );
898 const v2KeyExtractor = useCallback((item: ThreadListV2ListItem) => item.key, []);
899​
900 // FlatList treats a changed extraData identity as "re-render every visible
901 // row", so an inline object literal would invalidate all rows on every
902 // HomeScreen render.
903 const v2ExtraData = useMemo(
904 () => ({
905 projectByKey,
906 projectCwdByKey,
907 projectTitleByProjectKey: v2ProjectTitleByProjectKey,
908 serverConfigs,
909 savedConnectionsById: props.savedConnectionsById,
910 searchQuery: props.searchQuery,
911 snoozePresetMinute: nowMinute,
912 threadSearchMatchByKey,
913 }),
914 [
915 projectByKey,
916 projectCwdByKey,
917 props.searchQuery,
918 props.savedConnectionsById,
919 serverConfigs,
920 nowMinute,
921 threadSearchMatchByKey,
922 v2ProjectTitleByProjectKey,
923 ],
924 );
925​
926 const extraData = useMemo(
927 () => ({
928 projectCwdByKey,
929 savedConnectionsById: props.savedConnectionsById,
930 searchQuery: props.searchQuery,
931 threadSearchMatchByKey,
932 }),
933 [projectCwdByKey, props.savedConnectionsById, props.searchQuery, threadSearchMatchByKey],
934 );
935​
936 const renderItem = useCallback(
937 ({ item }: LegendListRenderItemProps<HomeListItem>) => {
938 switch (item.type) {
939 case "header":
940 return (
941 <ThreadListGroupHeader
942 variant="compact"
943 collapsed={item.collapsed}
944 isFirst={item.isFirst}
945 groupKey={item.group.key}
946 onGroupAction={updateGroupDisplay}
947 // Aggregated groups (same repo across machines) have no single
948 // target project, and `pending-project:` groups hold a placeholder
949 // built from queued-task metadata rather than a real project shell,
950 // so the quick new-thread button is single-real-project only.
951 newThreadTarget={item.group.newThreadTarget}
952 onNewThread={props.onNewThreadInProject}
953 project={item.group.representative}
954 threadCount={item.group.threads.length + item.group.pendingTasks.length}
955 title={item.group.title}
956 />
957 );
958 case "pending-task":
959 return (
960 <PendingTaskListRow
961 variant="compact"
962 pendingTask={item.pendingTask}
963 environmentLabel={
964 props.savedConnectionsById[item.pendingTask.message.environmentId]
965 ?.environmentLabel ?? null
966 }
967 environmentMachine={machineByEnvironmentId.get(
968 item.pendingTask.message.environmentId,
969 )}
970 isLast={item.isLast}
971 onSelectPendingTask={props.onSelectPendingTask}
972 onDeletePendingTask={props.onDeletePendingTask}
973 />
974 );
975 case "thread": {
976 const thread = item.thread;
977 return (
978 <ThreadListRow
979 variant="compact"
980 thread={thread}
981 environmentLabel={
982 props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
983 }
984 environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
985 projectCwd={
986 projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ??
987 null
988 }
989 isLast={item.isLast}
990 searchMatch={threadSearchMatchByKey.get(
991 threadSearchMatchKey({
992 environmentId: thread.environmentId,
993 threadId: thread.id,
994 }),
995 )}
996 searchQuery={props.searchQuery}
997 onArchiveThread={props.onArchiveThread}
998 onDeleteThread={props.onDeleteThread}
999 onRegenerateThreadTitle={handleRegenerateThreadTitle}
1000 titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
1001 onSelectThread={props.onSelectThread}
1002 onSwipeableClose={handleSwipeableClose}
1003 onSwipeableWillOpen={handleSwipeableWillOpen}
1004 />
1005 );
1007 case "show-more":
1008 return (
1009 <ThreadListShowMoreRow
1010 variant="compact"
1011 hiddenCount={item.hiddenCount}
1012 canShowLess={item.canShowLess}
1013 groupKey={item.groupKey}
1014 onGroupAction={updateGroupDisplay}
1015 />
1016 );
1018 },
1020 handleSwipeableClose,
1021 handleSwipeableWillOpen,
1022 handleRegenerateThreadTitle,
1023 machineByEnvironmentId,
1024 projectCwdByKey,
1025 props.onArchiveThread,
1026 props.onDeletePendingTask,
1027 props.onDeleteThread,
1028 props.onNewThreadInProject,
1029 props.onSelectPendingTask,
1030 props.onSelectThread,
1031 props.searchQuery,
1032 props.savedConnectionsById,
1033 threadSearchMatchByKey,
1034 titleRegenerationEnvironmentIds,
1035 updateGroupDisplay,
1036 ],
1037 );
1038​
1039 const keyExtractor = useCallback((item: HomeListItem) => item.key, []);
1040​
1041 /* Empty states */
1042 // The signal must ignore the search/environment filters: an active query
1043 // that matches nothing needs the in-list "No results" state, not the
1044 // full-page "No threads yet". Settled threads are unarchived live shells,
1045 // so the v1 check already covers v2.
1046 const hasAnyThreads =
1047 props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
1048 const hasResults = threadListV2Enabled ? threadListV2Items.length > 0 : projectGroups.length > 0;
1049 const selectedEnvironmentLabel =
1050 props.selectedEnvironmentId === null
1051 ? null
1052 : (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
1053 "this environment");
1054 // Connection state surfaces in the header title slot
1055 // (WorkspaceConnectionTitle) — nothing renders inside the list, so
1056 // reconnects never shift the rows.
1057 const emptyState = deriveEmptyState({
1058 catalogState: props.catalogState,
1059 projectCount: props.projects.length,
1060 });
1061​
1062 if (!hasAnyThreads) {
1063 return (
1064 <View
1065 className="flex-1 items-center justify-center bg-screen px-8"
1066 style={{
1067 paddingBottom: Math.max(insets.bottom, 24) + iosBottomToolbarClearance,
1068 paddingTop: NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 72 : 0,
1069 }}
1071 <View className="w-full max-w-[430px]">
1072 <EmptyState
1073 title={emptyState.title}
1074 detail={emptyState.detail}
1075 actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
1076 onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
1077 variant="plain"
1078 />
1079 {emptyState.loading ? (
1080 <View className="mt-4 items-center">
1081 <ActivityIndicator colorClassName={"accent-icon-muted"} />
1082 </View>
1083 ) : null}
1084 </View>
1085 </View>
1086 );
1088​
1089 const listHeader = Platform.OS === "ios" ? null : <HomeTopContentSpacer />;
1090​
1091 // Project scoping lives in the header filter menu (no inline chip row on
1092 // mobile — the menu is the one filter surface).
1093 const v2ListHeader = listHeader;
1094​
1095 const listEmpty = !hasResults ? (
1096 hasSearchQuery && threadSearch.isPending ? null : hasSearchQuery ? (
1097 <EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
1098 ) : selectedProjectScope !== null ? (
1099 <EmptyState
1100 title={`No threads in ${selectedProjectScope.title}`}
1101 detail="Choose another project or create a new task."
1102 />
1103 ) : selectedEnvironmentLabel ? (
1104 <EmptyState
1105 title={`No threads in ${selectedEnvironmentLabel}`}
1106 detail="Choose another environment or create a new task."
1107 />
1108 ) : (
1109 <EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
1111 ) : null;
1112 // Use the v2 project scope for its empty state. Snoozed threads need no
1113 // special empty state: their shelf header is a list row even while collapsed.
1114 const v2ListEmpty =
1115 hasSearchQuery && threadSearch.isPending ? null : hasSearchQuery ? (
1116 <EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
1117 ) : v2ScopedProjectGroup !== null ? (
1118 <EmptyState
1119 title={`No threads in ${v2ScopedProjectGroup.title}`}
1120 detail="Choose another project or create a new task."
1121 />
1122 ) : (
1123 listEmpty
1124 );
1125​
1126 if (threadListV2Enabled) {
1127 return (
1128 <View className="flex-1 bg-screen">
1129 <SwipeableScrollGateProvider enabled={swipeEnabled}>
1130 <FlatList
1131 data={threadListV2Items}
1132 renderItem={renderV2Item}
1133 keyExtractor={v2KeyExtractor}
1134 extraData={v2ExtraData}
1135 ListHeaderComponent={v2ListHeader}
1136 ListFooterComponent={
1137 settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? (
1138 <Pressable
1139 accessibilityRole="button"
1140 accessibilityLabel={`Show ${Math.min(threadListV2Layout.hiddenSettledCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
1141 onPress={showMoreSettled}
1142 className="mx-4 mt-2 items-center rounded-lg border border-dashed border-border py-2.5"
1143 style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
1145 <Text className="text-xs font-t3-medium text-foreground-muted">
1146 Show more ({threadListV2Layout.hiddenSettledCount} settled hidden)
1147 </Text>
1148 </Pressable>
1149 ) : null
1151 ListEmptyComponent={v2ListEmpty}
1152 style={{ flex: 1 }}
1153 automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
1154 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
1155 showsVerticalScrollIndicator={false}
1156 keyboardDismissMode="on-drag"
1157 keyboardShouldPersistTaps="handled"
1158 {...scrollGateHandlers}
1159 scrollEventThrottle={16}
1160 contentContainerStyle={{
1161 paddingBottom:
1162 Platform.OS === "ios"
1163 ? Math.max(insets.bottom, 24) + 96 + iosBottomToolbarClearance
1164 : Math.max(insets.bottom, 16) + 88,
1165 }}
1166 />
1167 </SwipeableScrollGateProvider>
1168 </View>
1169 );
1171​
1172 return (
1173 <View className="flex-1 bg-screen">
1174 {/* Sticky headers are deliberately not wired up: LegendList's JS sticky
1175 implementation mispositions pinned headers at mount under iOS
1176 automatic content insets (headers render one nav-inset too low until
1177 the first scroll event) and blanks non-pinned headers after
1178 collapse/expand data changes. The flattened layout still exposes
1179 `stickyHeaderIndices` if this gets revisited. */}
1180 <SwipeableScrollGateProvider enabled={swipeEnabled}>
1181 <LegendList
1182 ref={listRef}
1183 data={listLayout.items}
1184 renderItem={renderItem}
1185 keyExtractor={keyExtractor}
1186 itemsAreEqual={homeListItemsAreEqual}
1187 drawDistance={500}
1188 estimatedItemSize={ESTIMATED_THREAD_ROW_HEIGHT}
1189 extraData={extraData}
1190 ListHeaderComponent={listHeader}
1191 ListEmptyComponent={listEmpty}
1192 style={{ flex: 1 }}
1193 automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
1194 contentInsetAdjustmentBehavior={NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"}
1195 showsVerticalScrollIndicator={false}
1196 keyboardDismissMode="on-drag"
1197 keyboardShouldPersistTaps="handled"
1198 {...scrollGateHandlers}
1199 recycleItems
1200 scrollEventThrottle={16}
1201 contentContainerStyle={{
1202 // Android reserves room for the floating new-task FAB
1203 // (56 button + 16 gap + bottom inset). Pre-glass iOS shows a
1204 // standard 44pt bottom toolbar that overlays the list and is not
1205 // reflected in insets while contentInsetAdjustmentBehavior is
1206 // "never".
1207 paddingBottom:
1208 Platform.OS === "ios"
1209 ? Math.max(insets.bottom, 24) + 24 + iosBottomToolbarClearance
1210 : Math.max(insets.bottom, 16) + 88,
1211 }}
1212 scrollIndicatorInsets={
1213 Platform.OS === "ios"
1214 ? {
1215 bottom: Math.max(insets.bottom, 16) + 24 + iosBottomToolbarClearance,
1216 top: 0,
1218 : undefined
1220 />
1221 </SwipeableScrollGateProvider>
1222 </View>
1223 );