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

HomeScreen.tsx

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