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

HomeScreen.tsx

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