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

HomeScreen.tsx

1,214 lines45.2 KB

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