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