Skip to content
TypeScript

perf(mobile): thread detail screen and navigation sidebar compile with the React Compiler (#21145)

Julius Marmingead0a7d8667aa
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
index eb1123327e3..01d85ca3295 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -1,3 +1,5 @@
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import { AsyncResult } from "effect/reactivity";
import * as Dialog from "../../components/ui/Dialog";
import { useAtomValue } from "@effect/atom-react";
import { useChildThreadInputs, useThreadReportedModelSelection } from "../../state/entities";
@@ -52,16 +54,7 @@ import type { QueuedRunEdit } from "../../state/queued-run-edit";
import type { FollowUpBehavior } from "../../lib/followUpBehavior";
import type { ActiveTurnComposerAction } from "@t3tools/client-runtime/state/composer-dispatch";
import * as Haptics from "expo-haptics";
-import {
- memo,
- useCallback,
- useContext,
- useEffect,
- useLayoutEffect,
- useMemo,
- useRef,
- useState,
-} from "react";
+import { useContext, useEffect, useLayoutEffect, useRef, useState } from "react";
import {
AppState,
Keyboard,
@@ -326,7 +319,7 @@ const USER_INPUT_TOGGLE_TIMING = {
easing: Easing.out(Easing.cubic),
};
-export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
+export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetailScreenProps) {
const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();
const navigation = useNavigation();
const { session: voiceInputSession } = useGlobalVoiceInput();
@@ -334,33 +327,27 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const deviceState = useEnvironmentQuery(
deviceEnvironment.state({ environmentId: props.environmentId, input: {} }),
);
- const devicePreviews = useMemo(
- () => threadDevicePreviews(deviceState.data, props.selectedThread.id),
- [deviceState.data, props.selectedThread.id],
- );
- const openDevicePreview = useCallback(() => {
+ const devicePreviews = threadDevicePreviews(deviceState.data, props.selectedThread.id);
+ const openDevicePreview = () => {
Keyboard.dismiss();
navigation.navigate("ThreadDevicePreview", {
environmentId: props.environmentId,
threadId: props.selectedThread.id,
});
- }, [navigation, props.environmentId, props.selectedThread.id]);
+ };
const browserTabs = useThreadServerBrowserTabs({
environmentId: props.environmentId,
threadId: props.selectedThread.id,
enabled: props.serverConfig?.environment.capabilities.serverBrowser === true,
});
- const openBrowserPreview = useCallback(
- (tabId?: string) => {
- Keyboard.dismiss();
- navigation.navigate("ThreadBrowserPreview", {
- environmentId: props.environmentId,
- threadId: props.selectedThread.id,
- ...(tabId === undefined ? {} : { tabId }),
- });
- },
- [navigation, props.environmentId, props.selectedThread.id],
- );
+ const openBrowserPreview = (tabId?: string) => {
+ Keyboard.dismiss();
+ navigation.navigate("ThreadBrowserPreview", {
+ environmentId: props.environmentId,
+ threadId: props.selectedThread.id,
+ ...(tabId === undefined ? {} : { tabId }),
+ });
+ };
const insets = useSafeAreaInsets();
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
const liveKeyboardHeight = useKeyboardState((state) => state.height);
@@ -389,12 +376,12 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
useEffect(() => {
setKeyboardStateSuspect(false);
}, [isKeyboardVisible, liveKeyboardHeight]);
- const handleOwnedInputFocusChange = useCallback((focused: boolean) => {
+ const handleOwnedInputFocusChange = (focused: boolean) => {
ownedInputFocusedRef.current = focused;
if (focused) {
setKeyboardStateSuspect(false);
}
- }, []);
+ };
const windowHeight = useWindowDimensions().height;
const navigationHeaderHeight = useContext(HeaderHeightContext) ?? insets.top + 44;
const [screenMetrics, setScreenMetrics] = useState<NativeLayoutMetrics | null>(null);
@@ -419,8 +406,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const frame = requestAnimationFrame(() => composerEditorRef.current?.focus());
return () => cancelAnimationFrame(frame);
}, [editingRunId]);
- const draftMessageRef = useRef(props.draftMessage);
- draftMessageRef.current = props.draftMessage;
const composerOverlayRef = useRef<ViewInstance>(null);
const listRef = useRef<LegendListRef>(null);
const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
@@ -428,13 +413,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const lastScrolledSubmittedMessageIdRef = useRef<MessageId | null>(null);
const [composerExpanded, setComposerExpanded] = useState(false);
const [composerFocused, setComposerFocused] = useState(false);
- const handleComposerFocusChange = useCallback(
- (focused: boolean) => {
- setComposerFocused(focused);
- handleOwnedInputFocusChange(focused);
- },
- [handleOwnedInputFocusChange],
- );
+ const handleComposerFocusChange = (focused: boolean) => {
+ setComposerFocused(focused);
+ handleOwnedInputFocusChange(focused);
+ };
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
const [submittedMessageId, setSubmittedMessageId] = useState<MessageId | null>(null);
const [endFollowEnabled, setEndFollowEnabled] = useState(true);
@@ -579,46 +561,32 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
if (usageLimitsPanel !== null && usageLimitsPanel.key !== usageLimitsKey) {
setUsageLimitsPanel(null);
}
- const usageLimitsReport = useMemo(
- () =>
- usageLimitsPanel !== null && usageLimitsPanel.key === usageLimitsKey
- ? collectProviderUsageLimits(
- props.selectedThread.modelSelection.instanceId,
- props.serverConfig?.providers ?? [],
- props.serverConfig?.usageLimitSources ?? [],
- usageLimitsPanel.now,
- )
- : null,
- [
- props.selectedThread.modelSelection.instanceId,
- props.serverConfig,
- usageLimitsKey,
- usageLimitsPanel,
- ],
- );
- const showUsageLimits = useCallback(
- (report: UsageLimitsReport | null) =>
- setUsageLimitsPanel(
- report === null
- ? null
- : {
- key: usageLimitsKey,
- threadKey: selectedThreadKey,
- now: Date.parse(report.createdAt),
- },
- ),
- [selectedThreadKey, usageLimitsKey],
- );
- const dismissUsageLimits = useCallback(() => setUsageLimitsPanel(null), []);
+ const usageLimitsReport =
+ usageLimitsPanel !== null && usageLimitsPanel.key === usageLimitsKey
+ ? collectProviderUsageLimits(
+ props.selectedThread.modelSelection.instanceId,
+ props.serverConfig?.providers ?? [],
+ props.serverConfig?.usageLimitSources ?? [],
+ usageLimitsPanel.now,
+ )
+ : null;
+ const showUsageLimits = (report: UsageLimitsReport | null) =>
+ setUsageLimitsPanel(
+ report === null
+ ? null
+ : {
+ key: usageLimitsKey,
+ threadKey: selectedThreadKey,
+ now: Date.parse(report.createdAt),
+ },
+ );
+ const dismissUsageLimits = () => setUsageLimitsPanel(null);
// A send may resolve after navigating away, so only the originating
// thread's panel is cleared; a panel opened elsewhere in the meantime stays.
- const clearUsageLimitsFor = useCallback(
- (threadKey: string) =>
- setUsageLimitsPanel((current) =>
- current !== null && current.threadKey === threadKey ? null : current,
- ),
- [],
- );
+ const clearUsageLimitsFor = (threadKey: string) =>
+ setUsageLimitsPanel((current) =>
+ current !== null && current.threadKey === threadKey ? null : current,
+ );
const userInputCollapsed =
activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
// The card's height RESERVES keyboard space at all times instead of tracking the keyboard:
@@ -690,30 +658,32 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
[userInputCoverageApplies],
);
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
+ // Repin timers fire after the render that scheduled them, so they read follow
+ // state from the ref the writers below keep in step with it.
const endFollowEnabledRef = useRef(true);
- endFollowEnabledRef.current = endFollowEnabled;
const overlayRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const previousWorkingControlStateRef = useRef({
threadKey: selectedThreadKey,
visible: false,
});
- const scheduleOverlayRepin = useCallback(
- (delayMs: number) => {
- if (overlayRepinTimerRef.current !== null) {
- clearTimeout(overlayRepinTimerRef.current);
+ const handleEndFollowEnabledChange = (enabled: boolean) => {
+ endFollowEnabledRef.current = enabled;
+ setEndFollowEnabled(enabled);
+ };
+ const scheduleOverlayRepin = (delayMs: number) => {
+ if (overlayRepinTimerRef.current !== null) {
+ clearTimeout(overlayRepinTimerRef.current);
+ }
+ overlayRepinTimerRef.current = setTimeout(() => {
+ overlayRepinTimerRef.current = null;
+ if (!endFollowEnabledRef.current) {
+ return;
}
- overlayRepinTimerRef.current = setTimeout(() => {
- overlayRepinTimerRef.current = null;
- if (!endFollowEnabledRef.current) {
- return;
- }
- void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
- freeze.set(false);
- });
- }, delayMs);
- },
- [freeze, scrollMessageToEnd],
- );
+ void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
+ freeze.set(false);
+ });
+ }, delayMs);
+ };
useEffect(
() => () => {
if (overlayRepinTimerRef.current !== null) {
@@ -739,35 +709,29 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
// checks follow state again so a user who scrolled up stays put.
scheduleOverlayRepin(230);
}, [scheduleOverlayRepin, selectedThreadKey, showFloatingStatus]);
- const handleToggleUserInputCollapsed = useCallback(() => {
+ const handleToggleUserInputCollapsed = () => {
if (activeUserInputRequestId === null) {
return;
}
if (userInputCollapsed) {
- userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
- userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
+ userInputCardProgress.set(withTiming(1, USER_INPUT_TOGGLE_TIMING));
+ userInputInsetProgress.set(withTiming(1, USER_INPUT_TOGGLE_TIMING));
setCollapsedUserInputRequestId(null);
scheduleOverlayRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
} else {
Keyboard.dismiss();
- userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING);
+ userInputCardProgress.set(withTiming(0, USER_INPUT_TOGGLE_TIMING));
// Instant: the sinking card still covers the strip being revealed, and
// animating the inset downward is what drifted the short-content end
// anchor.
- userInputInsetProgress.value = 0;
+ userInputInsetProgress.set(0);
setCollapsedUserInputRequestId(activeUserInputRequestId);
scheduleOverlayRepin(60);
}
- }, [
- activeUserInputRequestId,
- scheduleOverlayRepin,
- userInputCardProgress,
- userInputCollapsed,
- userInputInsetProgress,
- ]);
+ };
useEffect(() => {
- userInputCardProgress.value = 1;
- userInputInsetProgress.value = 1;
+ userInputCardProgress.set(1);
+ userInputInsetProgress.set(1);
}, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
const showContent = props.showContent ?? true;
const layoutVariant = props.layoutVariant ?? "compact";
@@ -806,14 +770,14 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
);
const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
- const selectedProviderSkills = useMemo(() => {
+ const selectedProviderSkills = (() => {
const provider = props.serverConfig?.providers.find(
(candidate) => candidate.instanceId === selectedInstanceId,
);
return provider
? resolveProviderSkillsForCwd(provider, props.threadCwd ?? props.projectWorkspaceRoot)
: [];
- }, [props.projectWorkspaceRoot, props.serverConfig, props.threadCwd, selectedInstanceId]);
+ })();
useLayoutEffect(() => {
selectedThreadKeyRef.current = selectedThreadKey;
@@ -873,6 +837,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
setAnchorMessageId(null);
setSubmittedMessageId(null);
lastScrolledSubmittedMessageIdRef.current = null;
+ endFollowEnabledRef.current = true;
setEndFollowEnabled(true);
freeze.set(false);
}, [freeze, selectedThreadKey]);
@@ -935,98 +900,82 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
selectedThreadKey,
]);
- const handleSendMessage = useCallback(
- async (followUp?: ActiveTurnComposerAction) => {
- const targetThreadKey = selectedThreadKey;
- const hasUserMessage = selectedThreadFeed.some(
- (entry) => entry.type === "message" && entry.message.role === "user",
- );
- const messageId = await props.onSendMessage(followUp);
- if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
- return messageId;
- }
+ const handleSendMessage = async (followUp?: ActiveTurnComposerAction) => {
+ const targetThreadKey = selectedThreadKey;
+ const hasUserMessage = selectedThreadFeed.some(
+ (entry) => entry.type === "message" && entry.message.role === "user",
+ );
+ const messageId = await props.onSendMessage(followUp);
+ if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
+ return messageId;
+ }
- clearUsageLimitsFor(targetThreadKey);
+ clearUsageLimitsFor(targetThreadKey);
- setSubmittedMessageId(messageId);
- setAnchorMessageId(
- resolveThreadFeedSubmissionAnchor({
- currentAnchorMessageId: anchorMessageId,
- submittedMessageId: messageId,
- hasStartedTurn: props.selectedThread.latestRun !== null,
- hasUserMessage,
- queuedMessageCount: props.selectedThreadQueueCount,
- }),
- );
- composerEditorRef.current?.blur();
- return messageId;
- },
- [
- anchorMessageId,
- clearUsageLimitsFor,
- props.onSendMessage,
- props.selectedThread.latestRun,
- props.selectedThreadQueueCount,
- selectedThreadFeed,
- selectedThreadKey,
- ],
- );
+ setSubmittedMessageId(messageId);
+ setAnchorMessageId(
+ resolveThreadFeedSubmissionAnchor({
+ currentAnchorMessageId: anchorMessageId,
+ submittedMessageId: messageId,
+ hasStartedTurn: props.selectedThread.latestRun !== null,
+ hasUserMessage,
+ queuedMessageCount: props.selectedThreadQueueCount,
+ }),
+ );
+ composerEditorRef.current?.blur();
+ return messageId;
+ };
- const handleEditPendingMessage = useCallback(async (message: QueuedThreadMessage) => {
- try {
- if (
- (await editPendingThreadMessage(message)) &&
- selectedThreadKeyRef.current === scopedThreadKey(message.environmentId, message.threadId)
- ) {
- composerEditorRef.current?.focus();
- }
- } catch (error) {
+ const handleEditPendingMessage = async (message: QueuedThreadMessage) => {
+ const edited = await settlePromise(() => editPendingThreadMessage(message));
+ if (AsyncResult.isFailure(edited)) {
+ const error = squashAtomCommandFailure(edited);
Dialog.alert(
"Could not edit message",
error instanceof Error ? error.message : "Please try again.",
);
+ return;
}
- }, []);
+ if (
+ edited.value &&
+ selectedThreadKeyRef.current === scopedThreadKey(message.environmentId, message.threadId)
+ ) {
+ composerEditorRef.current?.focus();
+ }
+ };
- const collapseComposer = useCallback(() => {
+ const collapseComposer = () => {
composerEditorRef.current?.blur();
- }, []);
+ };
- const handleUseArtifactTemplate = useCallback(
- (template: CodexArtifactTemplate) => {
- const currentDraft = draftMessageRef.current;
- const nextDraft = appendCodexArtifactTemplateUsePrompt(currentDraft, template);
- if (nextDraft !== currentDraft) {
- draftMessageRef.current = nextDraft;
- props.onChangeDraftMessage(nextDraft);
- }
- requestAnimationFrame(() => {
- composerEditorRef.current?.focus();
- composerEditorRef.current?.setSelection({ start: nextDraft.length, end: nextDraft.length });
- });
- },
- [props.onChangeDraftMessage],
- );
+ const handleUseArtifactTemplate = (template: CodexArtifactTemplate) => {
+ const nextDraft = appendCodexArtifactTemplateUsePrompt(props.draftMessage, template);
+ if (nextDraft !== props.draftMessage) props.onChangeDraftMessage(nextDraft);
+ requestAnimationFrame(() => {
+ composerEditorRef.current?.focus();
+ composerEditorRef.current?.setSelection({ start: nextDraft.length, end: nextDraft.length });
+ });
+ };
- const handleScrollToEnd = useCallback(() => {
+ const handleScrollToEnd = () => {
void Haptics.selectionAsync();
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
freeze.set(false);
});
- }, [freeze, scrollMessageToEnd]);
+ };
const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
const { themeAppearance } = useAppearancePreferences();
const isDarkMode = themeAppearance === "dark";
- const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
+ const handleFeedTouchStart = (event: GestureResponderEvent) => {
feedTouchStartRef.current = {
pageX: event.nativeEvent.pageX,
pageY: event.nativeEvent.pageY,
};
- }, []);
+ };
- const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
+ const handleFeedTouchMove = (event: GestureResponderEvent) => {
const start = feedTouchStartRef.current;
if (!start) {
return;
@@ -1036,18 +985,18 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
if (Math.hypot(deltaX, deltaY) > 8) {
feedTouchStartRef.current = null;
}
- }, []);
+ };
- const handleFeedTouchEnd = useCallback(() => {
+ const handleFeedTouchEnd = () => {
if (feedTouchStartRef.current) {
collapseComposer();
}
feedTouchStartRef.current = null;
- }, [collapseComposer]);
+ };
- const handleFeedTouchCancel = useCallback(() => {
+ const handleFeedTouchCancel = () => {
feedTouchStartRef.current = null;
- }, []);
+ };
return (
<View className="flex-1">
@@ -1114,7 +1063,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
layoutVariant={layoutVariant}
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
- onEndFollowEnabledChange={setEndFollowEnabled}
+ onEndFollowEnabledChange={handleEndFollowEnabledChange}
skills={selectedProviderSkills}
onUseArtifactTemplate={handleUseArtifactTemplate}
/>
@@ -1415,4 +1364,4 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
) : null}
</View>
);
-});
+};
diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
index d62701444b2..b0b6a4b3272 100644
--- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
@@ -13,7 +13,7 @@ import {
import { LegendList } from "@legendapp/list/react-native";
import type { MenuAction } from "@react-native-menu/menu";
import { useAtomValue } from "@effect/atom-react";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import type { LayoutChangeEvent, TextInputInstance } from "react-native";
import { Platform, StyleSheet, TextInput, View } from "react-native";
import { GestureDetector, useNativeGesture } from "react-native-gesture-handler";
@@ -156,39 +156,31 @@ function ThreadNavigationSidebarPane(
const pendingTasks = usePendingNewTasks();
const queuedThreadKeys = useQueuedThreadKeys();
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
- const environments = useMemo(
- () =>
- Object.values(savedConnectionsById)
- .map((connection) => ({
- environmentId: connection.environmentId,
- label: connection.environmentLabel,
- }))
- .sort((left, right) => left.label.localeCompare(right.label)),
- [savedConnectionsById],
- );
- const availableEnvironmentIds = useMemo(
- () => new Set(environments.map((environment) => environment.environmentId)),
- [environments],
+ const environments = Object.values(savedConnectionsById)
+ .map((connection) => ({
+ environmentId: connection.environmentId,
+ label: connection.environmentLabel,
+ }))
+ .sort((left, right) => left.label.localeCompare(right.label));
+ const availableEnvironmentIds = new Set(
+ environments.map((environment) => environment.environmentId),
);
const { options, setSelectedEnvironmentId, setSelectedProjectKey } =
useHomeListOptions(availableEnvironmentIds);
- const searchEnvironmentIds = useMemo(
- () =>
- options.selectedEnvironmentId === null
- ? workspaceEnvironments
- .filter((environment) => environment.connectionState === "connected")
- .map((environment) => environment.environmentId)
- : workspaceEnvironments.some(
- (environment) =>
- environment.environmentId === options.selectedEnvironmentId &&
- environment.connectionState === "connected",
- )
- ? [options.selectedEnvironmentId]
- : [],
- [options.selectedEnvironmentId, workspaceEnvironments],
- );
+ const searchEnvironmentIds =
+ options.selectedEnvironmentId === null
+ ? workspaceEnvironments
+ .filter((environment) => environment.connectionState === "connected")
+ .map((environment) => environment.environmentId)
+ : workspaceEnvironments.some(
+ (environment) =>
+ environment.environmentId === options.selectedEnvironmentId &&
+ environment.connectionState === "connected",
+ )
+ ? [options.selectedEnvironmentId]
+ : [];
const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery);
- const threadSearchMatchByKey = useMemo(() => {
+ const threadSearchMatchByKey = (() => {
const matches = new Map<string, EnvironmentThreadSearchMatch>();
for (const match of threadSearch.matches) {
if (match.source === "user" || match.source === "assistant") {
@@ -196,11 +188,8 @@ function ThreadNavigationSidebarPane(
}
}
return matches;
- }, [threadSearch.matches]);
- const matchedThreadKeys = useMemo(
- () => new Set(threadSearch.matches.map(threadSearchMatchKey)),
- [threadSearch.matches],
- );
+ })();
+ const matchedThreadKeys = new Set(threadSearch.matches.map(threadSearchMatchKey));
const projectScopeKey = options.selectedProjectKey;
const resolvedProjectKey = resolveScratchProjectScopeKey(projectScopeKey, projects, {
sidebarProjectGroupingMode: options.projectGroupingMode,
@@ -211,75 +200,53 @@ function ThreadNavigationSidebarPane(
setSelectedProjectKey(resolvedProjectKey);
}
}, [projectScopeKey, resolvedProjectKey, setSelectedProjectKey]);
- const projectScopes = useMemo(
- () =>
- buildHomeProjectScopes({
- projects,
- environmentId: options.selectedEnvironmentId,
- projectGroupingMode: options.projectGroupingMode,
- }),
- [options.projectGroupingMode, options.selectedEnvironmentId, projects],
- );
- const projectFilterOptions = useMemo(
- () =>
- projectScopes.map((scope) => ({
- key: scope.key,
- label: scope.title,
- })),
- [projectScopes],
- );
- const projectTitleByProjectKey = useMemo(
- () =>
- new Map(
- projectScopes.flatMap((scope) =>
- scope.projectRefs.map(
- (projectRef) =>
- [
- scopedProjectKey(projectRef.environmentId, projectRef.projectId),
- scope.title,
- ] as const,
- ),
- ),
+ const projectScopes = buildHomeProjectScopes({
+ projects,
+ environmentId: options.selectedEnvironmentId,
+ projectGroupingMode: options.projectGroupingMode,
+ });
+ const projectFilterOptions = projectScopes.map((scope) => ({
+ key: scope.key,
+ label: scope.title,
+ }));
+ const projectTitleByProjectKey = new Map(
+ projectScopes.flatMap((scope) =>
+ scope.projectRefs.map(
+ (projectRef) =>
+ [scopedProjectKey(projectRef.environmentId, projectRef.projectId), scope.title] as const,
),
- [projectScopes],
- );
- const selectedProjectScope = useMemo(
- () => projectScopes.find((scope) => scope.key === resolvedProjectKey) ?? null,
- [projectScopes, resolvedProjectKey],
+ ),
);
+ const selectedProjectScope =
+ projectScopes.find((scope) => scope.key === resolvedProjectKey) ?? null;
const selectedProjectKey = selectedProjectScope?.key ?? null;
- const selectedProjectRefs = useMemo(
- () =>
- selectedProjectScope === null
- ? null
- : new Set(
- selectedProjectScope.projectRefs.map((projectRef) =>
- scopedProjectKey(projectRef.environmentId, projectRef.projectId),
- ),
+ const selectedProjectRefs =
+ selectedProjectScope === null
+ ? null
+ : new Set(
+ selectedProjectScope.projectRefs.map((projectRef) =>
+ scopedProjectKey(projectRef.environmentId, projectRef.projectId),
),
- [selectedProjectScope],
- );
- const projectByKey = useMemo(() => {
+ );
+ const projectByKey = (() => {
const map = new Map<string, EnvironmentProject>();
for (const project of projects) {
map.set(scopedProjectKey(project.environmentId, project.id), project);
}
return map;
- }, [projects]);
+ })();
const [settledVisibleCount, setSettledVisibleCount] = useState(
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
);
const settledResetKey = `${options.selectedEnvironmentId ?? "all"}:${selectedProjectKey ?? "all"}:${props.searchQuery.trim()}`;
- const lastSettledResetKeyRef = useRef(settledResetKey);
- if (lastSettledResetKeyRef.current !== settledResetKey) {
- lastSettledResetKeyRef.current = settledResetKey;
+ const [lastSettledResetKey, setLastSettledResetKey] = useState(settledResetKey);
+ if (lastSettledResetKey !== settledResetKey) {
+ setLastSettledResetKey(settledResetKey);
setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
}
- const showMoreSettled = useCallback(
- () => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
- [],
- );
+ const showMoreSettled = () =>
+ setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT);
const {
loaded: shelfPreferencesLoaded,
settledShelfExpanded,
@@ -290,11 +257,15 @@ function ThreadNavigationSidebarPane(
toggleSnoozedShelf,
toggleWorkingShelf,
} = useThreadListV2ShelfPreferences();
- const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
+ // The list's clock is state: the compiler caches anything computed from it on
+ // its other inputs, so a render-time `new Date()` would stop moving. The minute
+ // interval and the snooze-wake timer below both advance it.
+ const [now, setNow] = useState(() => new Date().toISOString());
+ const nowMinute = now.slice(0, 16);
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
useEffect(() => {
- setNowMinute(new Date().toISOString().slice(0, 16));
- const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
+ setNow(new Date().toISOString());
+ const id = setInterval(() => setNow(new Date().toISOString()), 60_000);
return () => clearInterval(id);
}, []);
const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
@@ -314,7 +285,7 @@ function ThreadNavigationSidebarPane(
// Up/down menu availability for every card, computed once per section per
// rebuild (see computeThreadMoveAvailability): per-thread planner calls made
// list construction quadratic, and this list rebuilds on every minute tick.
- const threadMoveAvailability = useMemo(() => {
+ const threadMoveAvailability = (() => {
const sectionAvailability = (section: "pinned" | "active") =>
computeThreadMoveAvailability({
allThreads: threads,
@@ -326,7 +297,7 @@ function ThreadNavigationSidebarPane(
threads,
section,
pendingOrder,
- now: new Date().toISOString(),
+ now,
settlementEnvironmentIds,
snoozeEnvironmentIds,
queuedThreadKeys,
@@ -336,19 +307,8 @@ function ThreadNavigationSidebarPane(
...sectionAvailability("pinned"),
...(workingShelfEnabled ? [] : sectionAvailability("active")),
]);
- }, [
- workingShelfEnabled,
- pinReorderEnvironmentIds,
- activeReorderEnvironmentIds,
- threads,
- pendingOrder,
- queuedThreadKeys,
- settlementEnvironmentIds,
- snoozeEnvironmentIds,
- nowMinute,
- snoozeWakeTick,
- ]);
- const threadListV2Layout = useMemo(() => {
+ })();
+ const threadListV2Layout = (() => {
threadListInboxReturns.observe(workingShelfEnabled ? threads : null);
return buildThreadListV2Items({
pendingOrder,
@@ -361,7 +321,7 @@ function ThreadNavigationSidebarPane(
snoozeEnvironmentIds,
queuedThreadKeys,
settledLimit: settledVisibleCount,
- now: new Date().toISOString(),
+ now,
workingShelfEnabled,
workingShelfExpanded,
inboxReturnAt: threadListInboxReturns.returnedAt,
@@ -369,38 +329,23 @@ function ThreadNavigationSidebarPane(
settledShelfExpanded,
selectedThreadKey: props.selectedThreadKey ?? null,
});
- }, [
- workingShelfEnabled,
- workingShelfExpanded,
- pendingOrder,
- queuedThreadKeys,
- nowMinute,
- snoozeWakeTick,
- snoozedShelfExpanded,
- settledShelfExpanded,
- props.selectedThreadKey,
- options.selectedEnvironmentId,
- props.searchQuery,
- matchedThreadKeys,
- settledVisibleCount,
- settlementEnvironmentIds,
- snoozeEnvironmentIds,
- threads,
- selectedProjectScope,
- ]);
+ })();
const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
useEffect(() => {
if (nextSnoozeWakeAt === null) return;
const wakeAtMs = Date.parse(nextSnoozeWakeAt);
if (Number.isNaN(wakeAtMs)) return;
const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
- const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
+ const id = setTimeout(() => {
+ setNow(new Date().toISOString());
+ bumpSnoozeWakeTick((tick) => tick + 1);
+ }, delayMs);
return () => clearTimeout(id);
// snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
// unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
// range) the boundary string is identical and the chain would die.
}, [nextSnoozeWakeAt, snoozeWakeTick]);
- const listItems = useMemo<readonly SidebarListItem[]>(() => {
+ const listItems = ((): readonly SidebarListItem[] => {
const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
const v2PendingTasks = pendingTasks.filter(
(pendingTask) =>
@@ -439,95 +384,79 @@ function ThreadNavigationSidebarPane(
});
}
return items;
- }, [
- nowMinute,
- options.selectedEnvironmentId,
- pendingTasks,
- props.searchQuery,
- queuedThreadKeys,
- threadMoveAvailability,
- selectedProjectRefs,
- settledShelfExpanded,
- shelfPreferencesLoaded,
- snoozedShelfExpanded,
- snoozeEnvironmentIds,
- threadListV2Layout,
- workingShelfExpanded,
- ]);
- const listMenuActions = useMemo<MenuAction[]>(
- () => [
- {
- id: "environment",
- title: "Environment",
- subactions: [
+ })();
+ const listMenuActions = [
+ {
+ id: "environment",
+ title: "Environment",
+ subactions: [
+ {
+ id: "environment:all",
+ title: "All environments",
+ subtitle: "Show threads from every environment",
+ state: options.selectedEnvironmentId === null ? "on" : "off",
+ },
+ ...environments.map((environment) => ({
+ id: `environment:${environment.environmentId}`,
+ title: environment.label,
+ state:
+ options.selectedEnvironmentId === environment.environmentId
+ ? ("on" as const)
+ : ("off" as const),
+ })),
+ ],
+ },
+ ...(projectFilterOptions.length === 0
+ ? []
+ : ([
{
- id: "environment:all",
- title: "All environments",
- subtitle: "Show threads from every environment",
- state: options.selectedEnvironmentId === null ? "on" : "off",
+ id: "project",
+ title: "Project",
+ subactions: [
+ {
+ id: "project:all",
+ title: "All projects",
+ subtitle: "Show threads from every project",
+ state: selectedProjectKey === null ? "on" : "off",
+ },
+ ...projectFilterOptions.map((project) => ({
+ id: `project:${project.key}`,
+ title: project.label,
+ state: selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
+ })),
+ ],
},
- ...environments.map((environment) => ({
- id: `environment:${environment.environmentId}`,
- title: environment.label,
- state:
- options.selectedEnvironmentId === environment.environmentId
- ? ("on" as const)
- : ("off" as const),
- })),
- ],
- },
- ...(projectFilterOptions.length === 0
- ? []
- : ([
- {
- id: "project",
- title: "Project",
- subactions: [
- {
- id: "project:all",
- title: "All projects",
- subtitle: "Show threads from every project",
- state: selectedProjectKey === null ? "on" : "off",
- },
- ...projectFilterOptions.map((project) => ({
- id: `project:${project.key}`,
- title: project.label,
- state: selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
- })),
- ],
- },
- ] satisfies MenuAction[])),
- ],
- [environments, options, projectFilterOptions, selectedProjectKey],
- );
- const handleListMenuAction = useCallback(
- ({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
- const event = nativeEvent.event;
- if (event === "environment:all") {
- setSelectedEnvironmentId(null);
- return;
- }
- if (event.startsWith("environment:")) {
- const environment = environments.find(
- (candidate) => String(candidate.environmentId) === event.slice("environment:".length),
- );
- if (environment) setSelectedEnvironmentId(environment.environmentId);
- return;
- }
- if (event === "project:all") {
- setSelectedProjectKey(null);
- return;
- }
- if (event.startsWith("project:")) {
- const projectKey = event.slice("project:".length);
- if (projectFilterOptions.some((project) => project.key === projectKey)) {
- setSelectedProjectKey(projectKey);
- }
- return;
+ ] satisfies MenuAction[])),
+ ] satisfies MenuAction[];
+ const handleListMenuAction = ({
+ nativeEvent,
+ }: {
+ readonly nativeEvent: { readonly event: string };
+ }) => {
+ const event = nativeEvent.event;
+ if (event === "environment:all") {
+ setSelectedEnvironmentId(null);
+ return;
+ }
+ if (event.startsWith("environment:")) {
+ const environment = environments.find(
+ (candidate) => String(candidate.environmentId) === event.slice("environment:".length),
+ );
+ if (environment) setSelectedEnvironmentId(environment.environmentId);
+ return;
+ }
+ if (event === "project:all") {
+ setSelectedProjectKey(null);
+ return;
+ }
+ if (event.startsWith("project:")) {
+ const projectKey = event.slice("project:".length);
+ if (projectFilterOptions.some((project) => project.key === projectKey)) {
+ setSelectedProjectKey(projectKey);
}
- },
- [environments, projectFilterOptions, setSelectedEnvironmentId, setSelectedProjectKey],
- );
+ return;
+ }
+ };
const [measuredHeaderHeight, setMeasuredHeaderHeight] = useState<number | null>(null);
const { height, paddingTop, paddingBottom } = useToolbarLayout();
@@ -540,38 +469,35 @@ function ThreadNavigationSidebarPane(
? paddingTop + height + paddingBottom
: insets.top + SIDEBAR_STICKY_HEADER_HEIGHT);
const topListInset = stickyHeaderHeight + 6;
- const handleStickyHeaderLayout = useCallback((event: LayoutChangeEvent) => {
+ const handleStickyHeaderLayout = (event: LayoutChangeEvent) => {
const nextHeight = event.nativeEvent.layout.height;
setMeasuredHeaderHeight((current) => (current === nextHeight ? current : nextHeight));
- }, []);
- const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
+ };
+ const handleSwipeableWillOpen = (methods: SwipeableMethods) => {
if (openSwipeableRef.current !== methods) {
openSwipeableRef.current?.close();
openSwipeableRef.current = methods;
}
- }, []);
- const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
+ };
+ const handleSwipeableClose = (methods: SwipeableMethods) => {
if (openSwipeableRef.current === methods) {
openSwipeableRef.current = null;
}
- }, []);
- const handleSelectThread = useCallback(
- (thread: EnvironmentThreadShell) => {
- props.onSelectThread(thread);
- openSwipeableRef.current?.close();
- },
- [props.onSelectThread],
- );
- const handleOpenThreadPullRequests = useCallback(
- (thread: EnvironmentThreadShell, pr: ThreadPrPresentation) => {
- props.onOpenThreadPullRequests(thread, pr);
- openSwipeableRef.current?.close();
- },
- [props.onOpenThreadPullRequests],
- );
- const handleScrollBeginDrag = useCallback(() => {
+ };
+ const handleSelectThread = (thread: EnvironmentThreadShell) => {
+ props.onSelectThread(thread);
openSwipeableRef.current?.close();
- }, []);
+ };
+ const handleOpenThreadPullRequests = (
+ thread: EnvironmentThreadShell,
+ pr: ThreadPrPresentation,
+ ) => {
+ props.onOpenThreadPullRequests(thread, pr);
+ openSwipeableRef.current?.close();
+ };
+ const handleScrollBeginDrag = () => {
+ openSwipeableRef.current?.close();
+ };
const onFabScroll = useFabScroll();
const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
onScroll: onFabScroll,
@@ -582,40 +508,26 @@ function ThreadNavigationSidebarPane(
// blank favicon and fallback title it was first rendered with. The minute
// clock deliberately stays out: its per-row text lives on the items, so a
// tick only re-renders rows whose displayed text actually moved.
- const listExtraData = useMemo(
- () => ({
- selectedThreadKey: props.selectedThreadKey ?? "",
- projectByKey,
- projectTitleByProjectKey,
- savedConnectionsById,
- listEnvironments,
- threadSearchMatchByKey,
- workingShelfEnabled,
- }),
- [
- props.selectedThreadKey,
- projectByKey,
- projectTitleByProjectKey,
- savedConnectionsById,
- listEnvironments,
- threadSearchMatchByKey,
- workingShelfEnabled,
- ],
- );
+ const listExtraData = {
+ selectedThreadKey: props.selectedThreadKey ?? "",
+ projectByKey,
+ projectTitleByProjectKey,
+ savedConnectionsById,
+ listEnvironments,
+ threadSearchMatchByKey,
+ workingShelfEnabled,
+ };
useThreadJumpShortcuts(listItems, handleSelectThread);
- const sidebarItemsAreEqual = useCallback(
- (previous: SidebarListItem, item: SidebarListItem): boolean => {
- if (isThreadListV2ListItem(previous) && isThreadListV2ListItem(item)) {
- return threadListV2ListItemsAreEqual(previous, item);
- }
- if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
- return previous.hiddenCount === item.hiddenCount;
- }
- return false;
- },
- [],
- );
- const focusSearch = useCallback(() => {
+ const sidebarItemsAreEqual = (previous: SidebarListItem, item: SidebarListItem): boolean => {
+ if (isThreadListV2ListItem(previous) && isThreadListV2ListItem(item)) {
+ return threadListV2ListItemsAreEqual(previous, item);
+ }
+ if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
+ return previous.hiddenCount === item.hiddenCount;
+ }
+ return false;
+ };
+ const focusSearch = () => {
if (Platform.OS === "android") return false;
const focus = () => {
if (props.nativeChrome) {
@@ -631,220 +543,156 @@ function ThreadNavigationSidebarPane(
focus();
}
return true;
- }, [props.nativeChrome, props.onRequestVisibility, props.visible]);
+ };
useHardwareKeyboardCommand("focusSearch", focusSearch);
- const renderListItem = useCallback(
- ({ item }: { readonly item: SidebarListItem }) => {
- switch (item.type) {
- case "v2-pending": {
- const pendingScopeKey = scopedProjectKey(
- item.pendingTask.environmentId,
- item.pendingTask.projectId,
- );
- return (
- <ThreadListV2PendingRow
- pendingTask={item.pendingTask}
- project={projectByKey.get(pendingScopeKey) ?? null}
- projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}
- environmentLabel={
- Object.keys(savedConnectionsById).length > 1
- ? (savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? null)
- : null
- }
- environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
- pane="sidebar"
- showPendingDivider={item.showPendingDivider}
- onSelectPendingTask={openPendingTask}
- onDeletePendingTask={confirmDeletePendingTask}
- />
- );
- }
- case "v2-thread": {
- const thread = item.item.thread;
- const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId);
- return (
- <ThreadListV2Row
- onNewThreadOnBranch={props.onNewThreadOnBranch}
- thread={thread}
- variant={item.item.variant}
- hasQueuedMessages={item.hasQueuedMessages}
- snoozed={item.item.snoozed}
- pinned={item.item.pinned}
- snoozePresetMinute={item.snoozePresetMinute ?? ""}
- snoozeWakeLabelText={item.snoozeWakeLabelText}
- timeLabel={item.timeLabel}
- project={projectByKey.get(scopeKey) ?? null}
- projectTitle={projectTitleByProjectKey.get(scopeKey)}
- providerInstance={resolveProviderInstance(thread)}
- providers={providersByEnvironmentId.get(thread.environmentId)}
- environmentLabel={
- Object.keys(savedConnectionsById).length > 1
- ? (savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
- : null
- }
- environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
- searchMatch={threadSearchMatchByKey.get(
- threadSearchMatchKey({
- environmentId: thread.environmentId,
- threadId: thread.id,
- }),
- )}
- searchQuery={props.searchQuery}
- pane="sidebar"
- selected={
- scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
- }
- fullSwipeWidth={props.width - 20}
- onSelectThread={handleSelectThread}
- onOpenThreadPullRequests={handleOpenThreadPullRequests}
- onDeleteThread={confirmDeleteThread}
- onArchiveThread={archiveThread}
- onRenameThread={renameThread}
- onRegenerateThreadTitle={regenerateThreadTitle}
- titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
- settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
- onSettleThread={settleThread}
- snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
- pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
- autoSettleOptOutSupported={autoSettleOptOutEnvironmentIds.has(thread.environmentId)}
- reorderSupported={
- item.item.pinned
- ? pinReorderEnvironmentIds.has(thread.environmentId)
- : !workingShelfEnabled && activeReorderEnvironmentIds.has(thread.environmentId)
- }
- canMoveUp={item.canMoveUp}
- canMoveDown={item.canMoveDown}
- onSnoozeThread={snoozeThread}
- onUnsnoozeThread={unsnoozeThread}
- onUnsettleThread={unsettleThread}
- onPinThread={pinThread}
- onUnpinThread={unpinThread}
- onSetThreadAutoSettle={setThreadAutoSettle}
- onMoveThread={moveThread}
- onSwipeableClose={handleSwipeableClose}
- onSwipeableWillOpen={handleSwipeableWillOpen}
- simultaneousSwipeGesture={sidebarScrollGesture}
- />
- );
- }
- case "v2-working-shelf":
- return (
- <ThreadListV2WorkingShelfHeader
- count={item.count}
- disabled={item.disabled}
- expanded={item.expanded}
- onToggle={toggleWorkingShelf}
- pane="sidebar"
- />
- );
- case "v2-snoozed-shelf":
- return (
- <ThreadListV2SnoozedShelfHeader
- count={item.count}
- disabled={item.disabled}
- expanded={item.expanded}
- onToggle={toggleSnoozedShelf}
- pane="sidebar"
- />
- );
- case "v2-settled-shelf":
- return (
- <ThreadListV2SettledShelfHeader
- count={item.count}
- disabled={item.disabled}
- expanded={item.expanded}
- onToggle={toggleSettledShelf}
- pane="sidebar"
- />
- );
- case "v2-show-more":
- return (
- <ThreadListV2ShowMoreRow
- pane="sidebar"
- hiddenCount={item.hiddenCount}
- onPress={showMoreSettled}
- />
- );
+ const renderListItem = ({ item }: { readonly item: SidebarListItem }) => {
+ switch (item.type) {
+ case "v2-pending": {
+ const pendingScopeKey = scopedProjectKey(
+ item.pendingTask.environmentId,
+ item.pendingTask.projectId,
+ );
+ return (
+ <ThreadListV2PendingRow
+ pendingTask={item.pendingTask}
+ project={projectByKey.get(pendingScopeKey) ?? null}
+ projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}
+ environmentLabel={
+ Object.keys(savedConnectionsById).length > 1
+ ? (savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? null)
+ : null
+ }
+ environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
+ pane="sidebar"
+ showPendingDivider={item.showPendingDivider}
+ onSelectPendingTask={openPendingTask}
+ onDeletePendingTask={confirmDeletePendingTask}
+ />
+ );
}
- },
- [
- archiveThread,
- activeReorderEnvironmentIds,
- confirmDeletePendingTask,
- confirmDeleteThread,
- handleOpenThreadPullRequests,
- handleSelectThread,
- handleSwipeableClose,
- handleSwipeableWillOpen,
- machineByEnvironmentId,
- moveThread,
- openPendingTask,
- pinReorderEnvironmentIds,
- pinThread,
- pinningEnvironmentIds,
- autoSettleOptOutEnvironmentIds,
- autoSettleOptOutEnvironmentIds,
- setThreadAutoSettle,
- projectByKey,
- projectTitleByProjectKey,
- regenerateThreadTitle,
- renameThread,
- props.onNewThreadOnBranch,
- props.searchQuery,
- props.selectedThreadKey,
- props.width,
- savedConnectionsById,
- resolveProviderInstance,
- providersByEnvironmentId,
- threadSearchMatchByKey,
- titleRegenerationEnvironmentIds,
- settleThread,
- settlementEnvironmentIds,
- showMoreSettled,
- sidebarScrollGesture,
- snoozeEnvironmentIds,
- snoozeThread,
- toggleSettledShelf,
- toggleSnoozedShelf,
- toggleWorkingShelf,
- unpinThread,
- unsettleThread,
- unsnoozeThread,
- workingShelfEnabled,
- ],
- );
+ case "v2-thread": {
+ const thread = item.item.thread;
+ const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId);
+ return (
+ <ThreadListV2Row
+ onNewThreadOnBranch={props.onNewThreadOnBranch}
+ thread={thread}
+ variant={item.item.variant}
+ hasQueuedMessages={item.hasQueuedMessages}
+ snoozed={item.item.snoozed}
+ pinned={item.item.pinned}
+ snoozePresetMinute={item.snoozePresetMinute ?? ""}
+ snoozeWakeLabelText={item.snoozeWakeLabelText}
+ timeLabel={item.timeLabel}
+ project={projectByKey.get(scopeKey) ?? null}
+ projectTitle={projectTitleByProjectKey.get(scopeKey)}
+ providerInstance={resolveProviderInstance(thread)}
+ providers={providersByEnvironmentId.get(thread.environmentId)}
+ environmentLabel={
+ Object.keys(savedConnectionsById).length > 1
+ ? (savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
+ : null
+ }
+ environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
+ searchMatch={threadSearchMatchByKey.get(
+ threadSearchMatchKey({
+ environmentId: thread.environmentId,
+ threadId: thread.id,
+ }),
+ )}
+ searchQuery={props.searchQuery}
+ pane="sidebar"
+ selected={scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey}
+ fullSwipeWidth={props.width - 20}
+ onSelectThread={handleSelectThread}
+ onOpenThreadPullRequests={handleOpenThreadPullRequests}
+ onDeleteThread={confirmDeleteThread}
+ onArchiveThread={archiveThread}
+ onRenameThread={renameThread}
+ onRegenerateThreadTitle={regenerateThreadTitle}
+ titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
+ settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
+ onSettleThread={settleThread}
+ snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
+ pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
+ autoSettleOptOutSupported={autoSettleOptOutEnvironmentIds.has(thread.environmentId)}
+ reorderSupported={
+ item.item.pinned
+ ? pinReorderEnvironmentIds.has(thread.environmentId)
+ : !workingShelfEnabled && activeReorderEnvironmentIds.has(thread.environmentId)
+ }
+ canMoveUp={item.canMoveUp}
+ canMoveDown={item.canMoveDown}
+ onSnoozeThread={snoozeThread}
+ onUnsnoozeThread={unsnoozeThread}
+ onUnsettleThread={unsettleThread}
+ onPinThread={pinThread}
+ onUnpinThread={unpinThread}
+ onSetThreadAutoSettle={setThreadAutoSettle}
+ onMoveThread={moveThread}
+ onSwipeableClose={handleSwipeableClose}
+ onSwipeableWillOpen={handleSwipeableWillOpen}
+ simultaneousSwipeGesture={sidebarScrollGesture}
+ />
+ );
+ }
+ case "v2-working-shelf":
+ return (
+ <ThreadListV2WorkingShelfHeader
+ count={item.count}
+ disabled={item.disabled}
+ expanded={item.expanded}
+ onToggle={toggleWorkingShelf}
+ pane="sidebar"
+ />
+ );
+ case "v2-snoozed-shelf":
+ return (
+ <ThreadListV2SnoozedShelfHeader
+ count={item.count}
+ disabled={item.disabled}
+ expanded={item.expanded}
+ onToggle={toggleSnoozedShelf}
+ pane="sidebar"
+ />
+ );
+ case "v2-settled-shelf":
+ return (
+ <ThreadListV2SettledShelfHeader
+ count={item.count}
+ disabled={item.disabled}
+ expanded={item.expanded}
+ onToggle={toggleSettledShelf}
+ pane="sidebar"
+ />
+ );
+ case "v2-show-more":
+ return (
+ <ThreadListV2ShowMoreRow
+ pane="sidebar"
+ hiddenCount={item.hiddenCount}
+ onPress={showMoreSettled}
+ />
+ );
+ }
+ };
const filterCustomized = options.selectedEnvironmentId !== null || selectedProjectKey !== null;
const filterIcon = filterCustomized
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle";
- const filterMenu = useMemo(
- () =>
- buildHomeListFilterMenu({
- environments,
- projects: projectFilterOptions,
- selectedEnvironmentId: options.selectedEnvironmentId,
- selectedProjectKey,
- onEnvironmentChange: setSelectedEnvironmentId,
- onProjectChange: setSelectedProjectKey,
- }),
- [
- environments,
- options,
- projectFilterOptions,
- selectedProjectKey,
- setSelectedEnvironmentId,
- setSelectedProjectKey,
- ],
- );
- const nativeHeaderItems = useMemo(
- () =>
- createSidebarHeaderItems({
- filterIcon,
- filterMenu,
- onOpenSettings: props.onOpenSettings,
- }),
- [filterIcon, filterMenu, props.onOpenSettings],
- );
+ const filterMenu = buildHomeListFilterMenu({
+ environments,
+ projects: projectFilterOptions,
+ selectedEnvironmentId: options.selectedEnvironmentId,
+ selectedProjectKey,
+ onEnvironmentChange: setSelectedEnvironmentId,
+ onProjectChange: setSelectedProjectKey,
+ });
+ const nativeHeaderItems = createSidebarHeaderItems({
+ filterIcon,
+ filterMenu,
+ onOpenSettings: props.onOpenSettings,
+ });
const listEmpty = (
<Text
className={
diff --git a/apps/mobile/src/features/threads/use-thread-list-v2-shelf-preferences.ts b/apps/mobile/src/features/threads/use-thread-list-v2-shelf-preferences.ts
index d8209074bc3..e0ca1ea3c4e 100644
--- a/apps/mobile/src/features/threads/use-thread-list-v2-shelf-preferences.ts
+++ b/apps/mobile/src/features/threads/use-thread-list-v2-shelf-preferences.ts
@@ -1,13 +1,8 @@
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/reactivity";
-import { useCallback, useRef } from "react";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
-/**
- * Refs advance before persistence starts so consecutive presses always toggle the latest value,
- * even if React has not rendered the optimistic patch yet.
- */
export function useThreadListV2ShelfPreferences() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
@@ -19,31 +14,33 @@ export function useThreadListV2ShelfPreferences() {
const workingShelfEnabled = loaded && preferencesResult.value.workingShelfEnabled === true;
const workingShelfExpanded =
loaded && preferencesResult.value.threadListWorkingShelfExpanded === true;
- const snoozedShelfExpandedRef = useRef(snoozedShelfExpanded);
- const settledShelfExpandedRef = useRef(settledShelfExpanded);
- const workingShelfExpandedRef = useRef(workingShelfExpanded);
- snoozedShelfExpandedRef.current = snoozedShelfExpanded;
- settledShelfExpandedRef.current = settledShelfExpanded;
- workingShelfExpandedRef.current = workingShelfExpanded;
- const toggleSnoozedShelf = useCallback(() => {
+ // A transform reads the optimistic value, so two presses before the next
+ // render still toggle twice instead of writing the same value.
+ const toggleSnoozedShelf = () => {
if (!loaded) return;
- const expanded = !snoozedShelfExpandedRef.current;
- snoozedShelfExpandedRef.current = expanded;
- savePreferences({ threadListSnoozedShelfExpanded: expanded });
- }, [loaded, savePreferences]);
- const toggleSettledShelf = useCallback(() => {
+ savePreferences({
+ transform: (current) => ({
+ threadListSnoozedShelfExpanded: current.threadListSnoozedShelfExpanded !== true,
+ }),
+ });
+ };
+ const toggleSettledShelf = () => {
if (!loaded) return;
- const expanded = !settledShelfExpandedRef.current;
- settledShelfExpandedRef.current = expanded;
- savePreferences({ threadListSettledShelfExpanded: expanded });
- }, [loaded, savePreferences]);
- const toggleWorkingShelf = useCallback(() => {
+ savePreferences({
+ transform: (current) => ({
+ threadListSettledShelfExpanded: current.threadListSettledShelfExpanded !== true,
+ }),
+ });
+ };
+ const toggleWorkingShelf = () => {
if (!loaded) return;
- const expanded = !workingShelfExpandedRef.current;
- workingShelfExpandedRef.current = expanded;
- savePreferences({ threadListWorkingShelfExpanded: expanded });
- }, [loaded, savePreferences]);
+ savePreferences({
+ transform: (current) => ({
+ threadListWorkingShelfExpanded: current.threadListWorkingShelfExpanded !== true,
+ }),
+ });
+ };
return {
loaded,
diff --git a/apps/mobile/src/reactCompilerCoverage.test.ts b/apps/mobile/src/reactCompilerCoverage.test.ts
index 92cec59f18c..cfe6008b80d 100644
--- a/apps/mobile/src/reactCompilerCoverage.test.ts
+++ b/apps/mobile/src/reactCompilerCoverage.test.ts
@@ -24,10 +24,7 @@ const KNOWN_BAILOUTS: Record<string, string> = {
"src/features/terminal/ThreadTerminalRouteScreen.tsx": "ref read during render",
"src/features/threads/PendingUserInputCard.tsx": "mutates a frozen value",
"src/features/threads/ThreadArrangementSheet.tsx": "ref read during render",
- "src/features/threads/ThreadDetailScreen.tsx": "mutates a frozen value",
"src/features/threads/ThreadFeed.tsx": "ref read during render, throw inside try, try/finally",
- "src/features/threads/ThreadNavigationSidebar.tsx": "ref read during render",
- "src/features/threads/use-thread-list-v2-shelf-preferences.ts": "ref read during render",
"src/features/voice-input/VoiceInputProvider.tsx": "ref read during render",
"src/features/voice-input/useVoiceInputController.ts": "ref read during render",
"src/native/StackHeader.tsx": "ref read during render",