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

HomeScreen.tsx

995 lines38.0 KB

1import { useAndroidControlSizing } from "../../components/useAndroidControlSizing";
2import type { ThreadMoveDestination } from "../threads/threadOrder";
3import { computeThreadMoveAvailability } from "../threads/threadOrder";
4import { LegendList } from "@legendapp/list/react-native";
5import {
6 type EnvironmentProject,
7 type EnvironmentThreadShell,
8} from "@t3tools/client-runtime/state/shell";
9import {
10 threadSearchMatchKey,
11 type EnvironmentThreadSearchMatch,
12} from "@t3tools/client-runtime/state/thread-search";
13import {
14 type EnvironmentId,
15 resolveEnvironmentMachineKind,
16 type SidebarProjectGroupingMode,
17} from "@t3tools/contracts";
18import { useAtomValue } from "@effect/atom-react";
19import { useFocusEffect } from "@react-navigation/native";
20import { useCallback, useEffect, useMemo, useRef, useState } from "react";
21import { ActivityIndicator, Platform, View } from "react-native";
22import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
23import { useSafeAreaInsets } from "react-native-safe-area-context";
24​
25import { cn } from "../../lib/cn";
26import { EmptyState } from "../../components/EmptyState";
27import { MaterialFloatingActionButton } from "../../components/MaterialFloatingActionButton";
28import type { WorkspaceEnvironment, WorkspaceState } from "../../state/workspaceModel";
29import type { SavedRemoteConnection } from "../../lib/connection";
30import { scopedProjectKey } from "../../lib/scopedEntities";
31import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
32import { useThreadSearch } from "../../state/queries";
33import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts";
34import { usePendingThreadOrder } from "../../state/thread-order";
35import { environmentServerConfigsAtom } from "../../state/server";
36import type { PendingNewTask } from "../../state/use-pending-new-tasks";
37import { useQueuedThreadKeys } from "../../state/use-thread-outbox";
38import {
39 ThreadListV2PendingRow,
40 ThreadListV2Row,
41 ThreadListV2SettledShelfHeader,
42 ThreadListV2ShowMoreRow,
43 ThreadListV2SnoozedShelfHeader,
44} from "../threads/thread-list-v2-items";
45import { useThreadRowProviderInstanceResolver } from "../threads/thread-provider-instance";
46import {
47 buildThreadListV2Items,
48 getThreadListV2OrderedSection,
49 buildThreadListV2ListItems,
50 threadListV2ListItemsAreEqual,
51 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
52 THREAD_LIST_V2_SETTLED_PAGE_COUNT,
53 type ThreadListV2ListItem,
54} from "../threads/threadListV2";
55import { useThreadListV2ShelfPreferences } from "../threads/use-thread-list-v2-shelf-preferences";
56import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
57import {
58 buildHomeProjectScopes,
59 sortHomeProjectScopes,
60 type HomeProjectSortOrder,
61} from "./homeThreadList";
62import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
63import { useMaterialFabScroll } from "./MaterialFabScrollContext";
64​
65/* ─── Types ──────────────────────────────────────────────────────────── */
66​
67interface HomeScreenProps {
68 readonly projects: ReadonlyArray<EnvironmentProject>;
69 readonly threads: ReadonlyArray<EnvironmentThreadShell>;
70 readonly pendingTasks: ReadonlyArray<PendingNewTask>;
71 readonly catalogState: WorkspaceState;
72 readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
73 readonly environments: ReadonlyArray<
74 HomeListFilterMenuEnvironment & Pick<WorkspaceEnvironment, "connectionState">
75 >;
76 readonly searchQuery: string;
77 readonly selectedEnvironmentId: EnvironmentId | null;
78 readonly selectedProjectKey: string | null;
79 readonly projectSortOrder: HomeProjectSortOrder;
80 readonly projectGroupingMode: SidebarProjectGroupingMode;
81 readonly onSearchQueryChange: (query: string) => void;
82 readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
83 readonly onProjectChange: (projectKey: string | null) => void;
84 readonly onAddConnection: () => void;
85 readonly onOpenSettings: () => void;
86 readonly onStartNewTask: () => void;
87 readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
88 readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
89 readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
90 /** Resolves true iff the settle was dispatched and succeeded. */
91 readonly onSettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
92 readonly onSnoozeThread: (
93 thread: EnvironmentThreadShell,
94 snoozedUntil: string,
95 ) => Promise<boolean>;
96 readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
97 readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
98 readonly onPinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
99 readonly onUnpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
100 readonly onSetThreadAutoSettle: (
101 thread: EnvironmentThreadShell,
102 enabled: boolean,
103 ) => Promise<boolean>;
104 readonly onMoveThread: (
105 thread: EnvironmentThreadShell,
106 direction: ThreadMoveDestination,
107 ) => Promise<boolean>;
108 readonly onRenameThread: (thread: EnvironmentThreadShell) => void;
109 readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
110 readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
111 readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
112 readonly onNewThreadOnBranch: (thread: EnvironmentThreadShell) => void;
113 readonly onNewThreadInProject: (project: EnvironmentProject) => void;
115​
116/* ─── Layout constants ───────────────────────────────────────────────── */
117​
118// v2 rows are mixed-height: settled slim rows run ~60dp, single-line cards
119// measured ~74dp on device (252px on the Pixel 10 Pro screenshot), two-line
120// cards ~94dp. The estimate seeds the recycler's initial container count,
121// `ceil((scrollLength + 2 * INITIAL_DRAW_DISTANCE) / estimate)` with the
122// initial draw distance capped at 50, so an estimate at or below the average
123// row height starts the pool at or above the item count for the short lists
124// that LegendList otherwise keeps pooling to exactly its item count — that is
125// what stopped the dev-mode "no unused container available" warning on the
126// seeded short-list device passes. It is a mitigation, not an elimination:
127// after first layout the full drawDistance applies, and a sudden expansion
128// past the pooled headroom (~25+ items appearing at once) still creates a
129// container on demand with the dev-only warning one pass ahead of the
130// measured-height pool expansion. The old tallest-card estimate (~92) fired
131// that warning on every ordinary shelf expand, so the average wins.
132const ESTIMATED_THREAD_LIST_V2_ROW_HEIGHT = 72;
133const PRE_LIQUID_GLASS_BOTTOM_TOOLBAR_HEIGHT = 44;
134/**
135 * Top spacing between the list and the Android custom header. The Android
136 * header is rendered in-flow above this screen and
137 * already consumes the top safe-area inset, so the list only needs breathing
138 * room here.
139 */
140​
141function deriveEmptyState(props: {
142 readonly catalogState: WorkspaceState;
143 readonly projectCount: number;
144}): { readonly title: string; readonly detail: string; readonly loading: boolean } {
145 const { catalogState } = props;
146 if (catalogState.isLoadingConnections) {
147 return {
148 title: "Loading environments",
149 detail: "Checking saved environments on this device.",
150 loading: true,
151 };
152 }
153​
154 if (!catalogState.hasConnections) {
155 return {
156 title: "No environments connected",
157 detail: "Add an environment to load projects and start coding sessions.",
158 loading: false,
159 };
160 }
161​
162 if (
163 (catalogState.connectionState === "available" ||
164 catalogState.connectionState === "offline" ||
165 catalogState.connectionState === "error" ||
166 catalogState.connectionState === "unsupported") &&
167 !catalogState.hasLoadedShellSnapshot
168 ) {
169 return {
170 title:
171 catalogState.connectionState === "unsupported"
172 ? "Client not supported"
173 : "Environment unavailable",
174 detail:
175 catalogState.connectionError ??
176 "The saved environment is offline. Check the URL or start the environment, then retry.",
177 loading: false,
178 };
179 }
180​
181 if (
182 catalogState.hasConnectingEnvironment &&
183 !catalogState.hasLoadedShellSnapshot &&
184 catalogState.connectionError === null
185 ) {
186 return {
187 title: "Connecting to environment",
188 detail: "Loading projects and threads from the saved environment.",
189 loading: true,
190 };
191 }
192​
193 if (props.projectCount === 0 && catalogState.hasLoadedShellSnapshot) {
194 return {
195 title: "No projects found",
196 detail: "The connected environment did not report any projects.",
197 loading: false,
198 };
199 }
200​
201 return {
202 title: "No threads yet",
203 detail: "Create a task to start a new coding session in one of your connected projects.",
204 loading: false,
205 };
207​
208function HomeTopContentSpacer() {
209 return <View className="h-4" />;
211​
212/* ─── Main screen ────────────────────────────────────────────────────── */
213​
214export function HomeScreen(props: HomeScreenProps) {
215 const queuedThreadKeys = useQueuedThreadKeys();
216 const openSwipeableRef = useRef<SwipeableMethods | null>(null);
217 const insets = useSafeAreaInsets();
218 const { fabClearance } = useAndroidControlSizing();
219 const iosBottomToolbarClearance =
220 Platform.OS === "ios" && !NATIVE_LIQUID_GLASS_SUPPORTED
221 ? PRE_LIQUID_GLASS_BOTTOM_TOOLBAR_HEIGHT
222 : 0;
223 const searchEnvironmentIds = useMemo(
224 () =>
225 props.selectedEnvironmentId === null
226 ? props.environments
227 .filter((environment) => environment.connectionState === "connected")
228 .map((environment) => environment.environmentId)
229 : props.environments.some(
230 (environment) =>
231 environment.environmentId === props.selectedEnvironmentId &&
232 environment.connectionState === "connected",
233 )
234 ? [props.selectedEnvironmentId]
235 : [],
236 [props.environments, props.selectedEnvironmentId],
237 );
238 const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery);
239 const threadSearchMatchByKey = useMemo(() => {
240 const matches = new Map<string, EnvironmentThreadSearchMatch>();
241 for (const match of threadSearch.matches) {
242 if (match.source === "user" || match.source === "assistant") {
243 matches.set(threadSearchMatchKey(match), match);
244 }
245 }
246 return matches;
247 }, [threadSearch.matches]);
248 const matchedThreadKeys = useMemo(
249 () => new Set(threadSearch.matches.map(threadSearchMatchKey)),
250 [threadSearch.matches],
251 );
252 const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
253 if (openSwipeableRef.current !== methods) {
254 openSwipeableRef.current?.close();
255 openSwipeableRef.current = methods;
256 }
257 }, []);
258​
259 const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
260 if (openSwipeableRef.current === methods) {
261 openSwipeableRef.current = null;
262 }
263 }, []);
264​
265 const handleScrollBeginDrag = useCallback(() => {
266 openSwipeableRef.current?.close();
267 }, []);
268 const onMaterialFabScroll = useMaterialFabScroll();
269 const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
270 onScroll: onMaterialFabScroll,
271 onScrollBeginDrag: handleScrollBeginDrag,
272 });
273​
274 const projectScopes = useMemo(
275 () =>
276 buildHomeProjectScopes({
277 projects: props.projects,
278 environmentId: props.selectedEnvironmentId,
279 projectGroupingMode: props.projectGroupingMode,
280 }),
281 [props.projectGroupingMode, props.projects, props.selectedEnvironmentId],
282 );
283 const hasSearchQuery = props.searchQuery.trim().length > 0;
284 const projectByKey = useMemo(() => {
285 const map = new Map<string, EnvironmentProject>();
286 for (const project of props.projects) {
287 map.set(scopedProjectKey(project.environmentId, project.id), project);
288 }
289 return map;
290 }, [props.projects]);
291​
292 const v2ProjectScopeKey = props.selectedProjectKey;
293 const v2ScopeProjects = useMemo(
294 () =>
295 sortHomeProjectScopes({
296 scopes: projectScopes,
297 threads: props.threads,
298 pendingTasks: props.pendingTasks,
299 projectSortOrder: props.projectSortOrder,
300 }),
301 [
302 props.pendingTasks,
303 props.projects,
304 props.projectSortOrder,
305 props.selectedEnvironmentId,
306 props.threads,
307 projectScopes,
308 ],
309 );
310 const v2ScopedProjectGroup = useMemo(
311 () =>
312 v2ProjectScopeKey === null
313 ? null
314 : (v2ScopeProjects.find(
315 (scope) =>
316 scope.key === v2ProjectScopeKey ||
317 scope.projectRefs.some(
318 (projectRef) =>
319 scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
320 v2ProjectScopeKey,
321 ),
322 ) ?? null),
323 [v2ProjectScopeKey, v2ScopeProjects],
324 );
325 const v2ProjectTitleByProjectKey = useMemo(
326 () =>
327 new Map(
328 v2ScopeProjects.flatMap((scope) =>
329 scope.projectRefs.map(
330 (projectRef) =>
331 [
332 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
333 scope.title,
334 ] as const,
335 ),
336 ),
337 ),
338 [v2ScopeProjects],
339 );
340 const v2ScopedProjectKeys = useMemo(
341 () =>
342 v2ScopedProjectGroup === null
343 ? null
344 : new Set(
345 v2ScopedProjectGroup.projectRefs.map((projectRef) =>
346 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
347 ),
348 ),
349 [v2ScopedProjectGroup],
350 );
351 // Thread List v2 (beta): one flat list in creation order, no grouping.
352 // Settled threads collapse into a recency tail below the card block.
353 // Settled threads stay in the live shell stream (settled ≠ archived), so
354 // the partition works directly off live shells — no snapshot merging or
355 // optimistic holds.
356 const handleSettleThread = props.onSettleThread;
357 const handleSnoozeThread = useCallback(
358 (thread: EnvironmentThreadShell, snoozedUntil: string) => {
359 void props.onSnoozeThread(thread, snoozedUntil);
360 },
361 [props.onSnoozeThread],
362 );
363 const handleUnsnoozeThread = useCallback(
364 (thread: EnvironmentThreadShell) => {
365 void props.onUnsnoozeThread(thread);
366 },
367 [props.onUnsnoozeThread],
368 );
369 const handlePinThread = useCallback(
370 (thread: EnvironmentThreadShell) => {
371 void props.onPinThread(thread);
372 },
373 [props.onPinThread],
374 );
375 const handleMoveThread = useCallback(
376 (thread: EnvironmentThreadShell, direction: ThreadMoveDestination) => {
377 void props.onMoveThread(thread, direction);
378 },
379 [props.onMoveThread],
380 );
381 const handleUnpinThread = useCallback(
382 (thread: EnvironmentThreadShell) => {
383 void props.onUnpinThread(thread);
384 },
385 [props.onUnpinThread],
386 );
387 const handleSetThreadAutoSettle = useCallback(
388 (thread: EnvironmentThreadShell, enabled: boolean) => {
389 void props.onSetThreadAutoSettle(thread, enabled);
390 },
391 [props.onSetThreadAutoSettle],
392 );
393 const handleRegenerateThreadTitle = useCallback(
394 (thread: EnvironmentThreadShell) => {
395 void props.onRegenerateThreadTitle(thread);
396 },
397 [props.onRegenerateThreadTitle],
398 );
399 const handleRenameThread = useCallback(
400 (thread: EnvironmentThreadShell) => props.onRenameThread(thread),
401 [props.onRenameThread],
402 );
403 const handleDeleteThread = props.onDeleteThread;
404 const handleUnsettleThread = props.onUnsettleThread;
405 // The settled tail renders in pages; expansion resets when the filter
406 // context changes so environment/search flips never inherit a deep page.
407 const [settledVisibleCount, setSettledVisibleCount] = useState(
408 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
409 );
410 const settledResetKey = `${props.selectedEnvironmentId ?? "all"}:${v2ProjectScopeKey ?? "all"}:${props.searchQuery.trim()}`;
411 const lastSettledResetKeyRef = useRef(settledResetKey);
412 if (lastSettledResetKeyRef.current !== settledResetKey) {
413 lastSettledResetKeyRef.current = settledResetKey;
414 setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
415 }
416 const showMoreSettled = useCallback(
417 () => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
418 [],
419 );
420 const {
421 loaded: shelfPreferencesLoaded,
422 settledShelfExpanded,
423 snoozedShelfExpanded,
424 toggleSettledShelf,
425 toggleSnoozedShelf,
426 } = useThreadListV2ShelfPreferences();
427 // The queued-start and snooze helpers need a clock while the list stays open.
428 const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
429 // Snooze wake times are second-precise; a counter bumped exactly at the
430 // next wake boundary re-runs the partition with a fresh clock so a woken
431 // thread reappears immediately instead of on the next minute tick.
432 const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
433 useFocusEffect(
434 useCallback(() => {
435 // Refresh immediately on enable or focus because the previous value can be hours old.
436 setNowMinute(new Date().toISOString().slice(0, 16));
437 const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
438 return () => clearInterval(id);
439 }, []),
440 );
441 // Threads on servers without the settlement capability never classify as
442 // settled (the user could neither un-settle nor pin them).
443 const serverConfigs = useAtomValue(environmentServerConfigsAtom);
444 const settlementEnvironmentIds = useMemo(() => {
445 const supported = new Set<EnvironmentId>();
446 for (const [environmentId, config] of serverConfigs) {
447 if (config.environment.capabilities.threadSettlement === true) {
448 supported.add(environmentId);
449 }
450 }
451 return supported;
452 }, [serverConfigs]);
453 const snoozeEnvironmentIds = useMemo(() => {
454 const supported = new Set<EnvironmentId>();
455 for (const [environmentId, config] of serverConfigs) {
456 if (config.environment.capabilities.threadSnooze === true) {
457 supported.add(environmentId);
458 }
459 }
460 return supported;
461 }, [serverConfigs]);
462 const pinningEnvironmentIds = useMemo(() => {
463 const supported = new Set<EnvironmentId>();
464 for (const [environmentId, config] of serverConfigs) {
465 if (config.environment.capabilities.threadPinning === true) {
466 supported.add(environmentId);
467 }
468 }
469 return supported;
470 }, [serverConfigs]);
471 const autoSettleOptOutEnvironmentIds = useMemo(() => {
472 const supported = new Set<EnvironmentId>();
473 for (const [environmentId, config] of serverConfigs) {
474 if (config.environment.capabilities.threadAutoSettleOptOut === true) {
475 supported.add(environmentId);
476 }
477 }
478 return supported;
479 }, [serverConfigs]);
480 const pinReorderEnvironmentIds = useMemo(() => {
481 const supported = new Set<EnvironmentId>();
482 for (const [environmentId, config] of serverConfigs) {
483 if (config.environment.capabilities.threadPinReorder === true) {
484 supported.add(environmentId);
485 }
486 }
487 return supported;
488 }, [serverConfigs]);
489 const activeReorderEnvironmentIds = useMemo(() => {
490 const supported = new Set<EnvironmentId>();
491 for (const [environmentId, config] of serverConfigs) {
492 if (config.environment.capabilities.threadActiveReorder === true) {
493 supported.add(environmentId);
494 }
495 }
496 return supported;
497 }, [serverConfigs]);
498 const titleRegenerationEnvironmentIds = useMemo(() => {
499 const supported = new Set<EnvironmentId>();
500 for (const [environmentId, config] of serverConfigs) {
501 if (config.environment.capabilities.threadTitleRegeneration === true) {
502 supported.add(environmentId);
503 }
504 }
505 return supported;
506 }, [serverConfigs]);
507 const machineByEnvironmentId = useMemo(
508 () =>
509 new Map(
510 [...serverConfigs].map(
511 ([environmentId, config]) =>
512 [environmentId, resolveEnvironmentMachineKind(config)] as const,
513 ),
514 ),
515 [serverConfigs],
516 );
517 // Reference-stable provider glyphs: a fresh object per render would break
518 // the memoized rows' props comparison on every parent render.
519 const resolveProviderInstance = useThreadRowProviderInstanceResolver(serverConfigs);
520 const pendingOrder = usePendingThreadOrder(nowMinute, snoozeWakeTick);
521 // Up/down menu availability for every card, computed once per section per
522 // rebuild (see computeThreadMoveAvailability): per-thread planner calls made
523 // list construction quadratic, and this list rebuilds on every minute tick.
524 const threadMoveAvailability = useMemo(() => {
525 const sectionAvailability = (section: "pinned" | "active") =>
526 computeThreadMoveAvailability({
527 allThreads: props.threads,
528 section,
529 pendingOrder,
530 reorderableEnvironmentIds: new Set(
531 [...serverConfigs].flatMap(([id, config]) =>
532 (section === "pinned"
533 ? config.environment.capabilities.threadPinReorder
534 : config.environment.capabilities.threadActiveReorder) === true
535 ? [id]
536 : [],
537 ),
538 ),
539 ordered: getThreadListV2OrderedSection({
540 threads: props.threads,
541 section,
542 pendingOrder,
543 now: new Date().toISOString(),
544 settlementEnvironmentIds,
545 snoozeEnvironmentIds,
546 queuedThreadKeys,
547 }),
548 });
549 return new Map([...sectionAvailability("pinned"), ...sectionAvailability("active")]);
550 }, [
551 serverConfigs,
552 props.threads,
553 pendingOrder,
554 queuedThreadKeys,
555 settlementEnvironmentIds,
556 snoozeEnvironmentIds,
557 nowMinute,
558 snoozeWakeTick,
559 ]);
560 const threadListV2Layout = useMemo(() => {
561 // Settled threads are live shells; archived threads keep their original
562 // "hidden from lists" meaning.
563 return buildThreadListV2Items({
564 pendingOrder,
565 threads: props.threads.filter((thread) => thread.archivedAt === null),
566 environmentId: props.selectedEnvironmentId,
567 projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
568 searchQuery: props.searchQuery,
569 matchedThreadKeys,
570 settlementEnvironmentIds,
571 snoozeEnvironmentIds,
572 queuedThreadKeys,
573 settledLimit: settledVisibleCount,
574 now: new Date().toISOString(),
575 snoozedShelfExpanded,
576 settledShelfExpanded,
577 selectedThreadKey: null,
578 });
579 }, [
580 pendingOrder,
581 queuedThreadKeys,
582 nowMinute,
583 snoozeWakeTick,
584 snoozedShelfExpanded,
585 settledShelfExpanded,
586 settledVisibleCount,
587 settlementEnvironmentIds,
588 snoozeEnvironmentIds,
589 props.searchQuery,
590 props.selectedEnvironmentId,
591 props.threads,
592 matchedThreadKeys,
593 v2ScopedProjectGroup,
594 ]);
595 // Re-partition the moment the earliest snooze expires (clamped to the
596 // signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
597 const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
598 useEffect(() => {
599 if (nextSnoozeWakeAt === null) return;
600 const wakeAtMs = Date.parse(nextSnoozeWakeAt);
601 if (Number.isNaN(wakeAtMs)) return;
602 const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
603 const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
604 return () => clearTimeout(id);
605 // snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
606 // unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
607 // range) the boundary string is identical and the chain would die.
608 }, [nextSnoozeWakeAt, snoozeWakeTick]);
609 // Queued tasks are not thread shells, so the v2 partition never sees them;
610 // they are spliced in below the active block and stay visible and deletable
611 // while their environment is offline. Same environment scope and search
612 // filter as the list itself.
613 const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
614 const v2PendingTasks = useMemo(
615 () =>
616 props.pendingTasks.filter(
617 (pendingTask) =>
618 (props.selectedEnvironmentId === null ||
619 pendingTask.environmentId === props.selectedEnvironmentId) &&
620 (v2ScopedProjectKeys === null ||
621 v2ScopedProjectKeys.has(
622 scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),
623 )) &&
624 (v2SearchQuery.length === 0 ||
625 pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
626 ),
627 [props.pendingTasks, props.selectedEnvironmentId, v2ScopedProjectKeys, v2SearchQuery],
628 );
629 const threadListV2Items = useMemo(
630 () =>
631 buildThreadListV2ListItems({
632 items: threadListV2Layout.items,
633 pendingTasks: v2PendingTasks,
634 snoozedCount: threadListV2Layout.snoozedCount,
635 snoozedShelfExpanded,
636 snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
637 settledCount: threadListV2Layout.settledCount,
638 settledShelfExpanded,
639 settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
640 snoozeLabelNow: `${nowMinute}:00.000Z`,
641 snoozeEnvironmentIds,
642 queuedThreadKeys,
643 moveAvailability: threadMoveAvailability,
644 shelfPreferencesLoading: !shelfPreferencesLoaded,
645 }),
646 [
647 nowMinute,
648 queuedThreadKeys,
649 threadMoveAvailability,
650 settledShelfExpanded,
651 shelfPreferencesLoaded,
652 snoozedShelfExpanded,
653 snoozeEnvironmentIds,
654 threadListV2Layout,
655 v2PendingTasks,
656 ],
657 );
658​
659 useThreadJumpShortcuts(threadListV2Items, props.onSelectThread);
660​
661 const renderV2Item = useCallback(
662 ({ item }: { readonly item: ThreadListV2ListItem }) => {
663 if (item.type === "v2-pending") {
664 const pendingScopeKey = scopedProjectKey(
665 item.pendingTask.environmentId,
666 item.pendingTask.projectId,
667 );
668 return (
669 <ThreadListV2PendingRow
670 pendingTask={item.pendingTask}
671 project={projectByKey.get(pendingScopeKey) ?? null}
672 projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}
673 environmentLabel={
674 Object.keys(props.savedConnectionsById).length > 1
675 ? (props.savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ??
676 null)
677 : null
678 }
679 environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
680 showPendingDivider={item.showPendingDivider}
681 showTrailingDivider={item.showTrailingDivider}
682 onSelectPendingTask={props.onSelectPendingTask}
683 onDeletePendingTask={props.onDeletePendingTask}
684 />
685 );
686 }
687 if (item.type === "v2-snoozed-shelf") {
688 return (
689 <ThreadListV2SnoozedShelfHeader
690 count={item.count}
691 disabled={item.disabled}
692 expanded={item.expanded}
693 onToggle={toggleSnoozedShelf}
694 />
695 );
696 }
697 if (item.type === "v2-settled-shelf") {
698 return (
699 <ThreadListV2SettledShelfHeader
700 count={item.count}
701 disabled={item.disabled}
702 expanded={item.expanded}
703 onToggle={toggleSettledShelf}
704 />
705 );
706 }
707 const thread = item.item.thread;
708 return (
709 <ThreadListV2Row
710 onNewThreadOnBranch={props.onNewThreadOnBranch}
711 thread={thread}
712 variant={item.item.variant}
713 hasQueuedMessages={item.hasQueuedMessages}
714 snoozed={item.item.snoozed}
715 pinned={item.item.pinned}
716 snoozePresetMinute={item.snoozePresetMinute ?? ""}
717 snoozeWakeLabelText={item.snoozeWakeLabelText}
718 timeLabel={item.timeLabel}
719 showTrailingDivider={item.showTrailingDivider}
720 project={
721 projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
722 }
723 projectTitle={v2ProjectTitleByProjectKey.get(
724 scopedProjectKey(thread.environmentId, thread.projectId),
725 )}
726 providerInstance={resolveProviderInstance(thread)}
727 environmentLabel={
728 Object.keys(props.savedConnectionsById).length > 1
729 ? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
730 : null
731 }
732 environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
733 searchMatch={threadSearchMatchByKey.get(
734 threadSearchMatchKey({
735 environmentId: thread.environmentId,
736 threadId: thread.id,
737 }),
738 )}
739 searchQuery={props.searchQuery}
740 onSelectThread={props.onSelectThread}
741 onDeleteThread={handleDeleteThread}
742 onArchiveThread={props.onArchiveThread}
743 onRenameThread={handleRenameThread}
744 onRegenerateThreadTitle={handleRegenerateThreadTitle}
745 titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
746 settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
747 onSettleThread={handleSettleThread}
748 snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
749 pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
750 autoSettleOptOutSupported={autoSettleOptOutEnvironmentIds.has(thread.environmentId)}
751 reorderSupported={
752 item.item.pinned
753 ? pinReorderEnvironmentIds.has(thread.environmentId)
754 : activeReorderEnvironmentIds.has(thread.environmentId)
755 }
756 canMoveUp={item.canMoveUp}
757 canMoveDown={item.canMoveDown}
758 onSnoozeThread={handleSnoozeThread}
759 onUnsnoozeThread={handleUnsnoozeThread}
760 onUnsettleThread={handleUnsettleThread}
761 onPinThread={handlePinThread}
762 onUnpinThread={handleUnpinThread}
763 onSetThreadAutoSettle={handleSetThreadAutoSettle}
764 onMoveThread={handleMoveThread}
765 onSwipeableClose={handleSwipeableClose}
766 onSwipeableWillOpen={handleSwipeableWillOpen}
767 />
768 );
769 },
770 [
771 handleDeleteThread,
772 activeReorderEnvironmentIds,
773 handleMoveThread,
774 handlePinThread,
775 handleRegenerateThreadTitle,
776 handleRenameThread,
777 handleSettleThread,
778 handleSnoozeThread,
779 handleUnpinThread,
780 handleUnsnoozeThread,
781 handleSwipeableClose,
782 handleSwipeableWillOpen,
783 handleUnsettleThread,
784 handleSetThreadAutoSettle,
785 autoSettleOptOutEnvironmentIds,
786 pinningEnvironmentIds,
787 machineByEnvironmentId,
788 pinReorderEnvironmentIds,
789 projectByKey,
790 props.onArchiveThread,
791 props.onDeletePendingTask,
792 props.onSelectPendingTask,
793 props.onSelectThread,
794 props.onNewThreadOnBranch,
795 props.savedConnectionsById,
796 resolveProviderInstance,
797 settlementEnvironmentIds,
798 snoozeEnvironmentIds,
799 threadSearchMatchByKey,
800 titleRegenerationEnvironmentIds,
801 toggleSettledShelf,
802 toggleSnoozedShelf,
803 v2ProjectTitleByProjectKey,
804 props.searchQuery,
805 ],
806 );
807 const v2KeyExtractor = useCallback((item: ThreadListV2ListItem) => item.key, []);
808​
809 // FlatList/LegendList treat a changed extraData identity as "re-render every
810 // visible row", so an inline object literal would invalidate all rows on
811 // every HomeScreen render — and the minute clock must stay out of it for
812 // the same reason: the clock text is precomputed per item instead.
813 const v2ExtraData = useMemo(
814 () => ({
815 projectByKey,
816 projectTitleByProjectKey: v2ProjectTitleByProjectKey,
817 serverConfigs,
818 savedConnectionsById: props.savedConnectionsById,
819 searchQuery: props.searchQuery,
820 threadSearchMatchByKey,
821 }),
822 [
823 projectByKey,
824 props.searchQuery,
825 props.savedConnectionsById,
826 serverConfigs,
827 threadSearchMatchByKey,
828 v2ProjectTitleByProjectKey,
829 ],
830 );
831​
832 /* Empty states */
833 // The signal must ignore the search/environment filters: an active query
834 // that matches nothing needs the in-list "No results" state, not the
835 // full-page "No threads yet". Settled threads are unarchived live shells,
836 // so the archived-at check already covers the settled shelf.
837 const hasAnyThreads =
838 props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
839 const selectedEnvironmentLabel =
840 props.selectedEnvironmentId === null
841 ? null
842 : (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
843 "this environment");
844 // Connection state surfaces in the header title slot
845 // (WorkspaceConnectionTitle) — nothing renders inside the list, so
846 // reconnects never shift the rows.
847 const emptyState = deriveEmptyState({
848 catalogState: props.catalogState,
849 projectCount: props.projects.length,
850 });
851​
852 if (!hasAnyThreads) {
853 return (
854 <View className="flex-1 bg-screen android:bg-header">
855 <View
856 className={cn(
857 "flex-1 items-center justify-center bg-screen px-8",
858 Platform.OS === "android" && "overflow-hidden rounded-t-[28px]",
859 )}
860 style={{
861 paddingBottom: Math.max(insets.bottom, 24) + iosBottomToolbarClearance,
862 paddingTop: NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 72 : 0,
863 }}
864 >
865 <View className="w-full max-w-[430px]">
866 <EmptyState
867 title={emptyState.title}
868 detail={emptyState.detail}
869 actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
870 onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
871 action={
872 Platform.OS === "android" && !props.catalogState.hasReadyEnvironment ? (
873 <MaterialFloatingActionButton
874 label="Add environment"
875 icon="plus"
876 variant="extended"
877 tone="primary"
878 onPress={props.onAddConnection}
879 />
880 ) : undefined
881 }
882 variant="plain"
883 />
884 {emptyState.loading ? (
885 <View className="mt-4 items-center">
886 <ActivityIndicator colorClassName="accent-icon-muted" />
887 </View>
888 ) : null}
889 </View>
890 </View>
891 </View>
892 );
893 }
894​
895 const listHeader = Platform.OS === "ios" ? null : <HomeTopContentSpacer />;
896​
897 // Project scoping lives in the header filter menu (no inline chip row on
898 // mobile — the menu is the one filter surface).
899 const v2ListHeader = listHeader;
900​
901 // Use the v2 project scope for its empty state. Snoozed threads need no
902 // special empty state: their shelf header is a list row even while collapsed.
903 const v2ListEmpty =
904 hasSearchQuery && threadSearch.isPending ? null : hasSearchQuery ? (
905 <EmptyState
906 title="No results"
907 detail={`No threads matching "${props.searchQuery}".`}
908 variant={Platform.OS === "android" ? "plain" : undefined}
909 />
910 ) : v2ScopedProjectGroup !== null ? (
911 <EmptyState
912 title={`No threads in ${v2ScopedProjectGroup.title}`}
913 detail="Choose another project or create a new task."
914 variant={Platform.OS === "android" ? "plain" : undefined}
915 />
916 ) : selectedEnvironmentLabel ? (
917 <EmptyState
918 title={`No threads in ${selectedEnvironmentLabel}`}
919 detail="Choose another environment or create a new task."
920 variant={Platform.OS === "android" ? "plain" : undefined}
921 />
922 ) : (
923 <EmptyState
924 title="No threads yet"
925 detail="Create a task to start a new coding session."
926 variant={Platform.OS === "android" ? "plain" : undefined}
927 />
928 );
929​
930 if (Platform.OS === "android" && threadListV2Items.length === 0) {
931 return (
932 <View className="flex-1 bg-header">
933 <View
934 className="flex-1 items-center justify-center overflow-hidden rounded-t-[28px] bg-screen px-4"
935 style={{ paddingBottom: insets.bottom }}
936 >
937 {v2ListEmpty}
938 </View>
939 </View>
940 );
941 }
942​
943 return (
944 <View className="flex-1 bg-screen android:bg-header">
945 <View
946 className={
947 Platform.OS === "android"
948 ? "flex-1 overflow-hidden rounded-t-[28px] bg-screen"
949 : "flex-1 bg-screen"
950 }
951 >
952 {/* Shared with the iPad sidebar: cells are reused across data
953 rebuilds and `itemsAreEqual` keeps a minute tick (or an unrelated
954 shell update) from re-rendering untouched rows. */}
955 <SwipeableScrollGateProvider enabled={swipeEnabled}>
956 <LegendList
957 data={threadListV2Items}
958 renderItem={renderV2Item}
959 keyExtractor={v2KeyExtractor}
960 getItemType={(item) => item.type}
961 itemsAreEqual={threadListV2ListItemsAreEqual}
962 estimatedItemSize={ESTIMATED_THREAD_LIST_V2_ROW_HEIGHT}
963 drawDistance={500}
964 recycleItems
965 extraData={v2ExtraData}
966 ListHeaderComponent={v2ListHeader}
967 ListFooterComponent={
968 settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? (
969 <ThreadListV2ShowMoreRow
970 hiddenCount={threadListV2Layout.hiddenSettledCount}
971 onPress={showMoreSettled}
972 />
973 ) : null
974 }
975 ListEmptyComponent={v2ListEmpty}
976 style={{ flex: 1 }}
977 automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
978 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
979 showsVerticalScrollIndicator={false}
980 keyboardDismissMode="on-drag"
981 keyboardShouldPersistTaps="handled"
982 {...scrollGateHandlers}
983 scrollEventThrottle={16}
984 contentContainerStyle={{
985 paddingBottom:
986 Platform.OS === "ios"
987 ? Math.max(insets.bottom, 24) + 96 + iosBottomToolbarClearance
988 : Math.max(insets.bottom, 16) + (Platform.OS === "android" ? fabClearance : 88),
989 }}
990 />
991 </SwipeableScrollGateProvider>
992 </View>
993 </View>
994 );