import type { EnvironmentProject, EnvironmentThreadShell,} from "@t3tools/client-runtime/state/shell";import { threadSearchMatchKey, type EnvironmentThreadSearchMatch,} from "@t3tools/client-runtime/state/thread-search";import { LegendList } from "@legendapp/list/react-native";import type { MenuAction } from "@react-native-menu/menu";import { useAtomValue } from "@effect/atom-react";import { type EnvironmentId, resolveEnvironmentMachineKind } from "@t3tools/contracts";import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import type { LayoutChangeEvent } from "react-native";import { Platform, Pressable, StyleSheet, TextInput, View } from "react-native";import { Gesture, GestureDetector } from "react-native-gesture-handler";import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";import { useSafeAreaInsets } from "react-native-safe-area-context";import type { SearchBarCommands } from "react-native-screens"; import { AppText as Text } from "../../components/AppText";import { CompactBrandTitle } from "../../components/CompactBrandTitle";import { ControlPillMenu } from "../../components/ControlPill";import { SymbolView } from "../../components/AppSymbol";import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";import { NativeStackScreenOptions } from "../../native/StackHeader";import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";import { useProjects, useThreadShells } from "../../state/entities";import { useThreadSearch } from "../../state/queries";import { useThreadListV2Enabled } from "./use-thread-list-v2-enabled";import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences";import { environmentServerConfigsAtom } from "../../state/server";import { usePendingNewTasks } from "../../state/use-pending-new-tasks";import { useWorkspaceState } from "../../state/workspace";import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";import { hasCustomHomeListOptions, PROJECT_SORT_OPTIONS, THREAD_SORT_OPTIONS, useHomeListOptions,} from "../home/home-list-options";import { buildHomeListFilterMenu } from "../home/home-list-filter-menu";import { buildHomeListLayout, DEFAULT_GROUP_DISPLAY_STATE, EMPTY_HOME_LIST_LAYOUT, homeListItemsAreEqual, nextGroupDisplayState, type HomeGroupDisplayAction, type HomeGroupDisplayState, type HomeListItem,} from "../home/homeListItems";import { buildHomeProjectScopes, buildHomeThreadGroups } from "../home/homeThreadList";import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";import { usePendingTaskListActions } from "../home/usePendingTaskListActions";import { useThreadListActions } from "../home/useThreadListActions";import { getConnectionAwareBrandHeaderOptions, WorkspaceConnectionTitle,} from "../home/WorkspaceConnectionTitle";import { SidebarHeaderActions } from "./sidebar-header-actions";import { SidebarFilterButton } from "./sidebar-filter-button";import { createSidebarHeaderItems } from "./sidebar-native-header-items";import { SidebarNavigationShell } from "./sidebar-navigation-shell";import { PendingTaskListRow, ThreadListGroupHeader, ThreadListRow, ThreadListShowMoreRow,} from "./thread-list-items";import { ThreadListV2PendingRow, ThreadListV2Row, ThreadListV2SettledShelfHeader, ThreadListV2SnoozedShelfHeader,} from "./thread-list-v2-items";import { buildThreadListV2Items, buildThreadListV2ListItems, THREAD_LIST_V2_SETTLED_INITIAL_COUNT, THREAD_LIST_V2_SETTLED_PAGE_COUNT, type ThreadListV2ListItem,} from "./threadListV2"; /** The sidebar list serves both lists: v1 grouped items or, when the Thread List v2 beta is on, flat v2 rows with queued tasks spliced in, and a settled "Show more" pager. */type SidebarListItem = | HomeListItem | ThreadListV2ListItem | { readonly type: "v2-show-more"; readonly key: string; readonly hiddenCount: number }; const SIDEBAR_STICKY_HEADER_HEIGHT = 106; interface ThreadNavigationSidebarProps { readonly width: number; readonly visible: boolean; readonly selectedThreadKey: string | null; readonly onOpenSettings: () => void; readonly onOpenEnvironmentSettings: () => void; readonly onNewThreadInProject: (project: EnvironmentProject) => void; readonly onSearchQueryChange: (query: string) => void; readonly onSelectThread: (thread: EnvironmentThreadShell) => void; readonly onRequestVisibility: () => void; readonly searchQuery: string;} /** * iPad/large-width sidebar column. * * On iOS the pane is hosted inside its own navigation-inert single-screen * native stack (SidebarNavigationShell) so the header is a real * UINavigationBar: large title, native bar-button items, and a * UISearchController search field — the same chrome a UISplitViewController * column gets. Other platforms keep the custom header chrome. */export function ThreadNavigationSidebar(props: ThreadNavigationSidebarProps) { if (Platform.OS !== "ios") { return <ThreadNavigationSidebarPane {...props} nativeChrome={false} />; } return <NativeSidebarContainer {...props} />;} function NativeSidebarContainer(props: ThreadNavigationSidebarProps) { return ( <View testID="thread-navigation-sidebar" className="flex-1 border-border bg-drawer" style={{ borderRightWidth: StyleSheet.hairlineWidth, width: props.width }} > <SidebarNavigationShell> <ThreadNavigationSidebarPane {...props} nativeChrome /> </SidebarNavigationShell> </View> );} function ThreadNavigationSidebarPane( props: ThreadNavigationSidebarProps & { readonly nativeChrome: boolean },) { const insets = useSafeAreaInsets(); const projects = useProjects(); const threads = useThreadShells(); const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState(); const { savedConnectionsById } = useSavedRemoteConnections(); const searchInputRef = useRef<TextInput>(null); const searchBarRef = useRef<SearchBarCommands>(null); const openSwipeableRef = useRef<SwipeableMethods | null>(null); const sidebarScrollGesture = useMemo(() => Gesture.Native(), []); const { archiveThread, confirmDeleteThread, settleThread, snoozeThread, unsnoozeThread, unsettleThread, pinThread, unpinThread, movePinnedThread, regenerateThreadTitle, } = useThreadListActions(); const threadListV2Enabled = useThreadListV2Enabled(); const pendingTasks = usePendingNewTasks(); const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions(); const environments = useMemo( () => Object.values(savedConnectionsById) .map((connection) => ({ environmentId: connection.environmentId, label: connection.environmentLabel, })) .sort((left, right) => left.label.localeCompare(right.label)), [savedConnectionsById], ); const availableEnvironmentIds = useMemo( () => new Set(environments.map((environment) => environment.environmentId)), [environments], ); const { options, setSelectedEnvironmentId, setProjectSortOrder, setThreadSortOrder } = useHomeListOptions(availableEnvironmentIds); const searchEnvironmentIds = useMemo( () => options.selectedEnvironmentId === null ? workspaceEnvironments .filter((environment) => environment.connectionState === "connected") .map((environment) => environment.environmentId) : workspaceEnvironments.some( (environment) => environment.environmentId === options.selectedEnvironmentId && environment.connectionState === "connected", ) ? [options.selectedEnvironmentId] : [], [options.selectedEnvironmentId, workspaceEnvironments], ); const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery); const threadSearchMatchByKey = useMemo(() => { const matches = new Map<string, EnvironmentThreadSearchMatch>(); for (const match of threadSearch.matches) { if (match.source === "user" || match.source === "assistant") { matches.set(threadSearchMatchKey(match), match); } } return matches; }, [threadSearch.matches]); const matchedThreadKeys = useMemo( () => new Set(threadSearch.matches.map(threadSearchMatchKey)), [threadSearch.matches], ); const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null); const projectScopes = useMemo( () => buildHomeProjectScopes({ projects, environmentId: options.selectedEnvironmentId, projectGroupingMode: options.projectGroupingMode, }), [options.projectGroupingMode, options.selectedEnvironmentId, projects], ); const projectFilterOptions = useMemo( () => projectScopes.map((scope) => ({ key: scope.key, label: scope.title, })), [projectScopes], ); const projectTitleByProjectKey = useMemo( () => new Map( projectScopes.flatMap((scope) => scope.projectRefs.map( (projectRef) => [ scopedProjectKey(projectRef.environmentId, projectRef.projectId), scope.title, ] as const, ), ), ), [projectScopes], ); const selectedProjectScope = useMemo( () => selectedProjectKey === null ? null : (projectScopes.find((scope) => scope.key === selectedProjectKey) ?? null), [projectScopes, selectedProjectKey], ); useEffect(() => { if ( selectedProjectKey !== null && !projectFilterOptions.some((project) => project.key === selectedProjectKey) ) { setSelectedProjectKey(null); } }, [projectFilterOptions, selectedProjectKey]); const selectedProjectRefs = useMemo( () => selectedProjectScope === null ? null : new Set( selectedProjectScope.projectRefs.map((projectRef) => scopedProjectKey(projectRef.environmentId, projectRef.projectId), ), ), [selectedProjectScope], ); const scopedProjects = useMemo( () => threadListV2Enabled ? [] : selectedProjectRefs === null ? projects : projects.filter((project) => selectedProjectRefs.has(scopedProjectKey(project.environmentId, project.id)), ), [threadListV2Enabled, projects, selectedProjectRefs], ); const scopedThreads = useMemo( () => threadListV2Enabled ? [] : selectedProjectRefs === null ? threads : threads.filter((thread) => selectedProjectRefs.has(scopedProjectKey(thread.environmentId, thread.projectId)), ), [threadListV2Enabled, selectedProjectRefs, threads], ); const scopedPendingTasks = useMemo( () => threadListV2Enabled ? [] : selectedProjectRefs === null ? pendingTasks : pendingTasks.filter((pendingTask) => selectedProjectRefs.has( scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId), ), ), [threadListV2Enabled, pendingTasks, selectedProjectRefs], ); const groups = useMemo( () => threadListV2Enabled ? [] : buildHomeThreadGroups({ projects: scopedProjects, threads: scopedThreads, pendingTasks: scopedPendingTasks, environmentId: options.selectedEnvironmentId, searchQuery: props.searchQuery, matchedThreadKeys, projectSortOrder: options.projectSortOrder, threadSortOrder: options.threadSortOrder, projectGroupingMode: options.projectGroupingMode, }), [ threadListV2Enabled, matchedThreadKeys, options, props.searchQuery, scopedPendingTasks, scopedProjects, scopedThreads, ], ); const [groupDisplayStates, setGroupDisplayStates] = useState< ReadonlyMap<string, HomeGroupDisplayState> >(() => new Map()); const updateGroupDisplay = useCallback((key: string, action: HomeGroupDisplayAction) => { setGroupDisplayStates((previous) => { const next = new Map(previous); next.set( key, nextGroupDisplayState(previous.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action), ); return next; }); }, []); const hasSearchQuery = props.searchQuery.trim().length > 0; const listLayout = useMemo( () => threadListV2Enabled ? EMPTY_HOME_LIST_LAYOUT : buildHomeListLayout({ groups, displayStates: groupDisplayStates, showAllThreads: hasSearchQuery, }), [threadListV2Enabled, groups, groupDisplayStates, hasSearchQuery], ); const projectCwdByKey = useMemo(() => { const map = new Map<string, string>(); for (const project of projects) { map.set(scopedProjectKey(project.environmentId, project.id), project.workspaceRoot); } return map; }, [projects]); const projectByKey = useMemo(() => { const map = new Map<string, EnvironmentProject>(); for (const project of projects) { map.set(scopedProjectKey(project.environmentId, project.id), project); } return map; }, [projects]); // Thread List v2 (beta) support — same model as the compact Home list // (HomeScreen.tsx): flat creation-order card block + settled recency tail. // The settled tail renders in pages; expansion resets when the filter // context changes so environment/search flips never inherit a deep page. const [settledVisibleCount, setSettledVisibleCount] = useState( THREAD_LIST_V2_SETTLED_INITIAL_COUNT, ); const settledResetKey = `${options.selectedEnvironmentId ?? "all"}:${selectedProjectKey ?? "all"}:${props.searchQuery.trim()}`; const lastSettledResetKeyRef = useRef(settledResetKey); if (lastSettledResetKeyRef.current !== settledResetKey) { lastSettledResetKeyRef.current = settledResetKey; setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT); } const showMoreSettled = useCallback( () => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT), [], ); const { loaded: shelfPreferencesLoaded, settledShelfExpanded, snoozedShelfExpanded, toggleSettledShelf, toggleSnoozedShelf, } = useThreadListV2ShelfPreferences(); // The queued-start and snooze helpers need a clock while the pane stays open. const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16)); // Snooze wake times are second-precise; a counter bumped exactly at the // next wake boundary re-runs the partition with a fresh clock so a woken // thread reappears immediately instead of on the next minute tick. const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0); useEffect(() => { if (!threadListV2Enabled) return; // Refresh immediately because the mount-time value can be hours old. setNowMinute(new Date().toISOString().slice(0, 16)); const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000); return () => clearInterval(id); }, [threadListV2Enabled]); // Threads on servers without the settlement capability never classify as // settled (the user could neither un-settle nor pin them). const serverConfigs = useAtomValue(environmentServerConfigsAtom); const settlementEnvironmentIds = useMemo(() => { const supported = new Set<EnvironmentId>(); for (const [environmentId, config] of serverConfigs) { if (config.environment.capabilities.threadSettlement === true) { supported.add(environmentId); } } return supported; }, [serverConfigs]); const snoozeEnvironmentIds = useMemo(() => { const supported = new Set<EnvironmentId>(); for (const [environmentId, config] of serverConfigs) { if (config.environment.capabilities.threadSnooze === true) { supported.add(environmentId); } } return supported; }, [serverConfigs]); const pinningEnvironmentIds = useMemo(() => { const supported = new Set<EnvironmentId>(); for (const [environmentId, config] of serverConfigs) { if (config.environment.capabilities.threadPinning === true) { supported.add(environmentId); } } return supported; }, [serverConfigs]); const pinReorderEnvironmentIds = useMemo(() => { const supported = new Set<EnvironmentId>(); for (const [environmentId, config] of serverConfigs) { if (config.environment.capabilities.threadPinReorder === true) { supported.add(environmentId); } } return supported; }, [serverConfigs]); const titleRegenerationEnvironmentIds = useMemo(() => { const supported = new Set<EnvironmentId>(); for (const [environmentId, config] of serverConfigs) { if (config.environment.capabilities.threadTitleRegeneration === true) { supported.add(environmentId); } } return supported; }, [serverConfigs]); const machineByEnvironmentId = useMemo( () => new Map( [...serverConfigs].map( ([environmentId, config]) => [environmentId, resolveEnvironmentMachineKind(config)] as const, ), ), [serverConfigs], ); // Canonical arranged pinned order for Move up/down flags — computed from // all shells so search/scope filtering never disables a valid move. const arrangedPinnedKeys = useMemo(() => { const pinned = sortPinnedThreadsByOrderKey( threads.filter( (thread) => thread.pinnedAt != null && thread.archivedAt === null && pinReorderEnvironmentIds.has(thread.environmentId), ), ); return pinned.map((thread) => `${thread.environmentId}:${thread.id}`); }, [pinReorderEnvironmentIds, threads]); const threadListV2Layout = useMemo(() => { if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0, snoozedCount: 0, snoozedShelfHeaderIndex: null, settledCount: 0, settledShelfHeaderIndex: null, nextSnoozeWakeAt: null, }; return buildThreadListV2Items({ threads: threads.filter((thread) => thread.archivedAt === null), environmentId: options.selectedEnvironmentId, projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs, searchQuery: props.searchQuery, matchedThreadKeys, settlementEnvironmentIds, snoozeEnvironmentIds, settledLimit: settledVisibleCount, now: new Date().toISOString(), snoozedShelfExpanded,Lines 1–500 of 1320. Load more
import type { EnvironmentProject, EnvironmentThreadShell, } from "@t3tools/client-runtime/state/shell"; import { threadSearchMatchKey, type EnvironmentThreadSearchMatch, } from "@t3tools/client-runtime/state/thread-search"; import { LegendList } from "@legendapp/list/react-native"; import type { MenuAction } from "@react-native-menu/menu"; import { useAtomValue } from "@effect/atom-react"; import { type EnvironmentId, resolveEnvironmentMachineKind } from "@t3tools/contracts"; import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { LayoutChangeEvent } from "react-native"; import { Platform, Pressable, StyleSheet, TextInput, View } from "react-native"; import { Gesture, GestureDetector } from "react-native-gesture-handler"; import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import type { SearchBarCommands } from "react-native-screens"; import { AppText as Text } from "../../components/AppText"; import { CompactBrandTitle } from "../../components/CompactBrandTitle"; import { ControlPillMenu } from "../../components/ControlPill"; import { SymbolView } from "../../components/AppSymbol"; import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass"; import { NativeStackScreenOptions } from "../../native/StackHeader"; import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities"; import { useProjects, useThreadShells } from "../../state/entities"; import { useThreadSearch } from "../../state/queries"; import { useThreadListV2Enabled } from "./use-thread-list-v2-enabled"; import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences"; import { environmentServerConfigsAtom } from "../../state/server"; import { usePendingNewTasks } from "../../state/use-pending-new-tasks"; import { useWorkspaceState } from "../../state/workspace"; import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands"; import { hasCustomHomeListOptions, PROJECT_SORT_OPTIONS, THREAD_SORT_OPTIONS, useHomeListOptions, } from "../home/home-list-options"; import { buildHomeListFilterMenu } from "../home/home-list-filter-menu"; import { buildHomeListLayout, DEFAULT_GROUP_DISPLAY_STATE, EMPTY_HOME_LIST_LAYOUT, homeListItemsAreEqual, nextGroupDisplayState, type HomeGroupDisplayAction, type HomeGroupDisplayState, type HomeListItem, } from "../home/homeListItems"; import { buildHomeProjectScopes, buildHomeThreadGroups } from "../home/homeThreadList"; import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions"; import { usePendingTaskListActions } from "../home/usePendingTaskListActions"; import { useThreadListActions } from "../home/useThreadListActions"; import { getConnectionAwareBrandHeaderOptions, WorkspaceConnectionTitle, } from "../home/WorkspaceConnectionTitle"; import { SidebarHeaderActions } from "./sidebar-header-actions"; import { SidebarFilterButton } from "./sidebar-filter-button"; import { createSidebarHeaderItems } from "./sidebar-native-header-items"; import { SidebarNavigationShell } from "./sidebar-navigation-shell"; import { PendingTaskListRow, ThreadListGroupHeader, ThreadListRow, ThreadListShowMoreRow, } from "./thread-list-items"; import { ThreadListV2PendingRow, ThreadListV2Row, ThreadListV2SettledShelfHeader, ThreadListV2SnoozedShelfHeader, } from "./thread-list-v2-items"; import { buildThreadListV2Items, buildThreadListV2ListItems, THREAD_LIST_V2_SETTLED_INITIAL_COUNT, THREAD_LIST_V2_SETTLED_PAGE_COUNT, type ThreadListV2ListItem, } from "./threadListV2"; /** The sidebar list serves both lists: v1 grouped items or, when the Thread List v2 beta is on, flat v2 rows with queued tasks spliced in, and a settled "Show more" pager. */ type SidebarListItem = | HomeListItem | ThreadListV2ListItem | { readonly type: "v2-show-more"; readonly key: string; readonly hiddenCount: number }; const SIDEBAR_STICKY_HEADER_HEIGHT = 106; interface ThreadNavigationSidebarProps { readonly width: number; readonly visible: boolean; readonly selectedThreadKey: string | null; readonly onOpenSettings: () => void; readonly onOpenEnvironmentSettings: () => void; readonly onNewThreadInProject: (project: EnvironmentProject) => void; readonly onSearchQueryChange: (query: string) => void; readonly onSelectThread: (thread: EnvironmentThreadShell) => void; readonly onRequestVisibility: () => void; readonly searchQuery: string; } /** * iPad/large-width sidebar column. * * On iOS the pane is hosted inside its own navigation-inert single-screen * native stack (SidebarNavigationShell) so the header is a real * UINavigationBar: large title, native bar-button items, and a * UISearchController search field — the same chrome a UISplitViewController * column gets. Other platforms keep the custom header chrome. */ export function ThreadNavigationSidebar(props: ThreadNavigationSidebarProps) { if (Platform.OS !== "ios") { return <ThreadNavigationSidebarPane {...props} nativeChrome={false} />; } return <NativeSidebarContainer {...props} />; } function NativeSidebarContainer(props: ThreadNavigationSidebarProps) { return ( <View testID="thread-navigation-sidebar" className="flex-1 border-border bg-drawer" style={{ borderRightWidth: StyleSheet.hairlineWidth, width: props.width }} > <SidebarNavigationShell> <ThreadNavigationSidebarPane {...props} nativeChrome /> </SidebarNavigationShell> </View> ); } function ThreadNavigationSidebarPane( props: ThreadNavigationSidebarProps & { readonly nativeChrome: boolean }, ) { const insets = useSafeAreaInsets(); const projects = useProjects(); const threads = useThreadShells(); const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState(); const { savedConnectionsById } = useSavedRemoteConnections(); const searchInputRef = useRef<TextInput>(null); const searchBarRef = useRef<SearchBarCommands>(null); const openSwipeableRef = useRef<SwipeableMethods | null>(null); const sidebarScrollGesture = useMemo(() => Gesture.Native(), []); const { archiveThread, confirmDeleteThread, settleThread, snoozeThread, unsnoozeThread, unsettleThread, pinThread, unpinThread, movePinnedThread, regenerateThreadTitle, } = useThreadListActions(); const threadListV2Enabled = useThreadListV2Enabled(); const pendingTasks = usePendingNewTasks(); const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions(); const environments = useMemo( () => Object.values(savedConnectionsById) .map((connection) => ({ environmentId: connection.environmentId, label: connection.environmentLabel, })) .sort((left, right) => left.label.localeCompare(right.label)), [savedConnectionsById], ); const availableEnvironmentIds = useMemo( () => new Set(environments.map((environment) => environment.environmentId)), [environments], ); const { options, setSelectedEnvironmentId, setProjectSortOrder, setThreadSortOrder } = useHomeListOptions(availableEnvironmentIds); const searchEnvironmentIds = useMemo( () => options.selectedEnvironmentId === null ? workspaceEnvironments .filter((environment) => environment.connectionState === "connected") .map((environment) => environment.environmentId) : workspaceEnvironments.some( (environment) => environment.environmentId === options.selectedEnvironmentId && environment.connectionState === "connected", ) ? [options.selectedEnvironmentId] : [], [options.selectedEnvironmentId, workspaceEnvironments], ); const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery); const threadSearchMatchByKey = useMemo(() => { const matches = new Map<string, EnvironmentThreadSearchMatch>(); for (const match of threadSearch.matches) { if (match.source === "user" || match.source === "assistant") { matches.set(threadSearchMatchKey(match), match); } } return matches; }, [threadSearch.matches]); const matchedThreadKeys = useMemo( () => new Set(threadSearch.matches.map(threadSearchMatchKey)), [threadSearch.matches], ); const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null); const projectScopes = useMemo( () => buildHomeProjectScopes({ projects, environmentId: options.selectedEnvironmentId, projectGroupingMode: options.projectGroupingMode, }), [options.projectGroupingMode, options.selectedEnvironmentId, projects], ); const projectFilterOptions = useMemo( () => projectScopes.map((scope) => ({ key: scope.key, label: scope.title, })), [projectScopes], ); const projectTitleByProjectKey = useMemo( () => new Map( projectScopes.flatMap((scope) => scope.projectRefs.map( (projectRef) => [ scopedProjectKey(projectRef.environmentId, projectRef.projectId), scope.title, ] as const, ), ), ), [projectScopes], ); const selectedProjectScope = useMemo( () => selectedProjectKey === null ? null : (projectScopes.find((scope) => scope.key === selectedProjectKey) ?? null), [projectScopes, selectedProjectKey], ); useEffect(() => { if ( selectedProjectKey !== null && !projectFilterOptions.some((project) => project.key === selectedProjectKey) ) { setSelectedProjectKey(null); } }, [projectFilterOptions, selectedProjectKey]); const selectedProjectRefs = useMemo( () => selectedProjectScope === null ? null : new Set( selectedProjectScope.projectRefs.map((projectRef) => scopedProjectKey(projectRef.environmentId, projectRef.projectId), ), ), [selectedProjectScope], ); const scopedProjects = useMemo( () => threadListV2Enabled ? [] : selectedProjectRefs === null ? projects : projects.filter((project) => selectedProjectRefs.has(scopedProjectKey(project.environmentId, project.id)), ), [threadListV2Enabled, projects, selectedProjectRefs], ); const scopedThreads = useMemo( () => threadListV2Enabled ? [] : selectedProjectRefs === null ? threads : threads.filter((thread) => selectedProjectRefs.has(scopedProjectKey(thread.environmentId, thread.projectId)), ), [threadListV2Enabled, selectedProjectRefs, threads], ); const scopedPendingTasks = useMemo( () => threadListV2Enabled ? [] : selectedProjectRefs === null ? pendingTasks : pendingTasks.filter((pendingTask) => selectedProjectRefs.has( scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId), ), ), [threadListV2Enabled, pendingTasks, selectedProjectRefs], ); const groups = useMemo( () => threadListV2Enabled ? [] : buildHomeThreadGroups({ projects: scopedProjects, threads: scopedThreads, pendingTasks: scopedPendingTasks, environmentId: options.selectedEnvironmentId, searchQuery: props.searchQuery, matchedThreadKeys, projectSortOrder: options.projectSortOrder, threadSortOrder: options.threadSortOrder, projectGroupingMode: options.projectGroupingMode, }), [ threadListV2Enabled, matchedThreadKeys, options, props.searchQuery, scopedPendingTasks, scopedProjects, scopedThreads, ], ); const [groupDisplayStates, setGroupDisplayStates] = useState< ReadonlyMap<string, HomeGroupDisplayState> >(() => new Map()); const updateGroupDisplay = useCallback((key: string, action: HomeGroupDisplayAction) => { setGroupDisplayStates((previous) => { const next = new Map(previous); next.set( key, nextGroupDisplayState(previous.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action), ); return next; }); }, []); const hasSearchQuery = props.searchQuery.trim().length > 0; const listLayout = useMemo( () => threadListV2Enabled ? EMPTY_HOME_LIST_LAYOUT : buildHomeListLayout({ groups, displayStates: groupDisplayStates, showAllThreads: hasSearchQuery, }), [threadListV2Enabled, groups, groupDisplayStates, hasSearchQuery], ); const projectCwdByKey = useMemo(() => { const map = new Map<string, string>(); for (const project of projects) { map.set(scopedProjectKey(project.environmentId, project.id), project.workspaceRoot); } return map; }, [projects]); const projectByKey = useMemo(() => { const map = new Map<string, EnvironmentProject>(); for (const project of projects) { map.set(scopedProjectKey(project.environmentId, project.id), project); } return map; }, [projects]); // Thread List v2 (beta) support — same model as the compact Home list // (HomeScreen.tsx): flat creation-order card block + settled recency tail. // The settled tail renders in pages; expansion resets when the filter // context changes so environment/search flips never inherit a deep page. const [settledVisibleCount, setSettledVisibleCount] = useState( THREAD_LIST_V2_SETTLED_INITIAL_COUNT, ); const settledResetKey = `${options.selectedEnvironmentId ?? "all"}:${selectedProjectKey ?? "all"}:${props.searchQuery.trim()}`; const lastSettledResetKeyRef = useRef(settledResetKey); if (lastSettledResetKeyRef.current !== settledResetKey) { lastSettledResetKeyRef.current = settledResetKey; setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT); } const showMoreSettled = useCallback( () => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT), [], ); const { loaded: shelfPreferencesLoaded, settledShelfExpanded, snoozedShelfExpanded, toggleSettledShelf, toggleSnoozedShelf, } = useThreadListV2ShelfPreferences(); // The queued-start and snooze helpers need a clock while the pane stays open. const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16)); // Snooze wake times are second-precise; a counter bumped exactly at the // next wake boundary re-runs the partition with a fresh clock so a woken // thread reappears immediately instead of on the next minute tick. const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0); useEffect(() => { if (!threadListV2Enabled) return; // Refresh immediately because the mount-time value can be hours old. setNowMinute(new Date().toISOString().slice(0, 16)); const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000); return () => clearInterval(id); }, [threadListV2Enabled]); // Threads on servers without the settlement capability never classify as // settled (the user could neither un-settle nor pin them). const serverConfigs = useAtomValue(environmentServerConfigsAtom); const settlementEnvironmentIds = useMemo(() => { const supported = new Set<EnvironmentId>(); for (const [environmentId, config] of serverConfigs) { if (config.environment.capabilities.threadSettlement === true) { supported.add(environmentId); } } return supported; }, [serverConfigs]); const snoozeEnvironmentIds = useMemo(() => { const supported = new Set<EnvironmentId>(); for (const [environmentId, config] of serverConfigs) { if (config.environment.capabilities.threadSnooze === true) { supported.add(environmentId); } } return supported; }, [serverConfigs]); const pinningEnvironmentIds = useMemo(() => { const supported = new Set<EnvironmentId>(); for (const [environmentId, config] of serverConfigs) { if (config.environment.capabilities.threadPinning === true) { supported.add(environmentId); } } return supported; }, [serverConfigs]); const pinReorderEnvironmentIds = useMemo(() => { const supported = new Set<EnvironmentId>(); for (const [environmentId, config] of serverConfigs) { if (config.environment.capabilities.threadPinReorder === true) { supported.add(environmentId); } } return supported; }, [serverConfigs]); const titleRegenerationEnvironmentIds = useMemo(() => { const supported = new Set<EnvironmentId>(); for (const [environmentId, config] of serverConfigs) { if (config.environment.capabilities.threadTitleRegeneration === true) { supported.add(environmentId); } } return supported; }, [serverConfigs]); const machineByEnvironmentId = useMemo( () => new Map( [...serverConfigs].map( ([environmentId, config]) => [environmentId, resolveEnvironmentMachineKind(config)] as const, ), ), [serverConfigs], ); // Canonical arranged pinned order for Move up/down flags — computed from // all shells so search/scope filtering never disables a valid move. const arrangedPinnedKeys = useMemo(() => { const pinned = sortPinnedThreadsByOrderKey( threads.filter( (thread) => thread.pinnedAt != null && thread.archivedAt === null && pinReorderEnvironmentIds.has(thread.environmentId), ), ); return pinned.map((thread) => `${thread.environmentId}:${thread.id}`); }, [pinReorderEnvironmentIds, threads]); const threadListV2Layout = useMemo(() => { if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0, snoozedCount: 0, snoozedShelfHeaderIndex: null, settledCount: 0, settledShelfHeaderIndex: null, nextSnoozeWakeAt: null, }; return buildThreadListV2Items({ threads: threads.filter((thread) => thread.archivedAt === null), environmentId: options.selectedEnvironmentId, projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs, searchQuery: props.searchQuery, matchedThreadKeys, settlementEnvironmentIds, snoozeEnvironmentIds, settledLimit: settledVisibleCount, now: new Date().toISOString(), snoozedShelfExpanded,