Compare commits

...
Author SHA1 Message Date
Julius MarmingeandClaude bd781891c5 Make thread list v2 the only mobile thread list
Retires the device-local `threadListV2Enabled` preference and deletes the
grouped v1 list from Home and the iPad sidebar.

- `HomeScreen` always renders the flat creation-order FlatList; the
  LegendList grouped layout, its group-collapse state, and the
  `collapsedProjectGroups` preference it wrote are gone. The v2 empty
  state now names the environment itself instead of falling through to
  the group-derived v1 empty state.
- `ThreadNavigationSidebar` drops the grouped item arm of
  `SidebarListItem` and its render cases.
- Sort submenus (project/thread) were already hidden whenever the beta
  was on, so they go with it, along with `hasCustomHomeListOptions`,
  `PROJECT_SORT_OPTIONS`, `THREAD_SORT_OPTIONS`, and the thread-sort
  option itself. `projectSortOrder` stays: it still orders the project
  scopes behind the project filter.
- Deletes `homeListItems.ts`, `threadPresentation.ts`,
  `buildHomeThreadGroups`, and the grouped row components
  (`ThreadListGroupHeader`, `ThreadListRow`, `ThreadListShowMoreRow`);
  `PendingTaskListRow` stays, both lists use it.
- Preferences are a plain JSON blob behind a positive allow-list, so
  dropping the two keys needs no migration — they are ignored on load
  and disappear on the next write.

Co-Authored-By: Claude <[email protected]>
2026-07-28 01:11:48 +02:00
17 changed files with 143 additions and 2662 deletions

No files matched your search

+9 -107
View File
@@ -1,7 +1,5 @@
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
import type { EnvironmentId } from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useCallback, useMemo, useRef } from "react";
import { Platform, Pressable, Text as RNText, TextInput, View } from "react-native";
@@ -12,21 +10,14 @@ import { ControlPillMenu } from "../../components/ControlPill";
import { SymbolView } from "../../components/AppSymbol";
import { T3Wordmark } from "../../components/T3Wordmark";
import { useThemeColor } from "../../lib/useThemeColor";
import { mobilePreferencesAtom } from "../../state/preferences";
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
import type { HomeProjectSortOrder } from "./homeThreadList";
import {
buildHomeListFilterMenu,
type HomeListFilterMenuEnvironment,
type HomeListFilterMenuProject,
} from "./home-list-filter-menu";
import {
hasCustomHomeListOptions,
PROJECT_SORT_OPTIONS,
THREAD_SORT_OPTIONS,
} from "./home-list-options";
export type HomeHeaderEnvironment = HomeListFilterMenuEnvironment;
@@ -36,13 +27,9 @@ export function HomeHeader(props: {
readonly searchQuery: string;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly selectedProjectKey: string | null;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly onSearchQueryChange: (query: string) => void;
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
readonly onProjectChange: (projectKey: string | null) => void;
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
readonly onOpenSettings: () => void;
readonly onStartNewTask: () => void;
}) {
@@ -59,24 +46,14 @@ function checkedMenuState(checked: boolean) {
return checked ? ("on" as const) : undefined;
}
/** Thread List v2 lays the list out in fixed creation order, so the
sort/group filter controls would be silently ignored — hide them and
key the "customized" icon state off the environment filter alone. */
function useThreadListV2FilterGate() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
return (
AsyncResult.isSuccess(preferencesResult) && preferencesResult.value.threadListV2Enabled === true
);
}
function AndroidHomeHeader(props: HomeHeaderProps) {
const insets = useSafeAreaInsets();
const iconColor = useThemeColor("--color-icon");
const mutedColor = useThemeColor("--color-foreground-muted");
const threadListV2Enabled = useThreadListV2FilterGate();
const hasCustomListOptions = threadListV2Enabled
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
: hasCustomHomeListOptions(props);
// The list lays out in fixed creation order, so environment and project are
// the only filters that can be customized.
const hasCustomListOptions =
props.selectedEnvironmentId !== null || props.selectedProjectKey !== null;
const menuActions = useMemo<MenuAction[]>(
() => [
{
@@ -115,38 +92,8 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
],
},
] satisfies MenuAction[])),
...(threadListV2Enabled
? []
: ([
{
id: "project-sort",
title: "Sort projects",
subactions: PROJECT_SORT_OPTIONS.map((option) => ({
id: `project-sort:${option.value}`,
title: option.label,
state: checkedMenuState(props.projectSortOrder === option.value),
})),
},
{
id: "thread-sort",
title: "Sort threads",
subactions: THREAD_SORT_OPTIONS.map((option) => ({
id: `thread-sort:${option.value}`,
title: option.label,
state: checkedMenuState(props.threadSortOrder === option.value),
})),
},
] satisfies MenuAction[])),
],
[
props.environments,
props.projectSortOrder,
props.projects,
props.selectedEnvironmentId,
props.selectedProjectKey,
props.threadSortOrder,
threadListV2Enabled,
],
[props.environments, props.projects, props.selectedEnvironmentId, props.selectedProjectKey],
);
const handleMenuAction = useCallback(
(event: { nativeEvent: { event: string } }) => {
@@ -179,20 +126,6 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
}
return;
}
const projectSort = PROJECT_SORT_OPTIONS.find(
(option) => id === `project-sort:${option.value}`,
);
if (projectSort) {
props.onProjectSortOrderChange(projectSort.value);
return;
}
const threadSort = THREAD_SORT_OPTIONS.find((option) => id === `thread-sort:${option.value}`);
if (threadSort) {
props.onThreadSortOrderChange(threadSort.value);
return;
}
},
[props],
);
@@ -291,19 +224,14 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
function IosHomeHeader(props: HomeHeaderProps) {
const searchBarRef = useRef<SearchBarCommands>(null);
const iconColor = useThemeColor("--color-icon");
const threadListV2Enabled = useThreadListV2FilterGate();
const hasCustomListOptions = threadListV2Enabled
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
: hasCustomHomeListOptions(props);
const hasCustomListOptions =
props.selectedEnvironmentId !== null || props.selectedProjectKey !== null;
const focusSearch = useCallback(() => {
searchBarRef.current?.focus();
return searchBarRef.current !== null;
}, []);
useHardwareKeyboardCommand("focusSearch", focusSearch);
const filterMenu = buildHomeListFilterMenu({
...props,
listOrganization: !threadListV2Enabled,
});
const filterMenu = buildHomeListFilterMenu(props);
return (
<>
@@ -426,32 +354,6 @@ function IosHomeHeader(props: HomeHeaderProps) {
))}
</NativeHeaderToolbar.Menu>
) : null}
<NativeHeaderToolbar.Menu title="Sort projects">
<NativeHeaderToolbar.Label>Sort projects</NativeHeaderToolbar.Label>
{PROJECT_SORT_OPTIONS.map((option) => (
<NativeHeaderToolbar.MenuAction
key={option.value}
isOn={props.projectSortOrder === option.value}
onPress={() => props.onProjectSortOrderChange(option.value)}
>
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
<NativeHeaderToolbar.Menu title="Sort threads">
<NativeHeaderToolbar.Label>Sort threads</NativeHeaderToolbar.Label>
{THREAD_SORT_OPTIONS.map((option) => (
<NativeHeaderToolbar.MenuAction
key={option.value}
isOn={props.threadSortOrder === option.value}
onPress={() => props.onThreadSortOrderChange(option.value)}
>
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
</NativeHeaderToolbar.Menu>
<NativeHeaderToolbar.Spacer width={8} sharesBackground={false} />
<NativeHeaderToolbar.SearchBarSlot />
@@ -51,12 +51,8 @@ export function HomeRouteScreen() {
() => new Set(environments.map((environment) => environment.environmentId)),
[environments],
);
const {
options: listOptions,
setSelectedEnvironmentId,
setProjectSortOrder,
setThreadSortOrder,
} = useHomeListOptions(availableEnvironmentIds);
const { options: listOptions, setSelectedEnvironmentId } =
useHomeListOptions(availableEnvironmentIds);
const selectedEnvironmentId = listOptions.selectedEnvironmentId;
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
const projectFilterOptions = useMemo(
@@ -115,15 +111,11 @@ export function HomeRouteScreen() {
searchQuery={searchQuery}
selectedEnvironmentId={selectedEnvironmentId}
selectedProjectKey={selectedProjectKey}
projectSortOrder={listOptions.projectSortOrder}
threadSortOrder={listOptions.threadSortOrder}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
onThreadSortOrderChange={setThreadSortOrder}
/>
<HomeScreen
@@ -142,7 +134,6 @@ export function HomeRouteScreen() {
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onSelectThread={(thread) => {
// Settled threads are live shells: opening one is plain
@@ -165,7 +156,6 @@ export function HomeRouteScreen() {
});
}}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
onThreadSortOrderChange={setThreadSortOrder}
pendingTasks={pendingTasks}
projectGroupingMode={listOptions.projectGroupingMode}
projects={projects}
@@ -175,7 +165,6 @@ export function HomeRouteScreen() {
selectedEnvironmentId={selectedEnvironmentId}
selectedProjectKey={selectedProjectKey}
threads={threads}
threadSortOrder={listOptions.threadSortOrder}
/>
</>
</AndroidHomeFabLayout>
+70 -408
View File
@@ -1,19 +1,9 @@
import {
LegendList,
type LegendListRef,
type LegendListRenderItemProps,
} from "@legendapp/list/react-native";
import {
type EnvironmentProject,
type EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type {
EnvironmentId,
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import type { EnvironmentId, SidebarProjectGroupingMode } from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ActivityIndicator, FlatList, Platform, Pressable, View } from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
@@ -26,15 +16,9 @@ import type { WorkspaceState } from "../../state/workspaceModel";
import type { SavedRemoteConnection } from "../../lib/connection";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { environmentServerConfigsAtom } from "../../state/server";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import {
PendingTaskListRow,
ThreadListGroupHeader,
ThreadListRow,
ThreadListShowMoreRow,
} from "../threads/thread-list-items";
import { PendingTaskListRow } from "../threads/thread-list-items";
import { ThreadListV2Row } from "../threads/thread-list-v2-items";
import {
buildThreadListV2Items,
@@ -43,18 +27,8 @@ import {
type ThreadListV2Item,
} from "../threads/threadListV2";
import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
import {
buildHomeListLayout,
DEFAULT_GROUP_DISPLAY_STATE,
homeListItemsAreEqual,
nextGroupDisplayState,
type HomeGroupDisplayAction,
type HomeGroupDisplayState,
type HomeListItem,
} from "./homeListItems";
import {
buildHomeProjectScopes,
buildHomeThreadGroups,
sortHomeProjectScopes,
type HomeProjectSortOrder,
} from "./homeThreadList";
@@ -75,13 +49,10 @@ interface HomeScreenProps {
readonly selectedEnvironmentId: EnvironmentId | null;
readonly selectedProjectKey: string | null;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
readonly onSearchQueryChange: (query: string) => void;
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
readonly onProjectChange: (projectKey: string | null) => void;
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
readonly onAddConnection: () => void;
readonly onOpenEnvironments: () => void;
readonly onOpenSettings: () => void;
@@ -97,16 +68,6 @@ interface HomeScreenProps {
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
}
/* ─── Layout constants ───────────────────────────────────────────────── */
const ESTIMATED_THREAD_ROW_HEIGHT = 72;
/**
* Top spacing between the list and the Android custom header. The Android
* header (AndroidHomeHeader) is rendered in-flow above this screen and
* already consumes the top safe-area inset, so the list only needs breathing
* room here.
*/
function deriveEmptyState(props: {
readonly catalogState: WorkspaceState;
readonly projectCount: number;
@@ -177,53 +138,9 @@ function HomeTopContentSpacer() {
/* ─── Main screen ────────────────────────────────────────────────────── */
export function HomeScreen(props: HomeScreenProps) {
const [groupDisplayStates, setGroupDisplayStates] = useState<
ReadonlyMap<string, HomeGroupDisplayState>
>(() => new Map());
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const threadListV2Enabled =
AsyncResult.isSuccess(preferencesResult) &&
preferencesResult.value.threadListV2Enabled === true;
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const listRef = useRef<LegendListRef | null>(null);
const insets = useSafeAreaInsets();
const accentColor = useThemeColor("--color-icon-muted");
const effectiveGroupDisplayStates = useMemo(() => {
const next = new Map(groupDisplayStates);
if (!AsyncResult.isSuccess(preferencesResult)) {
return next;
}
for (const key of preferencesResult.value.collapsedProjectGroups ?? []) {
const existing = next.get(key);
next.set(key, {
...(existing ?? DEFAULT_GROUP_DISPLAY_STATE),
collapsed: true,
});
}
return next;
}, [groupDisplayStates, preferencesResult]);
const effectiveGroupDisplayStatesRef = useRef(effectiveGroupDisplayStates);
effectiveGroupDisplayStatesRef.current = effectiveGroupDisplayStates;
const updateGroupDisplay = useCallback(
(key: string, action: HomeGroupDisplayAction) => {
const next = new Map(effectiveGroupDisplayStatesRef.current);
next.set(key, nextGroupDisplayState(next.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action));
effectiveGroupDisplayStatesRef.current = next;
setGroupDisplayStates(next);
if (action === "toggle-collapsed") {
const collapsedProjectGroups: string[] = [];
for (const [groupKey, state] of next) {
if (state.collapsed) {
collapsedProjectGroups.push(groupKey);
}
}
savePreferences({ collapsedProjectGroups });
}
},
[savePreferences],
);
const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
if (openSwipeableRef.current !== methods) {
@@ -254,96 +171,7 @@ export function HomeScreen(props: HomeScreenProps) {
}),
[props.projectGroupingMode, props.projects, props.selectedEnvironmentId],
);
const selectedProjectScope = useMemo(
() =>
props.selectedProjectKey === null
? null
: (projectScopes.find(
(scope) =>
scope.key === props.selectedProjectKey ||
scope.projectRefs.some(
(projectRef) =>
scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
props.selectedProjectKey,
),
) ?? null),
[projectScopes, props.selectedProjectKey],
);
const selectedProjectRefKeys = useMemo(
() =>
selectedProjectScope === null
? null
: new Set(
selectedProjectScope.projectRefs.map((projectRef) =>
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
),
),
[selectedProjectScope],
);
const scopedProjects = useMemo(
() =>
selectedProjectRefKeys === null
? props.projects
: props.projects.filter((project) =>
selectedProjectRefKeys.has(scopedProjectKey(project.environmentId, project.id)),
),
[props.projects, selectedProjectRefKeys],
);
const scopedThreads = useMemo(
() =>
selectedProjectRefKeys === null
? props.threads
: props.threads.filter((thread) =>
selectedProjectRefKeys.has(scopedProjectKey(thread.environmentId, thread.projectId)),
),
[props.threads, selectedProjectRefKeys],
);
const scopedPendingTasks = useMemo(
() =>
selectedProjectRefKeys === null
? props.pendingTasks
: props.pendingTasks.filter((pendingTask) =>
selectedProjectRefKeys.has(
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
),
),
[props.pendingTasks, selectedProjectRefKeys],
);
const projectGroups = useMemo(
() =>
buildHomeThreadGroups({
projects: scopedProjects,
threads: scopedThreads,
pendingTasks: scopedPendingTasks,
environmentId: props.selectedEnvironmentId,
searchQuery: props.searchQuery,
projectSortOrder: props.projectSortOrder,
threadSortOrder: props.threadSortOrder,
projectGroupingMode: props.projectGroupingMode,
}),
[
props.projectGroupingMode,
props.projectSortOrder,
props.searchQuery,
props.selectedEnvironmentId,
props.threadSortOrder,
scopedPendingTasks,
scopedProjects,
scopedThreads,
],
);
const hasSearchQuery = props.searchQuery.trim().length > 0;
const listLayout = useMemo(
() =>
buildHomeListLayout({
groups: projectGroups,
displayStates: effectiveGroupDisplayStates,
showAllThreads: hasSearchQuery,
}),
[projectGroups, effectiveGroupDisplayStates, hasSearchQuery],
);
const projectCwdByKey = useMemo(() => {
const map = new Map<string, string>();
@@ -420,7 +248,7 @@ export function HomeScreen(props: HomeScreenProps) {
),
[v2ScopedProjectGroup],
);
// Thread List v2 (beta): one flat list in creation order, no grouping.
// One flat list in creation order, no grouping.
// Settled threads collapse into a recency tail below the card block.
// Settled threads stay in the live shell stream (settled ≠ archived), so
// the partition works directly off live shells — no snapshot merging or
@@ -477,14 +305,9 @@ export function HomeScreen(props: HomeScreenProps) {
// thread reappears immediately instead of on the next minute tick.
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
useEffect(() => {
if (!threadListV2Enabled) return;
// Refresh immediately on enable: the mount-time value can be hours old
// by the time the beta is switched on, which would misclassify the
// inactivity auto-settle boundary until the first tick.
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);
@@ -506,36 +329,35 @@ export function HomeScreen(props: HomeScreenProps) {
}
return supported;
}, [serverConfigs]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled)
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
const threadListV2Layout = useMemo(
// Settled threads are live shells; archived threads keep their original
// "hidden from lists" meaning.
return buildThreadListV2Items({
threads: props.threads.filter((thread) => thread.archivedAt === null),
environmentId: props.selectedEnvironmentId,
projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
searchQuery: props.searchQuery,
() =>
buildThreadListV2Items({
threads: props.threads.filter((thread) => thread.archivedAt === null),
environmentId: props.selectedEnvironmentId,
projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
searchQuery: props.searchQuery,
changeRequestStateByKey,
settlementEnvironmentIds,
snoozeEnvironmentIds,
settledLimit: settledVisibleCount,
now: `${nowMinute}:00.000Z`,
snoozeNow: new Date().toISOString(),
}),
[
changeRequestStateByKey,
nowMinute,
snoozeWakeTick,
settledVisibleCount,
settlementEnvironmentIds,
snoozeEnvironmentIds,
settledLimit: settledVisibleCount,
now: `${nowMinute}:00.000Z`,
snoozeNow: new Date().toISOString(),
});
}, [
changeRequestStateByKey,
nowMinute,
snoozeWakeTick,
settledVisibleCount,
settlementEnvironmentIds,
snoozeEnvironmentIds,
props.searchQuery,
props.selectedEnvironmentId,
props.threads,
threadListV2Enabled,
v2ScopedProjectGroup,
]);
props.searchQuery,
props.selectedEnvironmentId,
props.threads,
v2ScopedProjectGroup,
],
);
// Re-partition the moment the earliest snooze expires (clamped to the
// signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
@@ -616,106 +438,13 @@ export function HomeScreen(props: HomeScreenProps) {
[],
);
const extraData = useMemo(
() => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }),
[props.savedConnectionsById, projectCwdByKey],
);
const renderItem = useCallback(
({ item }: LegendListRenderItemProps<HomeListItem>) => {
switch (item.type) {
case "header":
return (
<ThreadListGroupHeader
variant="compact"
collapsed={item.collapsed}
isFirst={item.isFirst}
groupKey={item.group.key}
onGroupAction={updateGroupDisplay}
// Aggregated groups (same repo across machines) have no single
// target project, and `pending-project:` groups hold a placeholder
// built from queued-task metadata rather than a real project shell,
// so the quick new-thread button is single-real-project only.
newThreadTarget={item.group.newThreadTarget}
onNewThread={props.onNewThreadInProject}
project={item.group.representative}
threadCount={item.group.threads.length + item.group.pendingTasks.length}
title={item.group.title}
/>
);
case "pending-task":
return (
<PendingTaskListRow
variant="compact"
pendingTask={item.pendingTask}
environmentLabel={
props.savedConnectionsById[item.pendingTask.message.environmentId]
?.environmentLabel ?? null
}
isLast={item.isLast}
onSelectPendingTask={props.onSelectPendingTask}
onDeletePendingTask={props.onDeletePendingTask}
/>
);
case "thread": {
const thread = item.thread;
return (
<ThreadListRow
variant="compact"
thread={thread}
environmentLabel={
props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
}
projectCwd={
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ??
null
}
isLast={item.isLast}
onArchiveThread={props.onArchiveThread}
onDeleteThread={props.onDeleteThread}
onSelectThread={props.onSelectThread}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
/>
);
}
case "show-more":
return (
<ThreadListShowMoreRow
variant="compact"
hiddenCount={item.hiddenCount}
canShowLess={item.canShowLess}
groupKey={item.groupKey}
onGroupAction={updateGroupDisplay}
/>
);
}
},
[
handleSwipeableClose,
handleSwipeableWillOpen,
projectCwdByKey,
props.onArchiveThread,
props.onDeletePendingTask,
props.onDeleteThread,
props.onNewThreadInProject,
props.onSelectPendingTask,
props.onSelectThread,
props.savedConnectionsById,
updateGroupDisplay,
],
);
const keyExtractor = useCallback((item: HomeListItem) => item.key, []);
/* Empty states */
// The signal must ignore the search/environment filters: an active query
// that matches nothing needs the in-list "No results" state, not the
// full-page "No threads yet". Settled threads are unarchived live shells,
// so the v1 check already covers v2.
// so this check covers them too.
const hasAnyThreads =
props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
const hasResults = projectGroups.length > 0;
const selectedEnvironmentLabel =
props.selectedEnvironmentId === null
? null
@@ -825,30 +554,11 @@ export function HomeScreen(props: HomeScreenProps) {
</>
);
const listEmpty = !hasResults ? (
hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : selectedProjectScope !== null ? (
<EmptyState
title={`No threads in ${selectedProjectScope.title}`}
detail="Choose another project or create a new task."
/>
) : selectedEnvironmentLabel ? (
<EmptyState
title={`No threads in ${selectedEnvironmentLabel}`}
detail="Choose another environment or create a new task."
/>
) : (
<EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
)
) : null;
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
// v2 project scope, so it can be null (results elsewhere) while this list
// is empty. Search outranks the scope — "No results" names the actionable
// fact when a query is active. Snoozed threads outrank the rest: "No
// threads yet" over an inbox that is merely all-snoozed reads as data
// loss. Pending tasks render in the header, so the list showing them
// isn't empty in the user's eyes.
// Search outranks the scope — "No results" names the actionable fact when a
// query is active. Snoozed threads outrank the rest: "No threads yet" over
// an inbox that is merely all-snoozed reads as data loss. Pending tasks
// render in the header, so the list showing them isn't empty in the user's
// eyes.
const v2SnoozedCount = threadListV2Layout.snoozedCount;
const v2ListEmpty =
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
@@ -875,106 +585,58 @@ export function HomeScreen(props: HomeScreenProps) {
title={`No threads in ${v2ScopedProjectGroup.title}`}
detail="Choose another project or create a new task."
/>
) : selectedEnvironmentLabel ? (
<EmptyState
title={`No threads in ${selectedEnvironmentLabel}`}
detail="Choose another environment or create a new task."
/>
) : (
listEmpty
<EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
);
if (threadListV2Enabled) {
return (
<View className="flex-1 bg-screen">
<SwipeableScrollGateProvider enabled={swipeEnabled}>
<FlatList
data={threadListV2Items}
renderItem={renderV2Item}
keyExtractor={v2KeyExtractor}
extraData={{
projectByKey,
serverConfigs,
savedConnectionsById: props.savedConnectionsById,
}}
ListHeaderComponent={v2ListHeader}
ListFooterComponent={
threadListV2Layout.hiddenSettledCount > 0 ? (
<Pressable
accessibilityRole="button"
accessibilityLabel={`Show ${Math.min(threadListV2Layout.hiddenSettledCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
onPress={showMoreSettled}
className="mx-4 mt-2 items-center rounded-lg border border-dashed border-border py-2.5"
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
>
<Text className="text-xs font-t3-medium text-foreground-muted">
Show more ({threadListV2Layout.hiddenSettledCount} settled hidden)
</Text>
</Pressable>
) : null
}
ListEmptyComponent={v2ListEmpty}
style={{ flex: 1 }}
automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
showsVerticalScrollIndicator={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
{...scrollGateHandlers}
scrollEventThrottle={16}
contentContainerStyle={{
paddingBottom:
Platform.OS === "ios"
? Math.max(insets.bottom, 24) + 96
: Math.max(insets.bottom, 16) + 88,
}}
/>
</SwipeableScrollGateProvider>
{connectionStatus}
</View>
);
}
return (
<View className="flex-1 bg-screen">
{/* Sticky headers are deliberately not wired up: LegendList's JS sticky
implementation mispositions pinned headers at mount under iOS
automatic content insets (headers render one nav-inset too low until
the first scroll event) and blanks non-pinned headers after
collapse/expand data changes. The flattened layout still exposes
`stickyHeaderIndices` if this gets revisited. */}
<SwipeableScrollGateProvider enabled={swipeEnabled}>
<LegendList
ref={listRef}
data={listLayout.items}
renderItem={renderItem}
keyExtractor={keyExtractor}
itemsAreEqual={homeListItemsAreEqual}
drawDistance={500}
estimatedItemSize={ESTIMATED_THREAD_ROW_HEIGHT}
extraData={extraData}
ListHeaderComponent={listHeader}
ListEmptyComponent={listEmpty}
<FlatList
data={threadListV2Items}
renderItem={renderV2Item}
keyExtractor={v2KeyExtractor}
extraData={{
projectByKey,
serverConfigs,
savedConnectionsById: props.savedConnectionsById,
}}
ListHeaderComponent={v2ListHeader}
ListFooterComponent={
threadListV2Layout.hiddenSettledCount > 0 ? (
<Pressable
accessibilityRole="button"
accessibilityLabel={`Show ${Math.min(threadListV2Layout.hiddenSettledCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
onPress={showMoreSettled}
className="mx-4 mt-2 items-center rounded-lg border border-dashed border-border py-2.5"
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
>
<Text className="text-xs font-t3-medium text-foreground-muted">
Show more ({threadListV2Layout.hiddenSettledCount} settled hidden)
</Text>
</Pressable>
) : null
}
ListEmptyComponent={v2ListEmpty}
style={{ flex: 1 }}
automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
contentInsetAdjustmentBehavior={NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"}
automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
showsVerticalScrollIndicator={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
{...scrollGateHandlers}
recycleItems
scrollEventThrottle={16}
contentContainerStyle={{
// Android reserves room for the floating new-task FAB
// (56 button + 16 gap + bottom inset).
paddingBottom:
Platform.OS === "ios"
? Math.max(insets.bottom, 24) + 24
? Math.max(insets.bottom, 24) + 96
: Math.max(insets.bottom, 16) + 88,
}}
scrollIndicatorInsets={
Platform.OS === "ios"
? {
bottom: Math.max(insets.bottom, 16) + 24,
top: 0,
}
: undefined
}
/>
</SwipeableScrollGateProvider>
{connectionStatus}
@@ -13,12 +13,8 @@ describe("buildHomeListFilterMenu", () => {
],
selectedEnvironmentId: null,
selectedProjectKey: "environment-1:project-1",
projectSortOrder: "updated_at",
threadSortOrder: "updated_at",
onEnvironmentChange: vi.fn(),
onProjectChange,
onProjectSortOrderChange: vi.fn(),
onThreadSortOrderChange: vi.fn(),
});
const projectMenu = menu.items.find(
@@ -1,7 +1,4 @@
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
import type { HomeProjectSortOrder } from "./homeThreadList";
import { PROJECT_SORT_OPTIONS, THREAD_SORT_OPTIONS } from "./home-list-options";
import type { EnvironmentId } from "@t3tools/contracts";
export interface HomeListFilterMenuEnvironment {
readonly environmentId: EnvironmentId;
@@ -37,16 +34,8 @@ export function buildHomeListFilterMenu(props: {
readonly projects: ReadonlyArray<HomeListFilterMenuProject>;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly selectedProjectKey: string | null;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
readonly onProjectChange: (projectKey: string | null) => void;
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
/** False hides the sort/group submenus. Thread List v2 uses a fixed
creation-order layout, so offering those controls while it silently
ignores them would be a lie; the environment filter still applies. */
readonly listOrganization?: boolean;
}): HomeListFilterMenu {
const items: Array<HomeListFilterMenuAction | HomeListFilterMenuSubmenu> = [];
@@ -95,31 +84,6 @@ export function buildHomeListFilterMenu(props: {
});
}
if (props.listOrganization !== false) {
items.push(
{
type: "submenu",
title: "Sort projects",
items: PROJECT_SORT_OPTIONS.map((option) => ({
type: "action",
title: option.label,
state: props.projectSortOrder === option.value ? "on" : "off",
onPress: () => props.onProjectSortOrderChange(option.value),
})),
},
{
type: "submenu",
title: "Sort threads",
items: THREAD_SORT_OPTIONS.map((option) => ({
type: "action",
title: option.label,
state: props.threadSortOrder === option.value ? "on" : "off",
onPress: () => props.onThreadSortOrderChange(option.value),
})),
},
);
}
return {
title: "Thread list options",
items,
@@ -1,31 +0,0 @@
import {
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { hasCustomHomeListOptions, type HomeListOptions } from "./home-list-options";
const defaults: HomeListOptions = {
selectedEnvironmentId: null,
projectSortOrder:
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
? "updated_at"
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
};
describe("home list options", () => {
it("recognizes default options", () => {
expect(hasCustomHomeListOptions(defaults)).toBe(false);
});
it("marks environment filters as customized", () => {
expect(
hasCustomHomeListOptions({ ...defaults, selectedEnvironmentId: "environment-1" as never }),
).toBe(true);
expect(
hasCustomHomeListOptions({ ...defaults, selectedProjectKey: "environment-1:project-1" }),
).toBe(true);
});
});
@@ -1,12 +1,5 @@
import type {
EnvironmentId,
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import {
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
} from "@t3tools/contracts";
import type { EnvironmentId, SidebarProjectGroupingMode } from "@t3tools/contracts";
import { DEFAULT_SIDEBAR_PROJECT_SORT_ORDER } from "@t3tools/contracts";
import {
createContext,
createElement,
@@ -23,8 +16,9 @@ import type { HomeProjectSortOrder } from "./homeThreadList";
export interface HomeListOptions {
readonly selectedEnvironmentId: EnvironmentId | null;
/** Orders the project scopes behind the project filter. The list itself is
always laid out in creation order, so there is no thread sort option. */
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
}
export interface ResolvedHomeListOptions extends HomeListOptions {
@@ -37,22 +31,6 @@ export function resolveProjectGroupingMode(
return projectGroupingEnabled === false ? "separate" : "repository";
}
export const PROJECT_SORT_OPTIONS: ReadonlyArray<{
readonly value: HomeProjectSortOrder;
readonly label: string;
}> = [
{ value: "updated_at", label: "Last user message" },
{ value: "created_at", label: "Created at" },
];
export const THREAD_SORT_OPTIONS: ReadonlyArray<{
readonly value: SidebarThreadSortOrder;
readonly label: string;
}> = [
{ value: "updated_at", label: "Last user message" },
{ value: "created_at", label: "Created at" },
];
function defaultHomeListOptions(): HomeListOptions {
return {
selectedEnvironmentId: null,
@@ -60,7 +38,6 @@ function defaultHomeListOptions(): HomeListOptions {
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
? "updated_at"
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
};
}
@@ -85,23 +62,6 @@ export function HomeListOptionsProvider({
return createElement(HomeListOptionsContext, { value }, children);
}
export function hasCustomHomeListOptions(
options: HomeListOptions & {
readonly selectedProjectKey?: string | null;
},
): boolean {
const defaultProjectSortOrder =
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
? "updated_at"
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER;
return (
options.selectedEnvironmentId !== null ||
(options.selectedProjectKey !== null && options.selectedProjectKey !== undefined) ||
options.projectSortOrder !== defaultProjectSortOrder ||
options.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER
);
}
export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<EnvironmentId>) {
const shared = useContext(HomeListOptionsContext);
const [localOptions, setLocalOptions] = useState<HomeListOptions>(defaultHomeListOptions);
@@ -124,16 +84,8 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environm
const setSelectedEnvironmentId = useCallback((value: EnvironmentId | null) => {
setOptions((current) => ({ ...current, selectedEnvironmentId: value }));
}, []);
const setProjectSortOrder = useCallback((value: HomeProjectSortOrder) => {
setOptions((current) => ({ ...current, projectSortOrder: value }));
}, []);
const setThreadSortOrder = useCallback((value: SidebarThreadSortOrder) => {
setOptions((current) => ({ ...current, threadSortOrder: value }));
}, []);
return {
options: resolvedOptions,
setSelectedEnvironmentId,
setProjectSortOrder,
setThreadSortOrder,
} as const;
}
@@ -1,242 +0,0 @@
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
buildHomeListLayout,
DEFAULT_GROUP_DISPLAY_STATE,
HOME_INITIAL_VISIBLE_THREADS,
HOME_SHOW_MORE_STEP,
nextGroupDisplayState,
type HomeGroupDisplayState,
type HomeListItem,
} from "./homeListItems";
import type { HomeThreadGroup } from "./homeThreadList";
const environmentId = EnvironmentId.make("environment-1");
function makeProject(id: string, title: string): EnvironmentProject {
return {
environmentId,
id: ProjectId.make(id),
title,
workspaceRoot: `/workspaces/${id}`,
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
};
}
function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell {
return {
environmentId,
id: ThreadId.make(id),
projectId,
title: `Thread ${id}`,
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
};
}
function makeGroup(key: string, threadCount: number): HomeThreadGroup {
const project = makeProject(key, key);
const threads = Array.from({ length: threadCount }, (_, index) =>
makeThread(`${key}-thread-${index}`, project.id),
);
return {
key,
title: key,
representative: project,
projects: [project],
pendingTasks: [],
threads,
// All threads inside the recency window, so the baseline stays at the
// initial page size and the pagination expectations below hold.
recentThreads: threads,
newThreadTarget: project,
};
}
function itemTypes(items: ReadonlyArray<HomeListItem>): string[] {
return items.map((item) => item.type);
}
function displayStates(
entries: Record<string, HomeGroupDisplayState>,
): ReadonlyMap<string, HomeGroupDisplayState> {
return new Map(Object.entries(entries));
}
describe("buildHomeListLayout", () => {
it("renders a header plus all threads for a small group without a show-more row", () => {
const layout = buildHomeListLayout({
groups: [makeGroup("alpha", 3)],
displayStates: displayStates({}),
});
expect(itemTypes(layout.items)).toEqual(["header", "thread", "thread", "thread"]);
expect(layout.stickyHeaderIndices).toEqual([0]);
expect(layout.items.at(-1)).toMatchObject({ type: "thread", isLast: true });
});
it("limits large groups to the initial visible count with a show-more row", () => {
const layout = buildHomeListLayout({
groups: [makeGroup("alpha", 133)],
displayStates: displayStates({}),
});
const threadItems = layout.items.filter((item) => item.type === "thread");
expect(threadItems).toHaveLength(HOME_INITIAL_VISIBLE_THREADS);
expect(layout.items.at(-1)).toMatchObject({
type: "show-more",
groupKey: "alpha",
hiddenCount: 133 - HOME_INITIAL_VISIBLE_THREADS,
canShowLess: false,
});
// The show-more row takes over the last slot, so no thread is marked last.
expect(threadItems.every((item) => item.type === "thread" && !item.isLast)).toBe(true);
});
it("reveals more threads per show-more step and offers show-less when exhausted", () => {
const group = makeGroup("alpha", 20);
const expandedOnce = buildHomeListLayout({
groups: [group],
displayStates: displayStates({
alpha: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"),
}),
});
expect(expandedOnce.items.filter((item) => item.type === "thread")).toHaveLength(
HOME_INITIAL_VISIBLE_THREADS + HOME_SHOW_MORE_STEP,
);
expect(expandedOnce.items.at(-1)).toMatchObject({
type: "show-more",
hiddenCount: 4,
canShowLess: true,
});
const fullyExpanded = buildHomeListLayout({
groups: [group],
displayStates: displayStates({
alpha: nextGroupDisplayState(
nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"),
"show-more",
),
}),
});
expect(fullyExpanded.items.filter((item) => item.type === "thread")).toHaveLength(20);
expect(fullyExpanded.items.at(-1)).toMatchObject({
type: "show-more",
hiddenCount: 0,
canShowLess: true,
});
const reset = nextGroupDisplayState(
nextGroupDisplayState(
nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"),
"show-more",
),
"show-less",
);
expect(reset.visibleCount).toBe(HOME_INITIAL_VISIBLE_THREADS);
});
it("offers show-less after expanding a stale group whose baseline is below the page size", () => {
// Stale project: 10 threads total but only 3 within the recency window.
const project = makeProject("stale", "stale");
const threads = Array.from({ length: 10 }, (_, index) =>
makeThread(`stale-thread-${index}`, project.id),
);
const group: HomeThreadGroup = {
key: "stale",
title: "stale",
representative: project,
projects: [project],
pendingTasks: [],
threads,
recentThreads: threads.slice(0, 3),
newThreadTarget: project,
};
const collapsedToRecent = buildHomeListLayout({
groups: [group],
displayStates: displayStates({}),
});
expect(collapsedToRecent.items.filter((item) => item.type === "thread")).toHaveLength(3);
expect(collapsedToRecent.items.at(-1)).toMatchObject({
type: "show-more",
hiddenCount: 7,
canShowLess: false,
});
const expanded = buildHomeListLayout({
groups: [group],
displayStates: displayStates({
stale: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"),
}),
});
expect(expanded.items.filter((item) => item.type === "thread")).toHaveLength(10);
expect(expanded.items.at(-1)).toMatchObject({
type: "show-more",
hiddenCount: 0,
canShowLess: true,
});
});
it("hides threads and the show-more row for collapsed groups", () => {
const layout = buildHomeListLayout({
groups: [makeGroup("alpha", 12), makeGroup("beta", 2)],
displayStates: displayStates({
alpha: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "toggle-collapsed"),
}),
});
expect(itemTypes(layout.items)).toEqual(["header", "header", "thread", "thread"]);
expect(layout.items[0]).toMatchObject({ type: "header", collapsed: true, isFirst: true });
expect(layout.items[1]).toMatchObject({ type: "header", collapsed: false, isFirst: false });
expect(layout.stickyHeaderIndices).toEqual([0, 1]);
});
it("suspends collapse and pagination while searching", () => {
const layout = buildHomeListLayout({
groups: [makeGroup("alpha", 12)],
displayStates: displayStates({
alpha: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "toggle-collapsed"),
}),
showAllThreads: true,
});
expect(layout.items.filter((item) => item.type === "thread")).toHaveLength(12);
expect(layout.items.some((item) => item.type === "show-more")).toBe(false);
});
it("keeps sticky indices aligned across multiple expanded groups", () => {
const layout = buildHomeListLayout({
groups: [makeGroup("alpha", 8), makeGroup("beta", 1)],
displayStates: displayStates({}),
});
// header + 6 threads + show-more = 8 items, so beta's header is index 8.
expect(layout.stickyHeaderIndices).toEqual([0, 8]);
expect(layout.items[8]).toMatchObject({ type: "header", isFirst: false });
});
});
@@ -1,207 +0,0 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import type { HomeThreadGroup } from "./homeThreadList";
/** Threads shown per project before the "Show more" affordance appears. */
export const HOME_INITIAL_VISIBLE_THREADS = 6;
/** Additional threads revealed per "Show more" tap. */
export const HOME_SHOW_MORE_STEP = 10;
export interface HomeGroupDisplayState {
readonly collapsed: boolean;
/** How many threads are currently revealed (clamped to the group size). */
readonly visibleCount: number;
}
export const DEFAULT_GROUP_DISPLAY_STATE: HomeGroupDisplayState = {
collapsed: false,
visibleCount: HOME_INITIAL_VISIBLE_THREADS,
};
export interface HomeHeaderListItem {
readonly type: "header";
readonly key: string;
readonly group: HomeThreadGroup;
readonly collapsed: boolean;
readonly isFirst: boolean;
}
export interface HomeThreadListItem {
readonly type: "thread";
readonly key: string;
readonly thread: EnvironmentThreadShell;
readonly isLast: boolean;
}
export interface HomePendingTaskListItem {
readonly type: "pending-task";
readonly key: string;
readonly pendingTask: PendingNewTask;
readonly isLast: boolean;
}
export interface HomeShowMoreListItem {
readonly type: "show-more";
readonly key: string;
readonly groupKey: string;
/** Threads still hidden. 0 means the group is fully expanded. */
readonly hiddenCount: number;
/** Whether more than the initial count is revealed, so "Show less" applies. */
readonly canShowLess: boolean;
}
export type HomeListItem =
| HomeHeaderListItem
| HomePendingTaskListItem
| HomeThreadListItem
| HomeShowMoreListItem;
export interface HomeListLayout {
readonly items: ReadonlyArray<HomeListItem>;
readonly stickyHeaderIndices: ReadonlyArray<number>;
}
export type HomeGroupDisplayAction = "toggle-collapsed" | "show-more" | "show-less";
export function nextGroupDisplayState(
current: HomeGroupDisplayState,
action: HomeGroupDisplayAction,
): HomeGroupDisplayState {
switch (action) {
case "toggle-collapsed":
return { ...current, collapsed: !current.collapsed };
case "show-more":
return { ...current, visibleCount: current.visibleCount + HOME_SHOW_MORE_STEP };
case "show-less":
return { ...current, visibleCount: HOME_INITIAL_VISIBLE_THREADS };
}
}
/**
* Structural equality for list items. Item objects are rebuilt on every
* collapse/show-more toggle; without this the lists would consider every
* mounted row changed and re-render all of them (each carrying a swipeable +
* a vcs-status subscription). Group/thread references are stable across
* toggles.
*/
export function homeListItemsAreEqual(previous: HomeListItem, item: HomeListItem): boolean {
switch (item.type) {
case "header":
return (
previous.type === "header" &&
previous.group === item.group &&
previous.collapsed === item.collapsed &&
previous.isFirst === item.isFirst
);
case "pending-task":
return (
previous.type === "pending-task" &&
previous.pendingTask === item.pendingTask &&
previous.isLast === item.isLast
);
case "thread":
return (
previous.type === "thread" &&
previous.thread === item.thread &&
previous.isLast === item.isLast
);
case "show-more":
return (
previous.type === "show-more" &&
previous.groupKey === item.groupKey &&
previous.hiddenCount === item.hiddenCount &&
previous.canShowLess === item.canShowLess
);
}
}
export function buildHomeListLayout(input: {
readonly groups: ReadonlyArray<HomeThreadGroup>;
readonly displayStates: ReadonlyMap<string, HomeGroupDisplayState>;
/**
* When searching, pagination is suspended so every match stays visible.
*/
readonly showAllThreads?: boolean;
}): HomeListLayout {
const items: HomeListItem[] = [];
const stickyHeaderIndices: number[] = [];
for (const [groupIndex, group] of input.groups.entries()) {
const display = input.displayStates.get(group.key) ?? DEFAULT_GROUP_DISPLAY_STATE;
const collapsed = display.collapsed && input.showAllThreads !== true;
stickyHeaderIndices.push(items.length);
items.push({
type: "header",
key: `header:${group.key}`,
group,
collapsed,
isFirst: groupIndex === 0,
});
if (collapsed) {
continue;
}
const totalCount = group.threads.length;
// Default to the group's recent-activity window (last few days, or a small
// fallback for stale projects), capped at the initial page size. Until the
// user taps "Show more", older threads stay hidden to save vertical space;
// "Show less" resets visibleCount to the initial constant, which lands back
// here at the recency baseline.
const baselineCount = Math.min(
group.recentThreads.length,
HOME_INITIAL_VISIBLE_THREADS,
totalCount,
);
const visibleCount = input.showAllThreads
? totalCount
: Math.min(
display.visibleCount > HOME_INITIAL_VISIBLE_THREADS
? display.visibleCount
: baselineCount,
totalCount,
);
const visibleThreads = group.threads.slice(0, visibleCount);
const hiddenCount = totalCount - visibleCount;
const hasShowMoreRow = !input.showAllThreads && totalCount > baselineCount;
// Pending (unsent) tasks lead the group and are never paginated away.
for (const [pendingIndex, pendingTask] of group.pendingTasks.entries()) {
items.push({
type: "pending-task",
key: `pending-task:${pendingTask.message.messageId}`,
pendingTask,
isLast:
pendingIndex === group.pendingTasks.length - 1 &&
visibleThreads.length === 0 &&
!hasShowMoreRow,
});
}
for (const [threadIndex, thread] of visibleThreads.entries()) {
items.push({
type: "thread",
key: `thread:${thread.environmentId}:${thread.id}`,
thread,
isLast: threadIndex === visibleThreads.length - 1 && !hasShowMoreRow,
});
}
if (hasShowMoreRow) {
items.push({
type: "show-more",
key: `show-more:${group.key}`,
groupKey: group.key,
hiddenCount,
// Compare against the group's own baseline, not the global page size:
// stale projects start below HOME_INITIAL_VISIBLE_THREADS, and "Show
// less" must be offered as soon as anything beyond the baseline shows.
canShowLess: visibleCount > baselineCount,
});
}
}
return { items, stickyHeaderIndices };
}
@@ -5,11 +5,7 @@ import type {
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
buildHomeProjectScopes,
buildHomeThreadGroups,
sortHomeProjectScopes,
} from "./homeThreadList";
import { buildHomeProjectScopes, sortHomeProjectScopes } from "./homeThreadList";
function makeProject(
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
@@ -50,27 +46,7 @@ function makeThread(
};
}
const NOW = Date.parse("2026-06-29T00:00:00.000Z");
function buildGroups(
projects: ReadonlyArray<EnvironmentProject>,
threads: ReadonlyArray<EnvironmentThreadShell>,
overrides: Partial<Parameters<typeof buildHomeThreadGroups>[0]> = {},
) {
return buildHomeThreadGroups({
projects,
threads,
environmentId: null,
searchQuery: "",
projectSortOrder: "updated_at",
threadSortOrder: "updated_at",
projectGroupingMode: "repository",
now: NOW,
...overrides,
});
}
describe("buildHomeThreadGroups", () => {
describe("home project scopes", () => {
it("builds one v2 scope for the same repository across environments", () => {
const localEnvironmentId = EnvironmentId.make("environment-local");
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
@@ -148,21 +124,12 @@ describe("buildHomeThreadGroups", () => {
updatedAt: "2026-06-02T00:00:00.000Z",
});
const projects = [local, stale, canonicalRemote];
const staleThread = makeThread({
environmentId: remoteEnvironmentId,
id: ThreadId.make("thread-stale-project-ref"),
projectId: stale.id,
title: "Still visible",
updatedAt: "2026-06-03T00:00:00.000Z",
});
const scopes = buildHomeProjectScopes({
projects,
environmentId: null,
projectGroupingMode: "repository",
});
const groups = buildGroups(projects, [staleThread]);
expect(scopes).toHaveLength(1);
expect(scopes[0]?.projects.map((project) => project.id)).toEqual([
local.id,
@@ -173,9 +140,6 @@ describe("buildHomeThreadGroups", () => {
stale.id,
canonicalRemote.id,
]);
expect(groups).toHaveLength(1);
expect(groups[0]?.threads.map((thread) => thread.id)).toEqual([staleThread.id]);
expect(groups[0]?.newThreadTarget?.id).toBe(canonicalRemote.id);
});
it("keeps repository identity from an older duplicate when the freshness winner lacks it", () => {
@@ -395,318 +359,6 @@ describe("buildHomeThreadGroups", () => {
environmentId: null,
projectGroupingMode: "repository",
});
const groups = buildGroups(
[project],
[
makeThread({
environmentId: project.environmentId,
id: ThreadId.make("thread-1"),
projectId: project.id,
title: "Thread",
}),
],
);
expect(scopes[0]?.title).toBe("codething-mvp");
expect(groups[0]?.title).toBe("codething-mvp");
});
it("sorts the newest thread first regardless of snapshot order", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const threads = [
makeThread({
environmentId,
id: ThreadId.make("thread-old"),
projectId: project.id,
title: "Older thread",
updatedAt: "2026-06-02T00:00:00.000Z",
}),
makeThread({
environmentId,
id: ThreadId.make("thread-new"),
projectId: project.id,
title: "Newer thread",
updatedAt: "2026-06-03T00:00:00.000Z",
}),
];
expect(buildGroups([project], threads)[0]?.threads.map((thread) => thread.id)).toEqual([
"thread-new",
"thread-old",
]);
});
it("supports independent project and thread creation-time sorting", () => {
const environmentId = EnvironmentId.make("environment-1");
const olderProject = makeProject({
environmentId,
id: ProjectId.make("project-older"),
title: "Older project",
});
const newerProject = makeProject({
environmentId,
id: ProjectId.make("project-newer"),
title: "Newer project",
});
const threads = [
makeThread({
environmentId,
id: ThreadId.make("old-created"),
projectId: olderProject.id,
title: "Updated recently",
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-05T00:00:00.000Z",
}),
makeThread({
environmentId,
id: ThreadId.make("new-created"),
projectId: olderProject.id,
title: "Created recently",
createdAt: "2026-06-04T00:00:00.000Z",
updatedAt: "2026-06-04T00:00:00.000Z",
}),
makeThread({
environmentId,
id: ThreadId.make("newest-project-thread"),
projectId: newerProject.id,
title: "Newest project",
createdAt: "2026-06-06T00:00:00.000Z",
}),
];
const groups = buildGroups([olderProject, newerProject], threads, {
projectSortOrder: "created_at",
threadSortOrder: "created_at",
projectGroupingMode: "separate",
});
expect(groups.map((group) => group.representative.id)).toEqual([
"project-newer",
"project-older",
]);
expect(groups[1]?.threads.map((thread) => thread.id)).toEqual(["new-created", "old-created"]);
});
it("filters both projects and threads to one environment", () => {
const localEnvironmentId = EnvironmentId.make("environment-local");
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
const projects = [
makeProject({
environmentId: localEnvironmentId,
id: ProjectId.make("project-local"),
title: "Local",
}),
makeProject({
environmentId: remoteEnvironmentId,
id: ProjectId.make("project-remote"),
title: "Remote",
}),
];
const threads = projects.map((project) =>
makeThread({
environmentId: project.environmentId,
id: ThreadId.make(`thread-${project.id}`),
projectId: project.id,
title: project.title,
}),
);
const groups = buildGroups(projects, threads, { environmentId: remoteEnvironmentId });
expect(groups).toHaveLength(1);
expect(groups[0]?.representative.environmentId).toBe(remoteEnvironmentId);
expect(groups[0]?.threads.map((thread) => thread.environmentId)).toEqual([remoteEnvironmentId]);
});
it("matches web repository, repository-path, and separate grouping modes", () => {
const environmentId = EnvironmentId.make("environment-1");
const repositoryIdentity = {
canonicalKey: "github.com/t3tools/t3code",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "[email protected]:t3tools/t3code.git",
},
provider: "github",
owner: "t3tools",
name: "t3code",
displayName: "T3 Code",
rootPath: "/workspaces/t3code",
};
const projects = [
makeProject({
environmentId,
id: ProjectId.make("project-web"),
title: "Web",
workspaceRoot: "/workspaces/t3code/apps/web",
repositoryIdentity,
}),
makeProject({
environmentId,
id: ProjectId.make("project-mobile"),
title: "Mobile",
workspaceRoot: "/workspaces/t3code/apps/mobile",
repositoryIdentity,
}),
];
const threads = projects.map((project) =>
makeThread({
environmentId,
id: ThreadId.make(`thread-${project.id}`),
projectId: project.id,
title: project.title,
}),
);
expect(buildGroups(projects, threads, { projectGroupingMode: "repository" })).toHaveLength(1);
expect(buildGroups(projects, threads, { projectGroupingMode: "repository_path" })).toHaveLength(
2,
);
expect(buildGroups(projects, threads, { projectGroupingMode: "separate" })).toHaveLength(2);
});
it("default view shows only threads from the last 5 days", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const threads = [
makeThread({
environmentId,
id: ThreadId.make("recent-1"),
projectId: project.id,
title: "Today",
updatedAt: "2026-06-28T00:00:00.000Z",
}),
makeThread({
environmentId,
id: ThreadId.make("recent-2"),
projectId: project.id,
title: "Within window",
updatedAt: "2026-06-25T00:00:00.000Z",
}),
makeThread({
environmentId,
id: ThreadId.make("old"),
projectId: project.id,
title: "Two weeks ago",
updatedAt: "2026-06-14T00:00:00.000Z",
}),
];
const group = buildGroups([project], threads)[0];
// Default view trims to recent threads...
expect(group?.recentThreads.map((thread) => thread.id)).toEqual(["recent-1", "recent-2"]);
// ...while full history stays available for the expanded view.
expect(group?.threads.map((thread) => thread.id)).toEqual(["recent-1", "recent-2", "old"]);
});
it("falls back to the most recent 3 threads when none are within 5 days", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const threads = ["2026-06-01", "2026-06-02", "2026-06-03", "2026-06-04", "2026-06-05"].map(
(day, index) =>
makeThread({
environmentId,
id: ThreadId.make(`thread-${index}`),
projectId: project.id,
title: `Thread ${index}`,
updatedAt: `${day}T00:00:00.000Z`,
}),
);
const group = buildGroups([project], threads)[0];
expect(group?.recentThreads.map((thread) => thread.id)).toEqual([
"thread-4",
"thread-3",
"thread-2",
]);
expect(group?.threads).toHaveLength(5);
});
it("does not apply the recency window while searching", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const threads = ["2026-06-01", "2026-06-02", "2026-06-03", "2026-06-04", "2026-06-05"].map(
(day, index) =>
makeThread({
environmentId,
id: ThreadId.make(`thread-${index}`),
projectId: project.id,
title: `Thread ${index}`,
updatedAt: `${day}T00:00:00.000Z`,
}),
);
const group = buildGroups([project], threads, { searchQuery: "T3 Code" })[0];
// Search reaches the full history rather than the 3-thread fallback.
expect(group?.recentThreads).toHaveLength(5);
expect(group?.recentThreads.map((thread) => thread.id)).toEqual(
group?.threads.map((thread) => thread.id),
);
});
it("targets quick new threads at the group member with the newest thread", () => {
const laptopEnv = EnvironmentId.make("environment-laptop");
const desktopEnv = EnvironmentId.make("environment-desktop");
const repositoryIdentity = {
canonicalKey: "github.com/pingdotgg/t3code",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "[email protected]:pingdotgg/t3code.git",
},
};
const laptopProject = makeProject({
environmentId: laptopEnv,
id: ProjectId.make("project-laptop"),
title: "t3code",
repositoryIdentity,
});
const desktopProject = makeProject({
environmentId: desktopEnv,
id: ProjectId.make("project-desktop"),
title: "t3code",
repositoryIdentity,
});
const threads = [
makeThread({
environmentId: laptopEnv,
id: ThreadId.make("thread-laptop"),
projectId: laptopProject.id,
title: "Older laptop thread",
updatedAt: "2026-06-27T00:00:00.000Z",
}),
makeThread({
environmentId: desktopEnv,
id: ThreadId.make("thread-desktop"),
projectId: desktopProject.id,
title: "Newest desktop thread",
updatedAt: "2026-06-28T00:00:00.000Z",
}),
];
// Aggregated into one group by repository; the quick new-thread target
// must follow the newest thread (desktop), not the arbitrary first member.
const groups = buildGroups([laptopProject, desktopProject], threads);
expect(groups).toHaveLength(1);
expect(groups[0]?.projects).toHaveLength(2);
expect(groups[0]?.newThreadTarget?.environmentId).toBe(desktopEnv);
expect(groups[0]?.newThreadTarget?.id).toBe(desktopProject.id);
});
});
@@ -9,7 +9,6 @@ import type {
} from "@t3tools/client-runtime/state/shell";
import {
getThreadSortTimestamp,
sortThreads,
toSortableTimestamp,
} from "@t3tools/client-runtime/state/thread-sort";
import type {
@@ -17,10 +16,8 @@ import type {
ScopedProjectRef,
SidebarProjectGroupingMode,
SidebarProjectSortOrder,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Option from "effect/Option";
import * as Order from "effect/Order";
import { scopedProjectKey } from "../../lib/scopedEntities";
@@ -182,240 +179,3 @@ export function sortHomeProjectScopes(input: {
),
);
}
/**
* Default home view only surfaces threads active within this window, to keep the
* screen compact while keeping recent work visible.
*/
const RECENT_THREAD_WINDOW_MS = 5 * 24 * 60 * 60 * 1000;
/** Fallback when a project has no threads inside the recency window. */
const RECENT_THREAD_FALLBACK_COUNT = 3;
export interface HomeThreadGroup {
readonly key: string;
readonly title: string;
readonly representative: EnvironmentProject;
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
/** Full sorted thread history for the group (revealed when expanded / searching). */
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
/** Subset shown by default: threads from the last few days, or the most recent few. */
readonly recentThreads: ReadonlyArray<EnvironmentThreadShell>;
/**
* Where a quick "new thread in this project" should land. For aggregated
* groups (same repo on several machines) this is the member that owns the
* group's most recent thread — the machine the user last worked on — rather
* than the arbitrary first member; the draft's computer picker covers
* switching from there. Null only for synthetic pending-project groups,
* whose single "project" is a placeholder built from queued-task metadata.
*/
readonly newThreadTarget: EnvironmentProject | null;
}
interface MutableHomeThreadGroup {
readonly key: string;
readonly projects: EnvironmentProject[];
readonly pendingTasks: PendingNewTask[];
readonly threads: EnvironmentThreadShell[];
}
function groupSortTimestamp(group: HomeThreadGroup, sortOrder: HomeProjectSortOrder): number {
const latestThread = group.threads.reduce(
(latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
Number.NEGATIVE_INFINITY,
);
return group.pendingTasks.reduce((latest, pendingTask) => {
const timestamp = Date.parse(pendingTask.message.createdAt);
return Number.isNaN(timestamp) ? latest : Math.max(latest, timestamp);
}, latestThread);
}
/**
* Trims a group's threads to recent activity for the default home view.
* `sortedThreads` must already be ordered newest-first for `threadSortOrder`.
* Keeps threads within {@link RECENT_THREAD_WINDOW_MS}; when none qualify, keeps
* the most recent {@link RECENT_THREAD_FALLBACK_COUNT} so a project never vanishes.
*/
function selectRecentThreads(
sortedThreads: ReadonlyArray<EnvironmentThreadShell>,
threadSortOrder: SidebarThreadSortOrder,
now: number,
): ReadonlyArray<EnvironmentThreadShell> {
const cutoff = now - RECENT_THREAD_WINDOW_MS;
const recent = sortedThreads.filter(
(thread) => getThreadSortTimestamp(thread, threadSortOrder) >= cutoff,
);
return recent.length > 0 ? recent : sortedThreads.slice(0, RECENT_THREAD_FALLBACK_COUNT);
}
export function buildHomeThreadGroups(input: {
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly pendingTasks?: ReadonlyArray<PendingNewTask>;
readonly environmentId: EnvironmentId | null;
readonly searchQuery: string;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
/** Current time used for the recency window; defaults to now. Injectable for tests. */
readonly now?: number;
}): ReadonlyArray<HomeThreadGroup> {
const now = input.now ?? Date.now();
const groups = new Map<string, MutableHomeThreadGroup>();
const groupKeyByProjectKey = new Map<string, string>();
for (const scope of buildHomeProjectScopes(input)) {
groups.set(scope.key, {
key: scope.key,
projects: [...scope.projects],
pendingTasks: [],
threads: [],
});
for (const projectRef of scope.projectRefs) {
groupKeyByProjectKey.set(
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
scope.key,
);
}
}
for (const pendingTask of input.pendingTasks ?? []) {
if (input.environmentId !== null && pendingTask.message.environmentId !== input.environmentId) {
continue;
}
const physicalKey = scopedProjectKey(
pendingTask.message.environmentId,
pendingTask.creation.projectId,
);
let groupKey = groupKeyByProjectKey.get(physicalKey);
if (!groupKey) {
// The project shell is not loaded (environment offline / project gone).
// A queued task must stay visible and deletable regardless, so build a
// standalone group from the metadata snapshotted at enqueue time.
groupKey = `pending-project:${physicalKey}`;
groupKeyByProjectKey.set(physicalKey, groupKey);
groups.set(groupKey, {
key: groupKey,
projects: [
{
environmentId: pendingTask.message.environmentId,
id: pendingTask.creation.projectId,
title: pendingTask.creation.projectTitle ?? "Unknown project",
workspaceRoot:
pendingTask.creation.projectCwd ?? String(pendingTask.creation.projectId),
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: pendingTask.message.createdAt,
updatedAt: pendingTask.message.createdAt,
},
],
pendingTasks: [],
threads: [],
});
}
groups.get(groupKey)?.pendingTasks.push(pendingTask);
}
for (const thread of input.threads) {
if (thread.archivedAt !== null) {
continue;
}
if (input.environmentId !== null && thread.environmentId !== input.environmentId) {
continue;
}
const physicalKey = scopedProjectKey(thread.environmentId, thread.projectId);
const groupKey = groupKeyByProjectKey.get(physicalKey);
if (!groupKey) {
continue;
}
groups.get(groupKey)?.threads.push(thread);
}
const query = input.searchQuery.trim().toLocaleLowerCase();
const result: HomeThreadGroup[] = [];
for (const group of groups.values()) {
const representative = group.projects[0];
if (!representative || (group.threads.length === 0 && group.pendingTasks.length === 0)) {
continue;
}
const title = deriveProjectGroupLabel({ representative, members: group.projects });
const groupMatches =
query.length === 0 ||
title.toLocaleLowerCase().includes(query) ||
group.projects.some((project) => project.title.toLocaleLowerCase().includes(query));
const matchingThreads = groupMatches
? group.threads
: group.threads.filter((thread) => thread.title.toLocaleLowerCase().includes(query));
const matchingPendingTasks = groupMatches
? group.pendingTasks
: group.pendingTasks.filter((pendingTask) =>
pendingTask.title.toLocaleLowerCase().includes(query),
);
if (matchingThreads.length === 0 && matchingPendingTasks.length === 0) {
continue;
}
const sortedThreads = sortThreads(matchingThreads, input.threadSortOrder);
// An active search should reach the full history, so the recency window
// only trims the default (no-query) view.
const recentThreads =
query.length === 0
? selectRecentThreads(sortedThreads, input.threadSortOrder, now)
: sortedThreads;
// A stale project id still resolves to the canonical member with the same
// environment/path, so quick creation follows the machine with the newest activity.
const lastActiveProject = Arr.head(sortedThreads).pipe(
Option.flatMap((thread) =>
Arr.findFirst(
input.projects,
(project) =>
project.environmentId === thread.environmentId && project.id === thread.projectId,
),
),
Option.flatMap((threadProject) =>
Arr.findFirst(
group.projects,
(project) =>
derivePhysicalProjectKey(project) === derivePhysicalProjectKey(threadProject),
),
),
Option.getOrNull,
);
result.push({
key: group.key,
title,
representative,
projects: group.projects,
pendingTasks: matchingPendingTasks,
threads: sortedThreads,
recentThreads,
newThreadTarget: group.key.startsWith("pending-project:")
? null
: (lastActiveProject ?? representative),
});
}
return Arr.sort(
result,
Order.mapInput(
Order.Struct({
timestamp: Order.flip(Order.Number),
title: Order.String,
key: Order.String,
}),
(group: HomeThreadGroup) => ({
timestamp: groupSortTimestamp(group, input.projectSortOrder),
title: group.title,
key: group.key,
}),
),
);
}
@@ -125,8 +125,6 @@ function LocalSettingsRouteScreen() {
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
</SettingsSection>
<BetaSettingsSection />
<ArchivedThreadsSettingsSection />
<AppSettingsSection />
@@ -512,8 +510,6 @@ function ConfiguredSettingsRouteScreen() {
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
</SettingsSection>
<BetaSettingsSection />
<ArchivedThreadsSettingsSection />
<AppSettingsSection />
@@ -541,35 +537,6 @@ function GeneralSettingsSection() {
);
}
/**
* Device-local beta toggles. Mobile has no client-settings sync, so this is
* the counterpart of web's Settings → Beta backed by mobile preferences.
*/
function BetaSettingsSection() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const threadListV2Enabled = AsyncResult.isSuccess(preferencesResult)
? preferencesResult.value.threadListV2Enabled === true
: false;
return (
<View className="gap-3">
<SettingsSection title="Beta">
<SettingsSwitchRow
icon="sidebar.left"
label="Thread List v2"
value={threadListV2Enabled}
onValueChange={(value) => savePreferences({ threadListV2Enabled: value })}
/>
</SettingsSection>
<Text className="px-2 text-sm text-foreground-muted">
One flat thread list in creation order. Active work renders as cards; settled threads
collapse to compact rows. Switch back any time.
</Text>
</View>
);
}
function AppSettingsSection() {
const icon = useThemeColor("--color-icon");
@@ -6,7 +6,6 @@ import type {
import { LegendList } from "@legendapp/list/react-native";
import type { MenuAction } from "@react-native-menu/menu";
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import type { LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent } from "react-native";
@@ -25,29 +24,14 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
import { useThemeColor } from "../../lib/useThemeColor";
import { useProjects, useThreadShells } from "../../state/entities";
import { mobilePreferencesAtom } from "../../state/preferences";
import { environmentServerConfigsAtom } from "../../state/server";
import { usePendingNewTasks, type PendingNewTask } 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 { useHomeListOptions } from "../home/home-list-options";
import { buildHomeListFilterMenu } from "../home/home-list-filter-menu";
import {
buildHomeListLayout,
DEFAULT_GROUP_DISPLAY_STATE,
homeListItemsAreEqual,
nextGroupDisplayState,
type HomeGroupDisplayAction,
type HomeGroupDisplayState,
type HomeListItem,
} from "../home/homeListItems";
import { buildHomeProjectScopes, buildHomeThreadGroups } from "../home/homeThreadList";
import { buildHomeProjectScopes } from "../home/homeThreadList";
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
import { useThreadListActions } from "../home/useThreadListActions";
@@ -57,12 +41,7 @@ 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 { PendingTaskListRow } from "./thread-list-items";
import { ThreadListV2Row } from "./thread-list-v2-items";
import {
buildThreadListV2Items,
@@ -71,11 +50,9 @@ import {
type ThreadListV2Item,
} from "./threadListV2";
/** The sidebar list serves both lists: v1 grouped items or, when the Thread
List v2 beta is on, queued offline tasks, flat v2 rows, and a settled
"Show more" pager. */
/** The sidebar list holds queued offline tasks, flat thread rows, and a
settled "Show more" pager. */
type SidebarListItem =
| HomeListItem
| {
readonly type: "v2-pending-task";
readonly key: string;
@@ -196,10 +173,6 @@ function ThreadNavigationSidebarPane(
const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
useThreadListActions();
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const threadListV2Enabled =
AsyncResult.isSuccess(preferencesResult) &&
preferencesResult.value.threadListV2Enabled === true;
const pendingTasks = usePendingNewTasks();
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
const environments = useMemo(
@@ -216,8 +189,7 @@ function ThreadNavigationSidebarPane(
() => new Set(environments.map((environment) => environment.environmentId)),
[environments],
);
const { options, setSelectedEnvironmentId, setProjectSortOrder, setThreadSortOrder } =
useHomeListOptions(availableEnvironmentIds);
const { options, setSelectedEnvironmentId } = useHomeListOptions(availableEnvironmentIds);
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
const projectScopes = useMemo(
() =>
@@ -277,72 +249,6 @@ function ThreadNavigationSidebarPane(
),
[selectedProjectScope],
);
const scopedProjects = useMemo(
() =>
selectedProjectRefs === null
? projects
: projects.filter((project) =>
selectedProjectRefs.has(scopedProjectKey(project.environmentId, project.id)),
),
[projects, selectedProjectRefs],
);
const scopedThreads = useMemo(
() =>
selectedProjectRefs === null
? threads
: threads.filter((thread) =>
selectedProjectRefs.has(scopedProjectKey(thread.environmentId, thread.projectId)),
),
[selectedProjectRefs, threads],
);
const scopedPendingTasks = useMemo(
() =>
selectedProjectRefs === null
? pendingTasks
: pendingTasks.filter((pendingTask) =>
selectedProjectRefs.has(
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
),
),
[pendingTasks, selectedProjectRefs],
);
const groups = useMemo(
() =>
buildHomeThreadGroups({
projects: scopedProjects,
threads: scopedThreads,
pendingTasks: scopedPendingTasks,
environmentId: options.selectedEnvironmentId,
searchQuery: props.searchQuery,
projectSortOrder: options.projectSortOrder,
threadSortOrder: options.threadSortOrder,
projectGroupingMode: options.projectGroupingMode,
}),
[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(
() =>
buildHomeListLayout({
groups,
displayStates: groupDisplayStates,
showAllThreads: hasSearchQuery,
}),
[groups, groupDisplayStates, hasSearchQuery],
);
const projectCwdByKey = useMemo(() => {
const map = new Map<string, string>();
for (const project of projects) {
@@ -358,10 +264,10 @@ function ThreadNavigationSidebarPane(
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.
// PR states stream in per-row; merged/closed PRs auto-settle their thread
// on the next partition.
// Same model as the compact Home list (HomeScreen.tsx): flat
// creation-order card block + settled recency tail. PR states stream in
// per-row; merged/closed PRs auto-settle their thread on the next
// partition.
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
ReadonlyMap<string, "open" | "closed" | "merged">
>(() => new Map());
@@ -404,14 +310,9 @@ function ThreadNavigationSidebarPane(
// thread reappears immediately instead of on the next minute tick.
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
useEffect(() => {
if (!threadListV2Enabled) return;
// Refresh immediately on enable: the mount-time value can be hours old
// by the time the beta is switched on, which would misclassify the
// inactivity auto-settle boundary until the first tick.
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);
@@ -433,34 +334,33 @@ function ThreadNavigationSidebarPane(
}
return supported;
}, [serverConfigs]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled)
return { items: [], hiddenSettledCount: 0, snoozedCount: 0, nextSnoozeWakeAt: null };
return buildThreadListV2Items({
threads: threads.filter((thread) => thread.archivedAt === null),
environmentId: options.selectedEnvironmentId,
projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
searchQuery: props.searchQuery,
const threadListV2Layout = useMemo(
() =>
buildThreadListV2Items({
threads: threads.filter((thread) => thread.archivedAt === null),
environmentId: options.selectedEnvironmentId,
projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
searchQuery: props.searchQuery,
changeRequestStateByKey,
settlementEnvironmentIds,
snoozeEnvironmentIds,
settledLimit: settledVisibleCount,
now: `${nowMinute}:00.000Z`,
snoozeNow: new Date().toISOString(),
}),
[
changeRequestStateByKey,
nowMinute,
snoozeWakeTick,
options.selectedEnvironmentId,
props.searchQuery,
settledVisibleCount,
settlementEnvironmentIds,
snoozeEnvironmentIds,
settledLimit: settledVisibleCount,
now: `${nowMinute}:00.000Z`,
snoozeNow: new Date().toISOString(),
});
}, [
changeRequestStateByKey,
nowMinute,
snoozeWakeTick,
options.selectedEnvironmentId,
props.searchQuery,
settledVisibleCount,
settlementEnvironmentIds,
snoozeEnvironmentIds,
threadListV2Enabled,
threads,
selectedProjectScope,
]);
threads,
selectedProjectScope,
],
);
// Re-partition the moment the earliest snooze expires (clamped to the
// signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
@@ -476,12 +376,11 @@ function ThreadNavigationSidebarPane(
// range) the boundary string is identical and the chain would die.
}, [nextSnoozeWakeAt, snoozeWakeTick]);
const listItems = useMemo<readonly SidebarListItem[]>(() => {
if (!threadListV2Enabled) return listLayout.items;
// Queued offline tasks render above the thread rows (mirrors the
// compact Home v2 list): they are not thread shells, so the v2 item
// builder never sees them, but they must stay visible and deletable
// while their environment is offline. Same environment scope and
// search filter as the list.
// compact Home list): they are not thread shells, so the item builder
// never sees them, but they must stay visible and deletable while their
// environment is offline. Same environment scope and search filter as
// the list.
const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
const v2PendingTasks = pendingTasks.filter(
(pendingTask) =>
@@ -516,12 +415,10 @@ function ThreadNavigationSidebarPane(
}
return items;
}, [
listLayout.items,
options.selectedEnvironmentId,
pendingTasks,
props.searchQuery,
selectedProjectRefs,
threadListV2Enabled,
threadListV2Layout,
]);
const showsConnectionStatus = shouldShowWorkspaceConnectionStatus(catalogState);
@@ -568,33 +465,8 @@ function ThreadNavigationSidebarPane(
],
},
] satisfies MenuAction[])),
// v2 lays the list out in fixed creation order — offering sort/group
// controls it silently ignores would be a lie. Environment still
// scopes the v2 partition, so it stays.
...(threadListV2Enabled
? []
: ([
{
id: "project-sort",
title: "Sort projects",
subactions: PROJECT_SORT_OPTIONS.map((option) => ({
id: `project-sort:${option.value}`,
title: option.label,
state: options.projectSortOrder === option.value ? "on" : "off",
})),
},
{
id: "thread-sort",
title: "Sort threads",
subactions: THREAD_SORT_OPTIONS.map((option) => ({
id: `thread-sort:${option.value}`,
title: option.label,
state: options.threadSortOrder === option.value ? "on" : "off",
})),
},
] satisfies MenuAction[])),
],
[environments, options, projectFilterOptions, selectedProjectKey, threadListV2Enabled],
[environments, options, projectFilterOptions, selectedProjectKey],
);
const handleListMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
@@ -621,28 +493,8 @@ function ThreadNavigationSidebarPane(
}
return;
}
const projectSort = PROJECT_SORT_OPTIONS.find(
(option) => `project-sort:${option.value}` === event,
);
if (projectSort) {
setProjectSortOrder(projectSort.value);
return;
}
const threadSort = THREAD_SORT_OPTIONS.find(
(option) => `thread-sort:${option.value}` === event,
);
if (threadSort) {
setThreadSortOrder(threadSort.value);
return;
}
},
[
environments,
projectFilterOptions,
setProjectSortOrder,
setSelectedEnvironmentId,
setThreadSortOrder,
],
[environments, projectFilterOptions, setSelectedEnvironmentId],
);
const backgroundColor = useThemeColor("--color-drawer");
@@ -718,17 +570,7 @@ function ThreadNavigationSidebarPane(
if (previous.type === "v2-pending-task" && item.type === "v2-pending-task") {
return previous.pendingTask === item.pendingTask && previous.isLast === item.isLast;
}
if (
previous.type === "v2-thread" ||
previous.type === "v2-show-more" ||
previous.type === "v2-pending-task" ||
item.type === "v2-thread" ||
item.type === "v2-show-more" ||
item.type === "v2-pending-task"
) {
return false;
}
return homeListItemsAreEqual(previous, item);
return false;
},
[],
);
@@ -823,75 +665,6 @@ function ThreadNavigationSidebarPane(
</Text>
</Pressable>
);
case "header":
return (
<ThreadListGroupHeader
variant="sidebar"
collapsed={item.collapsed}
isFirst={item.isFirst}
groupKey={item.group.key}
onGroupAction={updateGroupDisplay}
// Same gating as the compact Home list: aggregated groups have no
// single target project, and pending-project groups hold a
// placeholder shell rather than a real project.
newThreadTarget={item.group.newThreadTarget}
onNewThread={props.onNewThreadInProject}
project={item.group.representative}
threadCount={item.group.threads.length + item.group.pendingTasks.length}
title={item.group.title}
/>
);
case "pending-task":
return (
<PendingTaskListRow
variant="sidebar"
pendingTask={item.pendingTask}
environmentLabel={
savedConnectionsById[item.pendingTask.message.environmentId]?.environmentLabel ??
null
}
isLast={item.isLast}
onSelectPendingTask={openPendingTask}
onDeletePendingTask={confirmDeletePendingTask}
/>
);
case "thread": {
const thread = item.thread;
return (
<ThreadListRow
variant="sidebar"
thread={thread}
environmentLabel={
savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
}
projectCwd={
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ??
null
}
isLast={item.isLast}
selected={
scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
}
fullSwipeWidth={props.width - 20}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onSelectThread={handleSelectThread}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
simultaneousSwipeGesture={sidebarScrollGesture}
/>
);
}
case "show-more":
return (
<ThreadListShowMoreRow
variant="sidebar"
hiddenCount={item.hiddenCount}
canShowLess={item.canShowLess}
groupKey={item.groupKey}
onGroupAction={updateGroupDisplay}
/>
);
}
},
[
@@ -906,7 +679,6 @@ function ThreadNavigationSidebarPane(
projectByKey,
projectCwdByKey,
projectTitleByProjectKey,
props.onNewThreadInProject,
props.selectedThreadKey,
props.width,
savedConnectionsById,
@@ -916,14 +688,11 @@ function ThreadNavigationSidebarPane(
showMoreSettled,
sidebarScrollGesture,
unsettleThread,
updateGroupDisplay,
],
);
// v2 ignores the sort/group options, so only the environment filter can
// light the "customized" state while the beta is on.
const filterCustomized = threadListV2Enabled
? options.selectedEnvironmentId !== null || selectedProjectKey !== null
: hasCustomHomeListOptions({ ...options, selectedProjectKey });
// The list lays out in fixed creation order, so environment and project are
// the only filters that can be customized.
const filterCustomized = options.selectedEnvironmentId !== null || selectedProjectKey !== null;
const filterIcon = filterCustomized
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle";
@@ -934,24 +703,10 @@ function ThreadNavigationSidebarPane(
projects: projectFilterOptions,
selectedEnvironmentId: options.selectedEnvironmentId,
selectedProjectKey,
projectSortOrder: options.projectSortOrder,
threadSortOrder: options.threadSortOrder,
onEnvironmentChange: setSelectedEnvironmentId,
onProjectChange: setSelectedProjectKey,
onProjectSortOrderChange: setProjectSortOrder,
onThreadSortOrderChange: setThreadSortOrder,
listOrganization: !threadListV2Enabled,
}),
[
environments,
options,
projectFilterOptions,
selectedProjectKey,
setProjectSortOrder,
setSelectedEnvironmentId,
setThreadSortOrder,
threadListV2Enabled,
],
[environments, options, projectFilterOptions, selectedProjectKey, setSelectedEnvironmentId],
);
const nativeHeaderItems = useMemo(
() =>
@@ -1,32 +1,18 @@
import { useRecyclingState } from "@legendapp/list/react-native";
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { MenuAction } from "@react-native-menu/menu";
import { SymbolView } from "../../components/AppSymbol";
import { memo, useCallback, useMemo, type ComponentProps } from "react";
import { Pressable, useColorScheme, useWindowDimensions, View } from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import Svg, { Circle, Path } from "react-native-svg";
import { memo, useCallback } from "react";
import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { ControlPillMenu } from "../../components/ControlPill";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { cn } from "../../lib/cn";
import { relativeTime } from "../../lib/time";
import { useThemeColor } from "../../lib/useThemeColor";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr, type ThreadPr } from "../../state/use-thread-pr";
import type { HomeGroupDisplayAction } from "../home/homeListItems";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { resolveThreadStatus } from "./threadPresentation";
/**
* Shared presentation for the thread lists: the compact (phone) Home list and
* the iPad sidebar render the SAME items — group headers with collapse,
* thread rows with status/PR/subtitle, and show-more rows — differing only in
* metrics and chrome via `variant`.
* Shared presentation for the queued-task row: the compact (phone) Home list
* and the iPad sidebar render the same row, differing only in metrics and
* chrome via `variant`.
*/
export type ThreadListVariant = "compact" | "sidebar";
@@ -34,223 +20,6 @@ export type ThreadListVariant = "compact" | "sidebar";
export const THREAD_LIST_COMPACT_INSET = 20;
const SIDEBAR_ROW_RADIUS = 12;
function pullRequestTintColor(
state: ThreadPr["state"],
colorScheme: ReturnType<typeof useColorScheme>,
) {
const dark = colorScheme === "dark";
switch (state) {
case "open":
return dark ? "#34d399" : "#059669";
case "merged":
return dark ? "#a78bfa" : "#7c3aed";
case "closed":
return dark ? "#a1a1aa" : "#71717a";
}
}
function PullRequestIcon(props: { readonly size: number; readonly color: string }) {
return (
<Svg
width={props.size}
height={props.size}
viewBox="0 0 24 24"
fill="none"
stroke={props.color}
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
>
<Circle cx={18} cy={18} r={3} />
<Circle cx={6} cy={6} r={3} />
<Path d="M13 6h3a2 2 0 0 1 2 2v7" />
<Path d="M6 9v12" />
</Svg>
);
}
/* ─── Project group header ───────────────────────────────────────────── */
export const ThreadListGroupHeader = memo(function ThreadListGroupHeader(props: {
readonly variant: ThreadListVariant;
readonly project: EnvironmentProject;
readonly title: string;
readonly threadCount: number;
readonly collapsed: boolean;
readonly isFirst: boolean;
readonly groupKey: string;
readonly onGroupAction: (key: string, action: HomeGroupDisplayAction) => void;
/** Project a quick new thread should target; null hides the button. */
readonly newThreadTarget?: EnvironmentProject | null;
readonly onNewThread?: (project: EnvironmentProject) => void;
}) {
const iconMutedColor = useThemeColor("--color-icon-muted");
const { groupKey, onGroupAction, onNewThread } = props;
const newThreadTarget = props.newThreadTarget ?? null;
const compact = props.variant === "compact";
const handleToggle = useCallback(
() => onGroupAction(groupKey, "toggle-collapsed"),
[groupKey, onGroupAction],
);
const handleNewThread = useCallback(() => {
if (newThreadTarget) {
onNewThread?.(newThreadTarget);
}
}, [newThreadTarget, onNewThread]);
const showNewThreadButton = onNewThread !== undefined && newThreadTarget !== null;
// The new-thread button is a SIBLING of the collapse toggle, not a child:
// nested touchables are unreachable to VoiceOver/TalkBack (the parent
// swallows focus). Row padding lives on the container (explicit styles —
// dynamic padding classes on Pressable did not apply reliably) so both
// children share one centerline; hitSlop restores the padded tap area.
const verticalHitSlop = { top: props.isFirst ? 8 : 24, bottom: 12 };
return (
<View
className={compact ? "flex-row items-center bg-screen" : "flex-row items-center"}
style={{
minHeight: compact ? 44 : 36,
paddingLeft: compact ? 20 : 12,
// Compact right padding centers the 20pt plus glyph on the thread
// rows' trailing chevron column (18 + 13/2 ≈ 24.5 from the edge).
paddingRight: compact ? 14 : 12,
paddingBottom: compact ? 12 : 8,
paddingTop: props.isFirst ? (compact ? 8 : 4) : compact ? 24 : 20,
}}
>
<Pressable
accessibilityRole="button"
accessibilityState={{ expanded: !props.collapsed }}
accessibilityLabel={`${props.title}, ${props.threadCount} threads`}
accessibilityHint={props.collapsed ? "Expands the project" : "Collapses the project"}
className={
compact ? "flex-1 flex-row items-center gap-2.5" : "flex-1 flex-row items-center gap-2"
}
hitSlop={{ ...verticalHitSlop, left: compact ? 20 : 12 }}
onPress={handleToggle}
>
<ProjectFavicon
environmentId={props.project.environmentId}
open={!props.collapsed}
size={compact ? 22 : 18}
projectTitle={props.project.title}
workspaceRoot={props.project.workspaceRoot}
/>
<Text
className={
compact
? "flex-shrink text-base font-t3-bold tracking-[0.2px] text-foreground-muted"
: "flex-shrink text-sm font-t3-bold tracking-[0.2px] text-foreground-muted"
}
numberOfLines={1}
>
{props.title}
</Text>
<Text
className={
compact
? "flex-1 text-sm font-t3-medium text-foreground-tertiary"
: "flex-1 text-xs font-t3-medium text-foreground-tertiary"
}
>
{props.threadCount}
</Text>
</Pressable>
{showNewThreadButton ? (
<Pressable
accessibilityLabel={`Create new thread in ${props.title}`}
accessibilityRole="button"
hitSlop={{ ...verticalHitSlop, left: 10, right: 14 }}
onPress={handleNewThread}
style={({ pressed }) => ({ opacity: pressed ? 0.5 : 1, paddingLeft: 12 })}
>
<SymbolView
name="plus"
size={compact ? 20 : 16}
tintColor={iconMutedColor}
type="monochrome"
weight="medium"
/>
</Pressable>
) : null}
</View>
);
});
/* ─── Show more / show less row ──────────────────────────────────────── */
export const ThreadListShowMoreRow = memo(function ThreadListShowMoreRow(props: {
readonly variant: ThreadListVariant;
readonly hiddenCount: number;
readonly canShowLess: boolean;
readonly groupKey: string;
readonly onGroupAction: (key: string, action: HomeGroupDisplayAction) => void;
}) {
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const showsMore = props.hiddenCount > 0;
const compact = props.variant === "compact";
const { groupKey, onGroupAction } = props;
const handleShowMore = useCallback(
() => onGroupAction(groupKey, "show-more"),
[groupKey, onGroupAction],
);
const handleShowLess = useCallback(
() => onGroupAction(groupKey, "show-less"),
[groupKey, onGroupAction],
);
const button = (label: string, icon: "chevron.down" | "chevron.up", onPress: () => void) => (
<Pressable
accessibilityRole="button"
accessibilityLabel={label === "Show more" ? "Show more threads" : "Show fewer threads"}
className="rounded-full bg-subtle"
hitSlop={6}
onPress={onPress}
style={({ pressed }) => ({
opacity: pressed ? 0.6 : 1,
paddingHorizontal: compact ? 14 : 12,
paddingVertical: compact ? 7 : 6,
borderCurve: "continuous",
})}
>
<View className="flex-row items-center gap-1.5">
<SymbolView
name={icon}
size={10}
tintColor={iconSubtleColor}
type="monochrome"
weight="semibold"
/>
<Text
className={
compact
? "text-sm font-t3-medium text-foreground-muted"
: "text-xs font-t3-medium text-foreground-muted"
}
>
{label}
</Text>
</View>
</Pressable>
);
return (
<View
className={
compact ? "flex-row items-center gap-2.5 bg-screen" : "flex-row items-center gap-2"
}
style={{
paddingLeft: compact ? THREAD_LIST_COMPACT_INSET : 12,
paddingRight: compact ? 18 : 12,
paddingVertical: compact ? 12 : 8,
}}
>
{showsMore ? button("Show more", "chevron.down", handleShowMore) : null}
{props.canShowLess ? button("Show less", "chevron.up", handleShowLess) : null}
</View>
);
});
/* ─── Pending task row ───────────────────────────────────────────────── */
const PENDING_TASK_MENU_ACTIONS: MenuAction[] = [
@@ -403,264 +172,3 @@ export const PendingTaskListRow = memo(function PendingTaskListRow(props: {
</ControlPillMenu>
);
});
/* ─── Thread row ─────────────────────────────────────────────────────── */
const THREAD_ROW_MENU_ACTIONS: MenuAction[] = [
{ id: "archive", title: "Archive", image: "archivebox" },
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
];
export const ThreadListRow = memo(function ThreadListRow(props: {
readonly variant: ThreadListVariant;
readonly thread: EnvironmentThreadShell;
readonly environmentLabel: string | null;
readonly projectCwd: string | null;
readonly isLast: boolean;
/** Sidebar only: the thread currently open in the detail pane. */
readonly selected?: boolean;
/** Defaults to window width minus compact margins. */
readonly fullSwipeWidth?: number;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
readonly simultaneousSwipeGesture?: ComponentProps<
typeof ThreadSwipeable
>["simultaneousWithExternalGesture"];
}) {
const { width: windowWidth } = useWindowDimensions();
const colorScheme = useColorScheme();
const compact = props.variant === "compact";
const selected = props.selected === true;
// Recycling-safe: resets when the list container is reused for another
// thread, so a hover highlight can't leak across rows.
const [hovered, setHovered] = useRecyclingState(false);
const separatorColor = useThemeColor("--color-separator");
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const screenColor = useThemeColor("--color-screen");
const drawerColor = useThemeColor("--color-drawer");
const pressedBackgroundColor = useThemeColor("--color-subtle");
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
const { thread, onSelectThread, onArchiveThread, onDeleteThread } = props;
const status = resolveThreadStatus(thread);
const pr = useThreadPr(thread, props.projectCwd);
const timestamp = relativeTime(
thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
);
const threadAccessibilityLabel = pr ? `${thread.title}, ${pr.accessibilityLabel}` : thread.title;
const subtitleParts = [props.environmentLabel, thread.branch].filter((part): part is string =>
Boolean(part),
);
const backgroundColor = compact ? screenColor : drawerColor;
const effectivePressedBackground = selected ? "rgba(255,255,255,0.16)" : pressedBackgroundColor;
const effectiveStatus =
selected && status
? { ...status, pillClassName: "bg-white/20", textClassName: "text-white" }
: status;
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
const primaryAction = useMemo(
() => ({
accessibilityLabel: `Archive ${thread.title}`,
icon: "archivebox" as const,
label: "Archive",
onPress: handleArchive,
}),
[handleArchive, thread.title],
);
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "delete") handleDelete();
},
[handleArchive, handleDelete],
);
const statusPill = effectiveStatus ? (
<View className={`${effectiveStatus.pillClassName} rounded-full px-1.5 py-0.5`}>
<Text className={`text-3xs font-t3-bold ${effectiveStatus.textClassName}`}>
{effectiveStatus.label}
</Text>
</View>
) : null;
const subtitleRow =
subtitleParts.length > 0 || pr !== null ? (
<View className="mt-px flex-row items-center gap-1.5">
{subtitleParts.length > 0 ? (
<>
<Text
className={cn(
"shrink",
compact ? "text-sm text-foreground-muted" : "text-xs",
!compact &&
(selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted"),
)}
numberOfLines={1}
>
{subtitleParts.join(" · ")}
</Text>
</>
) : null}
{pr !== null ? (
<View className="flex-row items-center gap-0.5">
<PullRequestIcon
size={compact ? 13 : 11}
color={selected ? "#ffffff" : pullRequestTintColor(pr.state, colorScheme)}
/>
<Text
className={`${compact ? "text-sm" : "text-xs"} font-t3-medium ${
selected ? "text-white" : pr.textClassName
}`}
>
{pr.label}
</Text>
</View>
) : null}
</View>
) : null;
const rowContent = (close: () => void) =>
compact ? (
<Pressable
accessibilityHint="Swipe left for archive and delete actions"
accessibilityLabel={threadAccessibilityLabel}
accessibilityRole="button"
className="bg-screen"
onPress={() => {
close();
onSelectThread(thread);
}}
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
>
<View
style={{
paddingLeft: THREAD_LIST_COMPACT_INSET,
paddingRight: 18,
paddingTop: 10,
}}
>
<View
style={{
gap: 3,
borderBottomWidth: props.isLast ? 0 : 1,
borderBottomColor: separatorColor,
paddingBottom: 10,
}}
>
<View className="flex-row items-center justify-between gap-2">
<Text className="flex-1 text-lg font-t3-bold text-foreground" numberOfLines={1}>
{thread.title}
</Text>
<View className="flex-row items-center gap-2">
{statusPill}
<Text className="text-base tabular-nums text-foreground-tertiary">{timestamp}</Text>
<SymbolView
name="chevron.right"
size={13}
tintColor={iconSubtleColor}
type="monochrome"
/>
</View>
</View>
{subtitleRow}
</View>
</View>
</Pressable>
) : (
<Pressable
accessibilityHint="Opens the thread"
accessibilityLabel={threadAccessibilityLabel}
accessibilityRole="button"
accessibilityState={{ selected }}
onHoverIn={() => setHovered(true)}
onHoverOut={() => setHovered(false)}
onPress={() => {
close();
onSelectThread(thread);
}}
style={({ pressed }) => ({
backgroundColor: selected
? selectedBackgroundColor
: pressed || hovered
? effectivePressedBackground
: backgroundColor,
borderRadius: SIDEBAR_ROW_RADIUS,
cursor: "pointer",
minHeight: 64,
justifyContent: "center",
paddingHorizontal: 12,
paddingVertical: 10,
})}
>
<View className="gap-[3px]">
<View className="flex-row items-center justify-between gap-2">
<Text
className={cn(
"flex-1 text-base font-t3-medium",
selected ? "text-user-bubble-foreground" : "text-foreground",
)}
numberOfLines={1}
>
{thread.title}
</Text>
<View className="flex-row items-center gap-2">
{statusPill}
<Text
className={cn(
"text-xs tabular-nums",
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
)}
numberOfLines={1}
>
{timestamp}
</Text>
</View>
</View>
{subtitleRow}
</View>
</Pressable>
);
return (
<ThreadSwipeable
backgroundColor={backgroundColor}
containerStyle={
compact ? undefined : { borderRadius: SIDEBAR_ROW_RADIUS, overflow: "hidden" }
}
enableTrackpadSwipe
fullSwipeWidth={props.fullSwipeWidth ?? windowWidth - 32}
onDelete={handleDelete}
onSwipeableClose={props.onSwipeableClose}
onSwipeableWillOpen={props.onSwipeableWillOpen}
primaryAction={primaryAction}
resetKey={`${thread.environmentId}:${thread.id}`}
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
threadTitle={thread.title}
>
{(close) => (
// Messages-style row actions on long-press. iOS: a real
// UIContextMenuInteraction with the row as the zoom preview (needs the
// patched @react-native-menu, see
// patches/@[email protected] — in long-press mode the
// interaction is hosted by the component view and the underlying
// UIButton passes touches through, so row taps keep working). Android:
// ControlPillMenu injects onLongPress into the row and anchors the
// token-styled dropdown to it; taps and swipes are untouched.
<ControlPillMenu
actions={THREAD_ROW_MENU_ACTIONS}
onPressAction={handleMenuAction}
shouldOpenOnLongPress
>
{rowContent(close)}
</ControlPillMenu>
)}
</ThreadSwipeable>
);
});
@@ -1,129 +0,0 @@
import type { StatusTone } from "../../components/StatusPill";
import type { OrchestrationLatestTurn, OrchestrationSession } from "@t3tools/contracts";
import { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
export function threadSortValue(thread: EnvironmentThreadShell): number {
const candidate = Date.parse(thread.updatedAt ?? thread.createdAt);
return Number.isNaN(candidate) ? 0 : candidate;
}
export type ThreadStatusKind =
| "pending-approval"
| "awaiting-input"
| "working"
| "connecting"
| "error"
| "plan-ready";
export interface ThreadStatusPresentation extends StatusTone {
readonly kind: ThreadStatusKind;
/** Foreground color for the leading status icon. */
readonly iconColor: string;
/** Background color for the leading status icon circle. */
readonly iconBackground: string;
/** Whether the indicator represents in-flight activity. */
readonly pulse: boolean;
}
/** Neutral icon colors for threads with no actionable status. */
export const THREAD_STATUS_NEUTRAL_ICON = {
iconColor: "#8e8e93",
iconBackground: "rgba(142,142,147,0.22)",
} as const;
function isLatestTurnSettled(
latestTurn: OrchestrationLatestTurn | null,
session: OrchestrationSession | null,
): boolean {
if (!latestTurn?.startedAt) return false;
if (!latestTurn.completedAt) return false;
if (!session) return true;
return session.status !== "running";
}
/**
* Resolves the user-facing status of a thread, in priority order. Returns
* `null` for quiescent threads so rows stay free of "Idle"-style noise.
* Mirrors `resolveThreadStatusPill` in apps/web/src/components/Sidebar.logic.ts.
*/
export function resolveThreadStatus(
thread: EnvironmentThreadShell,
): ThreadStatusPresentation | null {
if (thread.hasPendingApprovals) {
return {
kind: "pending-approval",
label: "Needs Approval",
pillClassName: "bg-amber-500/12 dark:bg-amber-500/16",
textClassName: "text-amber-700 dark:text-amber-300",
iconColor: "#ff9f0a",
iconBackground: "rgba(255,159,10,0.22)",
pulse: false,
};
}
if (thread.hasPendingUserInput) {
return {
kind: "awaiting-input",
label: "Awaiting Input",
pillClassName: "bg-indigo-500/12 dark:bg-indigo-500/16",
textClassName: "text-indigo-700 dark:text-indigo-300",
iconColor: "#5e5ce6",
iconBackground: "rgba(94,92,230,0.22)",
pulse: false,
};
}
if (thread.session?.status === "running") {
return {
kind: "working",
label: "Working",
pillClassName: "bg-sky-500/12 dark:bg-sky-500/16",
textClassName: "text-sky-700 dark:text-sky-300",
iconColor: "#0a84ff",
iconBackground: "rgba(10,132,255,0.22)",
pulse: true,
};
}
if (thread.session?.status === "starting") {
return {
kind: "connecting",
label: "Connecting",
pillClassName: "bg-sky-500/12 dark:bg-sky-500/16",
textClassName: "text-sky-700 dark:text-sky-300",
iconColor: "#0a84ff",
iconBackground: "rgba(10,132,255,0.22)",
pulse: true,
};
}
if (thread.session?.status === "error" || thread.latestTurn?.state === "error") {
return {
kind: "error",
label: "Error",
pillClassName: "bg-rose-500/12 dark:bg-rose-500/16",
textClassName: "text-rose-700 dark:text-rose-300",
iconColor: "#ff453a",
iconBackground: "rgba(255,69,58,0.22)",
pulse: false,
};
}
const hasPlanReadyPrompt =
thread.interactionMode === "plan" &&
isLatestTurnSettled(thread.latestTurn, thread.session) &&
thread.hasActionableProposedPlan;
if (hasPlanReadyPrompt) {
return {
kind: "plan-ready",
label: "Plan Ready",
pillClassName: "bg-violet-500/12 dark:bg-violet-500/16",
textClassName: "text-violet-700 dark:text-violet-300",
iconColor: "#bf5af2",
iconBackground: "rgba(191,90,242,0.22)",
pulse: false,
};
}
return null;
}
@@ -21,14 +21,7 @@ export interface Preferences {
readonly codeFontSize?: number | null;
readonly codeWordBreak?: boolean;
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
readonly collapsedProjectGroups?: readonly string[];
readonly projectGroupingEnabled?: boolean;
/**
* Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no
* client-settings sync, so the flat v2 thread list is opted into per
* device.
*/
readonly threadListV2Enabled?: boolean;
}
export class MobilePreferencesLoadError extends Schema.TaggedErrorClass<MobilePreferencesLoadError>()(
@@ -77,9 +70,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
codeFontSize?: number | null;
codeWordBreak?: boolean;
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
collapsedProjectGroups?: readonly string[];
projectGroupingEnabled?: boolean;
threadListV2Enabled?: boolean;
} = {};
if (typeof parsed.liveActivitiesEnabled === "boolean") {
@@ -101,17 +92,9 @@ function sanitizePreferences(parsed: Preferences): Preferences {
(account): account is string => typeof account === "string",
);
}
if (Array.isArray(parsed.collapsedProjectGroups)) {
preferences.collapsedProjectGroups = parsed.collapsedProjectGroups.filter(
(key): key is string => typeof key === "string",
);
}
if (typeof parsed.projectGroupingEnabled === "boolean") {
preferences.projectGroupingEnabled = parsed.projectGroupingEnabled;
}
if (typeof parsed.threadListV2Enabled === "boolean") {
preferences.threadListV2Enabled = parsed.threadListV2Enabled;
}
return preferences;
}
+4 -4
View File
@@ -99,11 +99,11 @@ describe("mobile preferences state", () => {
const unmountUpdate = registry.mount(state.updatePreferencesAtom);
registry.set(state.updatePreferencesAtom, {
collapsedProjectGroups: ["project:new"],
connectOnboardingOptOutAccounts: ["account:new"],
});
pendingLoad.resolve({
baseFontSize: 18,
collapsedProjectGroups: ["project:old"],
connectOnboardingOptOutAccounts: ["account:old"],
});
const preferences = yield* AtomRegistry.getResult(registry, state.preferencesAtom, {
@@ -111,10 +111,10 @@ describe("mobile preferences state", () => {
});
expect(preferences).toEqual({
baseFontSize: 18,
collapsedProjectGroups: ["project:new"],
connectOnboardingOptOutAccounts: ["account:new"],
});
expect(savePatch).toHaveBeenCalledWith({
collapsedProjectGroups: ["project:new"],
connectOnboardingOptOutAccounts: ["account:new"],
});
expect(AsyncResult.isFailure(registry.get(state.updatePreferencesAtom))).toBe(false);