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