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 autoSettleOnMerge =
211 !AsyncResult.isSuccess(preferencesResult) ||
212 preferencesResult.value.autoSettleOnMerge !== false;
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 accentColor = useThemeColor("--color-icon-muted");
218 const iosBottomToolbarClearance =
219 Platform.OS === "ios" && !NATIVE_LIQUID_GLASS_SUPPORTED
220 ? PRE_LIQUID_GLASS_BOTTOM_TOOLBAR_HEIGHT
221 : 0;
222 const searchEnvironmentIds = useMemo(
223 () =>
224 props.selectedEnvironmentId === null
225 ? props.environments
226 .filter((environment) => environment.connectionState === "connected")
227 .map((environment) => environment.environmentId)
228 : props.environments.some(
229 (environment) =>
230 environment.environmentId === props.selectedEnvironmentId &&
231 environment.connectionState === "connected",
232 )
233 ? [props.selectedEnvironmentId]
234 : [],
235 [props.environments, props.selectedEnvironmentId],
236 );
237 const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery);
238 const threadSearchMatchByKey = useMemo(() => {
239 const matches = new Map<string, EnvironmentThreadSearchMatch>();
240 for (const match of threadSearch.matches) {
241 if (match.source === "user" || match.source === "assistant") {
242 matches.set(threadSearchMatchKey(match), match);
243 }
244 }
245 return matches;
246 }, [threadSearch.matches]);
247 const matchedThreadKeys = useMemo(
248 () => new Set(threadSearch.matches.map(threadSearchMatchKey)),
249 [threadSearch.matches],
250 );
251 const effectiveGroupDisplayStates = useMemo(() => {
252 const next = new Map(groupDisplayStates);
253 if (!AsyncResult.isSuccess(preferencesResult)) {
254 return next;
255 }
256 for (const key of preferencesResult.value.collapsedProjectGroups ?? []) {
257 const existing = next.get(key);
258 next.set(key, {
259 ...(existing ?? DEFAULT_GROUP_DISPLAY_STATE),
260 collapsed: true,
261 });
262 }
263 return next;
264 }, [groupDisplayStates, preferencesResult]);
265 const effectiveGroupDisplayStatesRef = useRef(effectiveGroupDisplayStates);
266 effectiveGroupDisplayStatesRef.current = effectiveGroupDisplayStates;
267
268 const updateGroupDisplay = useCallback(
269 (key: string, action: HomeGroupDisplayAction) => {
270 const next = new Map(effectiveGroupDisplayStatesRef.current);
271 next.set(key, nextGroupDisplayState(next.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action));
272 effectiveGroupDisplayStatesRef.current = next;
273 setGroupDisplayStates(next);
274 if (action === "toggle-collapsed") {
275 const collapsedProjectGroups: string[] = [];
276 for (const [groupKey, state] of next) {
277 if (state.collapsed) {
278 collapsedProjectGroups.push(groupKey);
279 }
280 }
281 savePreferences({ collapsedProjectGroups });
282 }
283 },
284 [savePreferences],
285 );
286
287 const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
288 if (openSwipeableRef.current !== methods) {
289 openSwipeableRef.current?.close();
290 openSwipeableRef.current = methods;
291 }
292 }, []);
293
294 const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
295 if (openSwipeableRef.current === methods) {
296 openSwipeableRef.current = null;
297 }
298 }, []);
299
300 const handleScrollBeginDrag = useCallback(() => {
301 openSwipeableRef.current?.close();
302 }, []);
303 const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
304 onScrollBeginDrag: handleScrollBeginDrag,
305 });
306
307 const projectScopes = useMemo(
308 () =>
309 buildHomeProjectScopes({
310 projects: props.projects,
311 environmentId: props.selectedEnvironmentId,
312 projectGroupingMode: props.projectGroupingMode,
313 }),
314 [props.projectGroupingMode, props.projects, props.selectedEnvironmentId],
315 );
316 const selectedProjectScope = useMemo(
317 () =>
318 props.selectedProjectKey === null
319 ? null
320 : (projectScopes.find(
321 (scope) =>
322 scope.key === props.selectedProjectKey ||
323 scope.projectRefs.some(
324 (projectRef) =>
325 scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
326 props.selectedProjectKey,
327 ),
328 ) ?? null),
329 [projectScopes, props.selectedProjectKey],
330 );
331 const selectedProjectRefKeys = useMemo(
332 () =>
333 selectedProjectScope === null
334 ? null
335 : new Set(
336 selectedProjectScope.projectRefs.map((projectRef) =>
337 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
338 ),
339 ),
340 [selectedProjectScope],
341 );
342 const scopedProjects = useMemo(
343 () =>
344 selectedProjectRefKeys === null
345 ? props.projects
346 : props.projects.filter((project) =>
347 selectedProjectRefKeys.has(scopedProjectKey(project.environmentId, project.id)),
348 ),
349 [props.projects, selectedProjectRefKeys],
350 );
351 const scopedThreads = useMemo(
352 () =>
353 selectedProjectRefKeys === null
354 ? props.threads
355 : props.threads.filter((thread) =>
356 selectedProjectRefKeys.has(scopedProjectKey(thread.environmentId, thread.projectId)),
357 ),
358 [props.threads, selectedProjectRefKeys],
359 );
360 const scopedPendingTasks = useMemo(
361 () =>
362 selectedProjectRefKeys === null
363 ? props.pendingTasks
364 : props.pendingTasks.filter((pendingTask) =>
365 selectedProjectRefKeys.has(
366 scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
367 ),
368 ),
369 [props.pendingTasks, selectedProjectRefKeys],
370 );
371
372 const projectGroups = useMemo(
373 () =>
374 buildHomeThreadGroups({
375 projects: scopedProjects,
376 threads: scopedThreads,
377 pendingTasks: scopedPendingTasks,
378 environmentId: props.selectedEnvironmentId,
379 searchQuery: props.searchQuery,
380 matchedThreadKeys,
381 projectSortOrder: props.projectSortOrder,
382 threadSortOrder: props.threadSortOrder,
383 projectGroupingMode: props.projectGroupingMode,
384 }),
385 [
386 props.projectGroupingMode,
387 props.projectSortOrder,
388 props.searchQuery,
389 props.selectedEnvironmentId,
390 props.threadSortOrder,
391 matchedThreadKeys,
392 scopedPendingTasks,
393 scopedProjects,
394 scopedThreads,
395 ],
396 );
397
398 const hasSearchQuery = props.searchQuery.trim().length > 0;
399 const listLayout = useMemo(
400 () =>
401 buildHomeListLayout({
402 groups: projectGroups,
403 displayStates: effectiveGroupDisplayStates,
404 showAllThreads: hasSearchQuery,
405 }),
406 [projectGroups, effectiveGroupDisplayStates, hasSearchQuery],
407 );
408
409 const projectCwdByKey = useMemo(() => {
410 const map = new Map<string, string>();
411 for (const project of props.projects) {
412 map.set(scopedProjectKey(project.environmentId, project.id), project.workspaceRoot);
413 }
414 return map;
415 }, [props.projects]);
416
417 const projectByKey = useMemo(() => {
418 const map = new Map<string, EnvironmentProject>();
419 for (const project of props.projects) {
420 map.set(scopedProjectKey(project.environmentId, project.id), project);
421 }
422 return map;
423 }, [props.projects]);
424
425 const v2ProjectScopeKey = props.selectedProjectKey;
426 const v2ScopeProjects = useMemo(
427 () =>
428 sortHomeProjectScopes({
429 scopes: projectScopes,
430 threads: props.threads,
431 pendingTasks: props.pendingTasks,
432 projectSortOrder: props.projectSortOrder,
433 }),
434 [
435 props.pendingTasks,
436 props.projects,
437 props.projectSortOrder,
438 props.selectedEnvironmentId,
439 props.threads,
440 projectScopes,
441 ],
442 );
443 const v2ScopedProjectGroup = useMemo(
444 () =>
445 v2ProjectScopeKey === null
446 ? null
447 : (v2ScopeProjects.find(
448 (scope) =>
449 scope.key === v2ProjectScopeKey ||
450 scope.projectRefs.some(
451 (projectRef) =>
452 scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
453 v2ProjectScopeKey,
454 ),
455 ) ?? null),
456 [v2ProjectScopeKey, v2ScopeProjects],
457 );
458 const v2ProjectTitleByProjectKey = useMemo(
459 () =>
460 new Map(
461 v2ScopeProjects.flatMap((scope) =>
462 scope.projectRefs.map(
463 (projectRef) =>
464 [
465 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
466 scope.title,
467 ] as const,
468 ),
469 ),
470 ),
471 [v2ScopeProjects],
472 );
473 const v2ScopedProjectKeys = useMemo(
474 () =>
475 v2ScopedProjectGroup === null
476 ? null
477 : new Set(
478 v2ScopedProjectGroup.projectRefs.map((projectRef) =>
479 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
480 ),
481 ),
482 [v2ScopedProjectGroup],
483 );
484 // Thread List v2 (beta): one flat list in creation order, no grouping.
485 // Settled threads collapse into a recency tail below the card block.
486 // Settled threads stay in the live shell stream (settled ≠ archived), so
487 // the partition works directly off live shells — no snapshot merging or
488 // optimistic holds.
489 // PR states stream in per-row. The next partition applies the configured
490 // merge rule and the always-on close rule, matching web.
491 const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
492 ReadonlyMap<string, "open" | "closed" | "merged">
493 >(() => new Map());
494 const handleChangeRequestState = useCallback(
495 (threadKey: string, state: "open" | "closed" | "merged" | null) => {
496 setChangeRequestStateByKey((current) => {
497 if ((current.get(threadKey) ?? null) === state) return current;
498 const next = new Map(current);
499 if (state === null) {
500 next.delete(threadKey);
501 } else {
502 next.set(threadKey, state);
503 }
504 return next;
505 });
506 },
507 [],
508 );
509 const handleSettleThread = useCallback(
510 (thread: EnvironmentThreadShell) => {
511 void props.onSettleThread(thread);
512 },
513 [props.onSettleThread],
514 );
515 const handleSnoozeThread = useCallback(
516 (thread: EnvironmentThreadShell, snoozedUntil: string) => {
517 void props.onSnoozeThread(thread, snoozedUntil);
518 },
519 [props.onSnoozeThread],
520 );
521 const handleUnsnoozeThread = useCallback(
522 (thread: EnvironmentThreadShell) => {
523 void props.onUnsnoozeThread(thread);
524 },
525 [props.onUnsnoozeThread],
526 );
527 const handlePinThread = useCallback(
528 (thread: EnvironmentThreadShell) => {
529 void props.onPinThread(thread);
530 },
531 [props.onPinThread],
532 );
533 const handleMovePinnedThread = useCallback(
534 (thread: EnvironmentThreadShell, direction: "up" | "down") => {
535 void props.onMovePinnedThread(thread, direction);
536 },
537 [props.onMovePinnedThread],
538 );
539 const handleUnpinThread = useCallback(
540 (thread: EnvironmentThreadShell) => {
541 void props.onUnpinThread(thread);
542 },
543 [props.onUnpinThread],
544 );
545 const handleRegenerateThreadTitle = useCallback(
546 (thread: EnvironmentThreadShell) => {
547 void props.onRegenerateThreadTitle(thread);
548 },
549 [props.onRegenerateThreadTitle],
550 );
551 const handleDeleteThread = props.onDeleteThread;
552 const handleUnsettleThread = props.onUnsettleThread;
553 // The settled tail renders in pages; expansion resets when the filter
554 // context changes so environment/search flips never inherit a deep page.
555 const [settledVisibleCount, setSettledVisibleCount] = useState(
556 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
557 );
558 const settledResetKey = `${props.selectedEnvironmentId ?? "all"}:${v2ProjectScopeKey ?? "all"}:${props.searchQuery.trim()}`;
559 const lastSettledResetKeyRef = useRef(settledResetKey);
560 if (lastSettledResetKeyRef.current !== settledResetKey) {
561 lastSettledResetKeyRef.current = settledResetKey;
562 setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
563 }
564 const showMoreSettled = useCallback(
565 () => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
566 [],
567 );
568 const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useState(false);
569 const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
570 const [settledShelfExpanded, setSettledShelfExpanded] = useState(true);
571 const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
572 // now is quantized to the minute and ticks so the inactivity auto-settle
573 // boundary is actually crossed while the app stays open (mirrors web);
574 // without a clock dependency the partition memoizes a frozen "now".
575 const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
576 // Snooze wake times are second-precise; a counter bumped exactly at the
577 // next wake boundary re-runs the partition with a fresh clock so a woken
578 // thread reappears immediately instead of on the next minute tick.
579 const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
580 useEffect(() => {
581 if (!threadListV2Enabled) return;
582 // Refresh immediately on enable: the mount-time value can be hours old
583 // by the time the beta is switched on, which would misclassify the
584 // inactivity auto-settle boundary until the first tick.
585 setNowMinute(new Date().toISOString().slice(0, 16));
586 const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
587 return () => clearInterval(id);
588 }, [threadListV2Enabled]);
589 // Threads on servers without the settlement capability never classify as
590 // settled (the user could neither un-settle nor pin them).
591 const serverConfigs = useAtomValue(environmentServerConfigsAtom);
592 const settlementEnvironmentIds = useMemo(() => {
593 const supported = new Set<EnvironmentId>();
594 for (const [environmentId, config] of serverConfigs) {
595 if (config.environment.capabilities.threadSettlement === true) {
596 supported.add(environmentId);
597 }
598 }
599 return supported;
600 }, [serverConfigs]);
601 const snoozeEnvironmentIds = useMemo(() => {
602 const supported = new Set<EnvironmentId>();
603 for (const [environmentId, config] of serverConfigs) {
604 if (config.environment.capabilities.threadSnooze === true) {
605 supported.add(environmentId);
606 }
607 }
608 return supported;
609 }, [serverConfigs]);
610 const pinningEnvironmentIds = useMemo(() => {
611 const supported = new Set<EnvironmentId>();
612 for (const [environmentId, config] of serverConfigs) {
613 if (config.environment.capabilities.threadPinning === true) {
614 supported.add(environmentId);
615 }
616 }
617 return supported;
618 }, [serverConfigs]);
619 const pinReorderEnvironmentIds = useMemo(() => {
620 const supported = new Set<EnvironmentId>();
621 for (const [environmentId, config] of serverConfigs) {
622 if (config.environment.capabilities.threadPinReorder === true) {
623 supported.add(environmentId);
624 }
625 }
626 return supported;
627 }, [serverConfigs]);
628 const titleRegenerationEnvironmentIds = useMemo(() => {
629 const supported = new Set<EnvironmentId>();
630 for (const [environmentId, config] of serverConfigs) {
631 if (config.environment.capabilities.threadTitleRegeneration === true) {
632 supported.add(environmentId);
633 }
634 }
635 return supported;
636 }, [serverConfigs]);
637 // Canonical arranged pinned order (reorder-capable threads only) for the
638 // Move up/down position flags. Computed from all shells, not the rendered
639 // list, so search/scope filtering never disables or misdirects a move.
640 const arrangedPinnedKeys = useMemo(() => {
641 const pinned = sortPinnedThreadsByOrderKey(
642 props.threads.filter(
643 (thread) =>
644 thread.pinnedAt != null &&
645 thread.archivedAt === null &&
646 pinReorderEnvironmentIds.has(thread.environmentId),
647 ),
648 );
649 return pinned.map((thread) => `${thread.environmentId}:${thread.id}`);
650 }, [pinReorderEnvironmentIds, props.threads]);
651 const threadListV2Layout = useMemo(() => {
652 if (!threadListV2Enabled)
653 return {
654 items: [],
655 hiddenSettledCount: 0,
656 snoozedCount: 0,
657 snoozedShelfHeaderIndex: null,
658 settledCount: 0,
659 settledShelfHeaderIndex: null,
660 nextSnoozeWakeAt: null,
661 };
662 // Settled threads are live shells; archived threads keep their original
663 // "hidden from lists" meaning.
664 return buildThreadListV2Items({
665 threads: props.threads.filter((thread) => thread.archivedAt === null),
666 environmentId: props.selectedEnvironmentId,
667 projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
668 searchQuery: props.searchQuery,
669 matchedThreadKeys,
670 changeRequestStateByKey,
671 autoSettleOnMerge,
672 settlementEnvironmentIds,
673 snoozeEnvironmentIds,
674 settledLimit: settledVisibleCount,
675 now: `${nowMinute}:00.000Z`,
676 snoozeNow: new Date().toISOString(),
677 snoozedShelfExpanded,
678 settledShelfExpanded,
679 selectedThreadKey: null,
680 });
681 }, [
682 changeRequestStateByKey,
683 autoSettleOnMerge,
684 nowMinute,
685 snoozeWakeTick,
686 snoozedShelfExpanded,
687 settledShelfExpanded,
688 settledVisibleCount,
689 settlementEnvironmentIds,
690 snoozeEnvironmentIds,
691 props.searchQuery,
692 props.selectedEnvironmentId,
693 props.threads,
694 matchedThreadKeys,
695 threadListV2Enabled,
696 v2ScopedProjectGroup,
697 ]);
698 // Re-partition the moment the earliest snooze expires (clamped to the
699 // signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
700 const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
701 useEffect(() => {
702 if (nextSnoozeWakeAt === null) return;
703 const wakeAtMs = Date.parse(nextSnoozeWakeAt);
704 if (Number.isNaN(wakeAtMs)) return;
705 const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
706 const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
707 return () => clearTimeout(id);
708 // snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
709 // unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
710 // range) the boundary string is identical and the chain would die.
711 }, [nextSnoozeWakeAt, snoozeWakeTick]);
712 // Queued tasks are not thread shells, so the v2 partition never sees them;
713 // they are spliced in below the active block and stay visible and deletable
714 // while their environment is offline. Same environment scope and search
715 // filter as the list itself.
716 const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
717 const v2PendingTasks = useMemo(
718 () =>
719 props.pendingTasks.filter(
720 (pendingTask) =>
721 (props.selectedEnvironmentId === null ||
722 pendingTask.message.environmentId === props.selectedEnvironmentId) &&
723 (v2ScopedProjectKeys === null ||
724 v2ScopedProjectKeys.has(
725 scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
726 )) &&
727 (v2SearchQuery.length === 0 ||
728 pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
729 ),
730 [props.pendingTasks, props.selectedEnvironmentId, v2ScopedProjectKeys, v2SearchQuery],
731 );
732 const threadListV2Items = useMemo(
733 () =>
734 buildThreadListV2ListItems({
735 items: threadListV2Layout.items,
736 pendingTasks: v2PendingTasks,
737 snoozedCount: threadListV2Layout.snoozedCount,
738 snoozedShelfExpanded,
739 snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
740 settledCount: threadListV2Layout.settledCount,
741 settledShelfExpanded,
742 settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
743 snoozeLabelNow: `${nowMinute}:00.000Z`,
744 }),
745 [settledShelfExpanded, snoozedShelfExpanded, threadListV2Layout, v2PendingTasks],
746 );
747
748 const renderV2Item = useCallback(
749 ({ item, index }: { readonly item: ThreadListV2ListItem; readonly index: number }) => {
750 const nextItem = threadListV2Items[index + 1];
751 const showTrailingDivider =
752 nextItem?.type === "v2-thread" ||
753 (nextItem?.type === "v2-pending" && !nextItem.showPendingDivider);
754 if (item.type === "v2-pending") {
755 const pendingScopeKey = scopedProjectKey(
756 item.pendingTask.message.environmentId,
757 item.pendingTask.creation.projectId,
758 );
759 return (
760 <ThreadListV2PendingRow
761 pendingTask={item.pendingTask}
762 project={projectByKey.get(pendingScopeKey) ?? null}
763 projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}
764 environmentLabel={
765 Object.keys(props.savedConnectionsById).length > 1
766 ? (props.savedConnectionsById[item.pendingTask.message.environmentId]
767 ?.environmentLabel ?? null)
768 : null
769 }
770 showPendingDivider={item.showPendingDivider}
771 showTrailingDivider={showTrailingDivider}
772 onSelectPendingTask={props.onSelectPendingTask}
773 onDeletePendingTask={props.onDeletePendingTask}
774 />
775 );
776 }
777 if (item.type === "v2-snoozed-shelf") {
778 return (
779 <ThreadListV2SnoozedShelfHeader
780 count={item.count}
781 expanded={item.expanded}
782 onToggle={toggleSnoozedShelf}
783 />
784 );
785 }
786 if (item.type === "v2-settled-shelf") {
787 return (
788 <ThreadListV2SettledShelfHeader
789 count={item.count}
790 expanded={item.expanded}
791 onToggle={toggleSettledShelf}
792 />
793 );
794 }
795 const thread = item.item.thread;
796 return (
797 <ThreadListV2Row
798 thread={thread}
799 variant={item.item.variant}
800 snoozed={item.item.snoozed}
801 pinned={item.item.pinned}
802 snoozePresetMinute={nowMinute}
803 snoozeWakeLabelText={item.snoozeWakeLabelText}
804 showTrailingDivider={showTrailingDivider}
805 project={
806 projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
807 }
808 projectTitle={v2ProjectTitleByProjectKey.get(
809 scopedProjectKey(thread.environmentId, thread.projectId),
810 )}
811 providerDriver={
812 serverConfigs
813 .get(thread.environmentId)
814 ?.providers.find(
815 (provider) =>
816 provider.instanceId ===
817 (thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
818 )?.driver ?? null
819 }
820 environmentLabel={
821 Object.keys(props.savedConnectionsById).length > 1
822 ? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
823 : null
824 }
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 onChangeRequestState={handleChangeRequestState}
854 projectCwd={
855 projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
856 }
857 onSwipeableClose={handleSwipeableClose}
858 onSwipeableWillOpen={handleSwipeableWillOpen}
859 />
860 );
861 },
862 [
863 handleChangeRequestState,
864 handleDeleteThread,
865 arrangedPinnedKeys,
866 handleMovePinnedThread,
867 handlePinThread,
868 handleRegenerateThreadTitle,
869 handleSettleThread,
870 handleSnoozeThread,
871 handleUnpinThread,
872 handleUnsnoozeThread,
873 handleSwipeableClose,
874 handleSwipeableWillOpen,
875 handleUnsettleThread,
876 pinningEnvironmentIds,
877 pinReorderEnvironmentIds,
878 projectByKey,
879 projectCwdByKey,
880 props.onArchiveThread,
881 props.onDeletePendingTask,
882 props.onSelectPendingTask,
883 props.onSelectThread,
884 props.savedConnectionsById,
885 serverConfigs,
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 isLast={item.isLast}
968 onSelectPendingTask={props.onSelectPendingTask}
969 onDeletePendingTask={props.onDeletePendingTask}
970 />
971 );
972 case "thread": {
973 const thread = item.thread;
974 return (
975 <ThreadListRow
976 variant="compact"
977 thread={thread}
978 environmentLabel={
979 props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
980 }
981 projectCwd={
982 projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ??
983 null
984 }
985 isLast={item.isLast}
986 searchMatch={threadSearchMatchByKey.get(
987 threadSearchMatchKey({
988 environmentId: thread.environmentId,
989 threadId: thread.id,
990 }),
991 )}
992 searchQuery={props.searchQuery}
993 onArchiveThread={props.onArchiveThread}
994 onDeleteThread={props.onDeleteThread}
995 onRegenerateThreadTitle={handleRegenerateThreadTitle}
996 titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
997 onSelectThread={props.onSelectThread}
998 onSwipeableClose={handleSwipeableClose}
999 onSwipeableWillOpen={handleSwipeableWillOpen}
1000 />
1001 );
1002 }
1003 case "show-more":
1004 return (
1005 <ThreadListShowMoreRow
1006 variant="compact"
1007 hiddenCount={item.hiddenCount}
1008 canShowLess={item.canShowLess}
1009 groupKey={item.groupKey}
1010 onGroupAction={updateGroupDisplay}
1011 />
1012 );
1013 }
1014 },
1015 [
1016 handleSwipeableClose,
1017 handleSwipeableWillOpen,
1018 handleRegenerateThreadTitle,
1019 projectCwdByKey,
1020 props.onArchiveThread,
1021 props.onDeletePendingTask,
1022 props.onDeleteThread,
1023 props.onNewThreadInProject,
1024 props.onSelectPendingTask,
1025 props.onSelectThread,
1026 props.searchQuery,
1027 props.savedConnectionsById,
1028 threadSearchMatchByKey,
1029 titleRegenerationEnvironmentIds,
1030 updateGroupDisplay,
1031 ],
1032 );
1033
1034 const keyExtractor = useCallback((item: HomeListItem) => item.key, []);
1035
1036 /* Empty states */
1037 // The signal must ignore the search/environment filters: an active query
1038 // that matches nothing needs the in-list "No results" state, not the
1039 // full-page "No threads yet". Settled threads are unarchived live shells,
1040 // so the v1 check already covers v2.
1041 const hasAnyThreads =
1042 props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
1043 const hasResults = projectGroups.length > 0;
1044 const selectedEnvironmentLabel =
1045 props.selectedEnvironmentId === null
1046 ? null
1047 : (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
1048 "this environment");
1049 // Connection state surfaces in the header title slot
1050 // (WorkspaceConnectionTitle) — nothing renders inside the list, so
1051 // reconnects never shift the rows.
1052 const emptyState = deriveEmptyState({
1053 catalogState: props.catalogState,
1054 projectCount: props.projects.length,
1055 });
1056
1057 if (!hasAnyThreads) {
1058 return (
1059 <View
1060 className="flex-1 items-center justify-center bg-screen px-8"
1061 style={{
1062 paddingBottom: Math.max(insets.bottom, 24) + iosBottomToolbarClearance,
1063 paddingTop: NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 72 : 0,
1064 }}
1065 >
1066 <View className="w-full max-w-[430px]">
1067 <EmptyState
1068 title={emptyState.title}
1069 detail={emptyState.detail}
1070 actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
1071 onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
1072 variant="plain"
1073 />
1074 {emptyState.loading ? (
1075 <View className="mt-4 items-center">
1076 <ActivityIndicator color={accentColor} />
1077 </View>
1078 ) : null}
1079 </View>
1080 </View>
1081 );
1082 }
1083
1084 const listHeader = Platform.OS === "ios" ? null : <HomeTopContentSpacer />;
1085
1086 // Project scoping lives in the header filter menu (no inline chip row on
1087 // mobile — the menu is the one filter surface).
1088 const v2ListHeader = listHeader;
1089
1090 const listEmpty = !hasResults ? (
1091 hasSearchQuery && threadSearch.isPending ? null : hasSearchQuery ? (
1092 <EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
1093 ) : selectedProjectScope !== null ? (
1094 <EmptyState
1095 title={`No threads in ${selectedProjectScope.title}`}
1096 detail="Choose another project or create a new task."
1097 />
1098 ) : selectedEnvironmentLabel ? (
1099 <EmptyState
1100 title={`No threads in ${selectedEnvironmentLabel}`}
1101 detail="Choose another environment or create a new task."
1102 />
1103 ) : (
1104 <EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
1105 )
1106 ) : null;
1107 // Self-contained: v1's listEmpty keys off projectGroups, which ignores the
1108 // v2 project scope, so it can be null (results elsewhere) while this list
1109 // is empty. Snoozed threads need no special empty state: their shelf header
1110 // is a list row even while collapsed.
1111 const v2ListEmpty =
1112 hasSearchQuery && threadSearch.isPending ? null : hasSearchQuery ? (
1113 <EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
1114 ) : v2ScopedProjectGroup !== null ? (
1115 <EmptyState
1116 title={`No threads in ${v2ScopedProjectGroup.title}`}
1117 detail="Choose another project or create a new task."
1118 />
1119 ) : (
1120 listEmpty
1121 );
1122
1123 if (threadListV2Enabled) {
1124 return (
1125 <View className="flex-1 bg-screen">
1126 <SwipeableScrollGateProvider enabled={swipeEnabled}>
1127 <FlatList
1128 data={threadListV2Items}
1129 renderItem={renderV2Item}
1130 keyExtractor={v2KeyExtractor}
1131 extraData={v2ExtraData}
1132 ListHeaderComponent={v2ListHeader}
1133 ListFooterComponent={
1134 settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? (
1135 <Pressable
1136 accessibilityRole="button"
1137 accessibilityLabel={`Show ${Math.min(threadListV2Layout.hiddenSettledCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
1138 onPress={showMoreSettled}
1139 className="mx-4 mt-2 items-center rounded-lg border border-dashed border-border py-2.5"
1140 style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
1141 >
1142 <Text className="text-xs font-t3-medium text-foreground-muted">
1143 Show more ({threadListV2Layout.hiddenSettledCount} settled hidden)
1144 </Text>
1145 </Pressable>
1146 ) : null
1147 }
1148 ListEmptyComponent={v2ListEmpty}
1149 style={{ flex: 1 }}
1150 automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
1151 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
1152 showsVerticalScrollIndicator={false}
1153 keyboardDismissMode="on-drag"
1154 keyboardShouldPersistTaps="handled"
1155 {...scrollGateHandlers}
1156 scrollEventThrottle={16}
1157 contentContainerStyle={{
1158 paddingBottom:
1159 Platform.OS === "ios"
1160 ? Math.max(insets.bottom, 24) + 96 + iosBottomToolbarClearance
1161 : Math.max(insets.bottom, 16) + 88,
1162 }}
1163 />
1164 </SwipeableScrollGateProvider>
1165 </View>
1166 );
1167 }
1168
1169 return (
1170 <View className="flex-1 bg-screen">
1171 {/* Sticky headers are deliberately not wired up: LegendList's JS sticky
1172 implementation mispositions pinned headers at mount under iOS
1173 automatic content insets (headers render one nav-inset too low until
1174 the first scroll event) and blanks non-pinned headers after
1175 collapse/expand data changes. The flattened layout still exposes
1176 `stickyHeaderIndices` if this gets revisited. */}
1177 <SwipeableScrollGateProvider enabled={swipeEnabled}>
1178 <LegendList
1179 ref={listRef}
1180 data={listLayout.items}
1181 renderItem={renderItem}
1182 keyExtractor={keyExtractor}
1183 itemsAreEqual={homeListItemsAreEqual}
1184 drawDistance={500}
1185 estimatedItemSize={ESTIMATED_THREAD_ROW_HEIGHT}
1186 extraData={extraData}
1187 ListHeaderComponent={listHeader}
1188 ListEmptyComponent={listEmpty}
1189 style={{ flex: 1 }}
1190 automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
1191 contentInsetAdjustmentBehavior={NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"}
1192 showsVerticalScrollIndicator={false}
1193 keyboardDismissMode="on-drag"
1194 keyboardShouldPersistTaps="handled"
1195 {...scrollGateHandlers}
1196 recycleItems
1197 scrollEventThrottle={16}
1198 contentContainerStyle={{
1199 // Android reserves room for the floating new-task FAB
1200 // (56 button + 16 gap + bottom inset). Pre-glass iOS shows a
1201 // standard 44pt bottom toolbar that overlays the list and is not
1202 // reflected in insets while contentInsetAdjustmentBehavior is
1203 // "never".
1204 paddingBottom:
1205 Platform.OS === "ios"
1206 ? Math.max(insets.bottom, 24) + 24 + iosBottomToolbarClearance
1207 : Math.max(insets.bottom, 16) + 88,
1208 }}
1209 scrollIndicatorInsets={
1210 Platform.OS === "ios"
1211 ? {
1212 bottom: Math.max(insets.bottom, 16) + 24 + iosBottomToolbarClearance,
1213 top: 0,
1214 }
1215 : undefined
1216 }
1217 />
1218 </SwipeableScrollGateProvider>
1219 </View>
1220 );
1221}