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

HomeScreen.tsx

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