@devries-cameron20 / t3code-1 / commits / ad0a7d8667
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 18, 2026 at 14:33 UTC ad0a7d8667aa6895bca7da7c1d2461c5bbafd1cb
4 files changed +480 -689
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+132 -183
@@ -1,3 +1,5 @@
1 +import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2 +import { AsyncResult } from "effect/reactivity";
3 import * as Dialog from "../../components/ui/Dialog";
4 import { useAtomValue } from "@effect/atom-react";
5 import { useChildThreadInputs, useThreadReportedModelSelection } from "../../state/entities";
@@ -52,16 +54,7 @@ import type { QueuedRunEdit } from "../../state/queued-run-edit";
54 import type { FollowUpBehavior } from "../../lib/followUpBehavior";
55 import type { ActiveTurnComposerAction } from "@t3tools/client-runtime/state/composer-dispatch";
56 import * as Haptics from "expo-haptics";
55 -import {
56 - memo,
57 - useCallback,
58 - useContext,
59 - useEffect,
60 - useLayoutEffect,
61 - useMemo,
62 - useRef,
63 - useState,
64 -} from "react";
57 +import { useContext, useEffect, useLayoutEffect, useRef, useState } from "react";
58 import {
59 AppState,
60 Keyboard,
@@ -326,7 +319,7 @@ const USER_INPUT_TOGGLE_TIMING = {
319 easing: Easing.out(Easing.cubic),
320 };
321
329 -export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
322 +export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetailScreenProps) {
323 const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();
324 const navigation = useNavigation();
325 const { session: voiceInputSession } = useGlobalVoiceInput();
@@ -334,33 +327,27 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
327 const deviceState = useEnvironmentQuery(
328 deviceEnvironment.state({ environmentId: props.environmentId, input: {} }),
329 );
337 - const devicePreviews = useMemo(
338 - () => threadDevicePreviews(deviceState.data, props.selectedThread.id),
339 - [deviceState.data, props.selectedThread.id],
340 - );
341 - const openDevicePreview = useCallback(() => {
330 + const devicePreviews = threadDevicePreviews(deviceState.data, props.selectedThread.id);
331 + const openDevicePreview = () => {
332 Keyboard.dismiss();
333 navigation.navigate("ThreadDevicePreview", {
334 environmentId: props.environmentId,
335 threadId: props.selectedThread.id,
336 });
347 - }, [navigation, props.environmentId, props.selectedThread.id]);
337 + };
338 const browserTabs = useThreadServerBrowserTabs({
339 environmentId: props.environmentId,
340 threadId: props.selectedThread.id,
341 enabled: props.serverConfig?.environment.capabilities.serverBrowser === true,
342 });
353 - const openBrowserPreview = useCallback(
354 - (tabId?: string) => {
355 - Keyboard.dismiss();
356 - navigation.navigate("ThreadBrowserPreview", {
357 - environmentId: props.environmentId,
358 - threadId: props.selectedThread.id,
359 - ...(tabId === undefined ? {} : { tabId }),
360 - });
361 - },
362 - [navigation, props.environmentId, props.selectedThread.id],
363 - );
343 + const openBrowserPreview = (tabId?: string) => {
344 + Keyboard.dismiss();
345 + navigation.navigate("ThreadBrowserPreview", {
346 + environmentId: props.environmentId,
347 + threadId: props.selectedThread.id,
348 + ...(tabId === undefined ? {} : { tabId }),
349 + });
350 + };
351 const insets = useSafeAreaInsets();
352 const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
353 const liveKeyboardHeight = useKeyboardState((state) => state.height);
@@ -389,12 +376,12 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
376 useEffect(() => {
377 setKeyboardStateSuspect(false);
378 }, [isKeyboardVisible, liveKeyboardHeight]);
392 - const handleOwnedInputFocusChange = useCallback((focused: boolean) => {
379 + const handleOwnedInputFocusChange = (focused: boolean) => {
380 ownedInputFocusedRef.current = focused;
381 if (focused) {
382 setKeyboardStateSuspect(false);
383 }
397 - }, []);
384 + };
385 const windowHeight = useWindowDimensions().height;
386 const navigationHeaderHeight = useContext(HeaderHeightContext) ?? insets.top + 44;
387 const [screenMetrics, setScreenMetrics] = useState<NativeLayoutMetrics | null>(null);
@@ -419,8 +406,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
406 const frame = requestAnimationFrame(() => composerEditorRef.current?.focus());
407 return () => cancelAnimationFrame(frame);
408 }, [editingRunId]);
422 - const draftMessageRef = useRef(props.draftMessage);
423 - draftMessageRef.current = props.draftMessage;
409 const composerOverlayRef = useRef<ViewInstance>(null);
410 const listRef = useRef<LegendListRef>(null);
411 const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
@@ -428,13 +413,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
413 const lastScrolledSubmittedMessageIdRef = useRef<MessageId | null>(null);
414 const [composerExpanded, setComposerExpanded] = useState(false);
415 const [composerFocused, setComposerFocused] = useState(false);
431 - const handleComposerFocusChange = useCallback(
432 - (focused: boolean) => {
433 - setComposerFocused(focused);
434 - handleOwnedInputFocusChange(focused);
435 - },
436 - [handleOwnedInputFocusChange],
437 - );
416 + const handleComposerFocusChange = (focused: boolean) => {
417 + setComposerFocused(focused);
418 + handleOwnedInputFocusChange(focused);
419 + };
420 const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
421 const [submittedMessageId, setSubmittedMessageId] = useState<MessageId | null>(null);
422 const [endFollowEnabled, setEndFollowEnabled] = useState(true);
@@ -579,46 +561,32 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
561 if (usageLimitsPanel !== null && usageLimitsPanel.key !== usageLimitsKey) {
562 setUsageLimitsPanel(null);
563 }
582 - const usageLimitsReport = useMemo(
583 - () =>
584 - usageLimitsPanel !== null && usageLimitsPanel.key === usageLimitsKey
585 - ? collectProviderUsageLimits(
586 - props.selectedThread.modelSelection.instanceId,
587 - props.serverConfig?.providers ?? [],
588 - props.serverConfig?.usageLimitSources ?? [],
589 - usageLimitsPanel.now,
590 - )
591 - : null,
592 - [
593 - props.selectedThread.modelSelection.instanceId,
594 - props.serverConfig,
595 - usageLimitsKey,
596 - usageLimitsPanel,
597 - ],
598 - );
599 - const showUsageLimits = useCallback(
600 - (report: UsageLimitsReport | null) =>
601 - setUsageLimitsPanel(
602 - report === null
603 - ? null
604 - : {
605 - key: usageLimitsKey,
606 - threadKey: selectedThreadKey,
607 - now: Date.parse(report.createdAt),
608 - },
609 - ),
610 - [selectedThreadKey, usageLimitsKey],
611 - );
612 - const dismissUsageLimits = useCallback(() => setUsageLimitsPanel(null), []);
564 + const usageLimitsReport =
565 + usageLimitsPanel !== null && usageLimitsPanel.key === usageLimitsKey
566 + ? collectProviderUsageLimits(
567 + props.selectedThread.modelSelection.instanceId,
568 + props.serverConfig?.providers ?? [],
569 + props.serverConfig?.usageLimitSources ?? [],
570 + usageLimitsPanel.now,
571 + )
572 + : null;
573 + const showUsageLimits = (report: UsageLimitsReport | null) =>
574 + setUsageLimitsPanel(
575 + report === null
576 + ? null
577 + : {
578 + key: usageLimitsKey,
579 + threadKey: selectedThreadKey,
580 + now: Date.parse(report.createdAt),
581 + },
582 + );
583 + const dismissUsageLimits = () => setUsageLimitsPanel(null);
584 // A send may resolve after navigating away, so only the originating
585 // thread's panel is cleared; a panel opened elsewhere in the meantime stays.
615 - const clearUsageLimitsFor = useCallback(
616 - (threadKey: string) =>
617 - setUsageLimitsPanel((current) =>
618 - current !== null && current.threadKey === threadKey ? null : current,
619 - ),
620 - [],
621 - );
586 + const clearUsageLimitsFor = (threadKey: string) =>
587 + setUsageLimitsPanel((current) =>
588 + current !== null && current.threadKey === threadKey ? null : current,
589 + );
590 const userInputCollapsed =
591 activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
592 // 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
658 [userInputCoverageApplies],
659 );
660 const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
661 + // Repin timers fire after the render that scheduled them, so they read follow
662 + // state from the ref the writers below keep in step with it.
663 const endFollowEnabledRef = useRef(true);
694 - endFollowEnabledRef.current = endFollowEnabled;
664 const overlayRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
665 const previousWorkingControlStateRef = useRef({
666 threadKey: selectedThreadKey,
667 visible: false,
668 });
700 - const scheduleOverlayRepin = useCallback(
701 - (delayMs: number) => {
702 - if (overlayRepinTimerRef.current !== null) {
703 - clearTimeout(overlayRepinTimerRef.current);
669 + const handleEndFollowEnabledChange = (enabled: boolean) => {
670 + endFollowEnabledRef.current = enabled;
671 + setEndFollowEnabled(enabled);
672 + };
673 + const scheduleOverlayRepin = (delayMs: number) => {
674 + if (overlayRepinTimerRef.current !== null) {
675 + clearTimeout(overlayRepinTimerRef.current);
676 + }
677 + overlayRepinTimerRef.current = setTimeout(() => {
678 + overlayRepinTimerRef.current = null;
679 + if (!endFollowEnabledRef.current) {
680 + return;
681 }
705 - overlayRepinTimerRef.current = setTimeout(() => {
706 - overlayRepinTimerRef.current = null;
707 - if (!endFollowEnabledRef.current) {
708 - return;
709 - }
710 - void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
711 - freeze.set(false);
712 - });
713 - }, delayMs);
714 - },
715 - [freeze, scrollMessageToEnd],
716 - );
682 + void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
683 + freeze.set(false);
684 + });
685 + }, delayMs);
686 + };
687 useEffect(
688 () => () => {
689 if (overlayRepinTimerRef.current !== null) {
@@ -739,35 +709,29 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
709 // checks follow state again so a user who scrolled up stays put.
710 scheduleOverlayRepin(230);
711 }, [scheduleOverlayRepin, selectedThreadKey, showFloatingStatus]);
742 - const handleToggleUserInputCollapsed = useCallback(() => {
712 + const handleToggleUserInputCollapsed = () => {
713 if (activeUserInputRequestId === null) {
714 return;
715 }
716 if (userInputCollapsed) {
747 - userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
748 - userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
717 + userInputCardProgress.set(withTiming(1, USER_INPUT_TOGGLE_TIMING));
718 + userInputInsetProgress.set(withTiming(1, USER_INPUT_TOGGLE_TIMING));
719 setCollapsedUserInputRequestId(null);
720 scheduleOverlayRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
721 } else {
722 Keyboard.dismiss();
753 - userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING);
723 + userInputCardProgress.set(withTiming(0, USER_INPUT_TOGGLE_TIMING));
724 // Instant: the sinking card still covers the strip being revealed, and
725 // animating the inset downward is what drifted the short-content end
726 // anchor.
757 - userInputInsetProgress.value = 0;
727 + userInputInsetProgress.set(0);
728 setCollapsedUserInputRequestId(activeUserInputRequestId);
729 scheduleOverlayRepin(60);
730 }
761 - }, [
762 - activeUserInputRequestId,
763 - scheduleOverlayRepin,
764 - userInputCardProgress,
765 - userInputCollapsed,
766 - userInputInsetProgress,
767 - ]);
731 + };
732 useEffect(() => {
769 - userInputCardProgress.value = 1;
770 - userInputInsetProgress.value = 1;
733 + userInputCardProgress.set(1);
734 + userInputInsetProgress.set(1);
735 }, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
736 const showContent = props.showContent ?? true;
737 const layoutVariant = props.layoutVariant ?? "compact";
@@ -806,14 +770,14 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
770 );
771 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
772 useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
809 - const selectedProviderSkills = useMemo(() => {
773 + const selectedProviderSkills = (() => {
774 const provider = props.serverConfig?.providers.find(
775 (candidate) => candidate.instanceId === selectedInstanceId,
776 );
777 return provider
778 ? resolveProviderSkillsForCwd(provider, props.threadCwd ?? props.projectWorkspaceRoot)
779 : [];
816 - }, [props.projectWorkspaceRoot, props.serverConfig, props.threadCwd, selectedInstanceId]);
780 + })();
781
782 useLayoutEffect(() => {
783 selectedThreadKeyRef.current = selectedThreadKey;
@@ -873,6 +837,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
837 setAnchorMessageId(null);
838 setSubmittedMessageId(null);
839 lastScrolledSubmittedMessageIdRef.current = null;
840 + endFollowEnabledRef.current = true;
841 setEndFollowEnabled(true);
842 freeze.set(false);
843 }, [freeze, selectedThreadKey]);
@@ -935,98 +900,82 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
900 selectedThreadKey,
901 ]);
902
938 - const handleSendMessage = useCallback(
939 - async (followUp?: ActiveTurnComposerAction) => {
940 - const targetThreadKey = selectedThreadKey;
941 - const hasUserMessage = selectedThreadFeed.some(
942 - (entry) => entry.type === "message" && entry.message.role === "user",
943 - );
944 - const messageId = await props.onSendMessage(followUp);
945 - if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
946 - return messageId;
947 - }
903 + const handleSendMessage = async (followUp?: ActiveTurnComposerAction) => {
904 + const targetThreadKey = selectedThreadKey;
905 + const hasUserMessage = selectedThreadFeed.some(
906 + (entry) => entry.type === "message" && entry.message.role === "user",
907 + );
908 + const messageId = await props.onSendMessage(followUp);
909 + if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
910 + return messageId;
911 + }
912
949 - clearUsageLimitsFor(targetThreadKey);
913 + clearUsageLimitsFor(targetThreadKey);
914
951 - setSubmittedMessageId(messageId);
952 - setAnchorMessageId(
953 - resolveThreadFeedSubmissionAnchor({
954 - currentAnchorMessageId: anchorMessageId,
955 - submittedMessageId: messageId,
956 - hasStartedTurn: props.selectedThread.latestRun !== null,
957 - hasUserMessage,
958 - queuedMessageCount: props.selectedThreadQueueCount,
959 - }),
960 - );
961 - composerEditorRef.current?.blur();
962 - return messageId;
963 - },
964 - [
965 - anchorMessageId,
966 - clearUsageLimitsFor,
967 - props.onSendMessage,
968 - props.selectedThread.latestRun,
969 - props.selectedThreadQueueCount,
970 - selectedThreadFeed,
971 - selectedThreadKey,
972 - ],
973 - );
915 + setSubmittedMessageId(messageId);
916 + setAnchorMessageId(
917 + resolveThreadFeedSubmissionAnchor({
918 + currentAnchorMessageId: anchorMessageId,
919 + submittedMessageId: messageId,
920 + hasStartedTurn: props.selectedThread.latestRun !== null,
921 + hasUserMessage,
922 + queuedMessageCount: props.selectedThreadQueueCount,
923 + }),
924 + );
925 + composerEditorRef.current?.blur();
926 + return messageId;
927 + };
928
975 - const handleEditPendingMessage = useCallback(async (message: QueuedThreadMessage) => {
976 - try {
977 - if (
978 - (await editPendingThreadMessage(message)) &&
979 - selectedThreadKeyRef.current === scopedThreadKey(message.environmentId, message.threadId)
980 - ) {
981 - composerEditorRef.current?.focus();
982 - }
983 - } catch (error) {
929 + const handleEditPendingMessage = async (message: QueuedThreadMessage) => {
930 + const edited = await settlePromise(() => editPendingThreadMessage(message));
931 + if (AsyncResult.isFailure(edited)) {
932 + const error = squashAtomCommandFailure(edited);
933 Dialog.alert(
934 "Could not edit message",
935 error instanceof Error ? error.message : "Please try again.",
936 );
937 + return;
938 }
989 - }, []);
939 + if (
940 + edited.value &&
941 + selectedThreadKeyRef.current === scopedThreadKey(message.environmentId, message.threadId)
942 + ) {
943 + composerEditorRef.current?.focus();
944 + }
945 + };
946
991 - const collapseComposer = useCallback(() => {
947 + const collapseComposer = () => {
948 composerEditorRef.current?.blur();
993 - }, []);
949 + };
950
995 - const handleUseArtifactTemplate = useCallback(
996 - (template: CodexArtifactTemplate) => {
997 - const currentDraft = draftMessageRef.current;
998 - const nextDraft = appendCodexArtifactTemplateUsePrompt(currentDraft, template);
999 - if (nextDraft !== currentDraft) {
1000 - draftMessageRef.current = nextDraft;
1001 - props.onChangeDraftMessage(nextDraft);
1002 - }
1003 - requestAnimationFrame(() => {
1004 - composerEditorRef.current?.focus();
1005 - composerEditorRef.current?.setSelection({ start: nextDraft.length, end: nextDraft.length });
1006 - });
1007 - },
1008 - [props.onChangeDraftMessage],
1009 - );
951 + const handleUseArtifactTemplate = (template: CodexArtifactTemplate) => {
952 + const nextDraft = appendCodexArtifactTemplateUsePrompt(props.draftMessage, template);
953 + if (nextDraft !== props.draftMessage) props.onChangeDraftMessage(nextDraft);
954 + requestAnimationFrame(() => {
955 + composerEditorRef.current?.focus();
956 + composerEditorRef.current?.setSelection({ start: nextDraft.length, end: nextDraft.length });
957 + });
958 + };
959
1011 - const handleScrollToEnd = useCallback(() => {
960 + const handleScrollToEnd = () => {
961 void Haptics.selectionAsync();
962 void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
963 freeze.set(false);
964 });
1016 - }, [freeze, scrollMessageToEnd]);
965 + };
966
967 const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
968 const { themeAppearance } = useAppearancePreferences();
969 const isDarkMode = themeAppearance === "dark";
970
1022 - const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
971 + const handleFeedTouchStart = (event: GestureResponderEvent) => {
972 feedTouchStartRef.current = {
973 pageX: event.nativeEvent.pageX,
974 pageY: event.nativeEvent.pageY,
975 };
1027 - }, []);
976 + };
977
1029 - const handleFeedTouchMove = useCallback((event: GestureResponderEvent) => {
978 + const handleFeedTouchMove = (event: GestureResponderEvent) => {
979 const start = feedTouchStartRef.current;
980 if (!start) {
981 return;
@@ -1036,18 +985,18 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
985 if (Math.hypot(deltaX, deltaY) > 8) {
986 feedTouchStartRef.current = null;
987 }
1039 - }, []);
988 + };
989
1041 - const handleFeedTouchEnd = useCallback(() => {
990 + const handleFeedTouchEnd = () => {
991 if (feedTouchStartRef.current) {
992 collapseComposer();
993 }
994 feedTouchStartRef.current = null;
1046 - }, [collapseComposer]);
995 + };
996
1048 - const handleFeedTouchCancel = useCallback(() => {
997 + const handleFeedTouchCancel = () => {
998 feedTouchStartRef.current = null;
1050 - }, []);
999 + };
1000
1001 return (
1002 <View className="flex-1">
@@ -1114,7 +1063,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
1063 layoutVariant={layoutVariant}
1064 usesAutomaticContentInsets={props.usesAutomaticContentInsets}
1065 onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
1117 - onEndFollowEnabledChange={setEndFollowEnabled}
1066 + onEndFollowEnabledChange={handleEndFollowEnabledChange}
1067 skills={selectedProviderSkills}
1068 onUseArtifactTemplate={handleUseArtifactTemplate}
1069 />
@@ -1415,4 +1364,4 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
1364 ) : null}
1365 </View>
1366 );
1418 -});
1367 +};
apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+325 -477
@@ -13,7 +13,7 @@ import {
13 import { LegendList } from "@legendapp/list/react-native";
14 import type { MenuAction } from "@react-native-menu/menu";
15 import { useAtomValue } from "@effect/atom-react";
16 -import { useCallback, useEffect, useMemo, useRef, useState } from "react";
16 +import { useEffect, useRef, useState } from "react";
17 import type { LayoutChangeEvent, TextInputInstance } from "react-native";
18 import { Platform, StyleSheet, TextInput, View } from "react-native";
19 import { GestureDetector, useNativeGesture } from "react-native-gesture-handler";
@@ -156,39 +156,31 @@ function ThreadNavigationSidebarPane(
156 const pendingTasks = usePendingNewTasks();
157 const queuedThreadKeys = useQueuedThreadKeys();
158 const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
159 - const environments = useMemo(
160 - () =>
161 - Object.values(savedConnectionsById)
162 - .map((connection) => ({
163 - environmentId: connection.environmentId,
164 - label: connection.environmentLabel,
165 - }))
166 - .sort((left, right) => left.label.localeCompare(right.label)),
167 - [savedConnectionsById],
168 - );
169 - const availableEnvironmentIds = useMemo(
170 - () => new Set(environments.map((environment) => environment.environmentId)),
171 - [environments],
159 + const environments = Object.values(savedConnectionsById)
160 + .map((connection) => ({
161 + environmentId: connection.environmentId,
162 + label: connection.environmentLabel,
163 + }))
164 + .sort((left, right) => left.label.localeCompare(right.label));
165 + const availableEnvironmentIds = new Set(
166 + environments.map((environment) => environment.environmentId),
167 );
168 const { options, setSelectedEnvironmentId, setSelectedProjectKey } =
169 useHomeListOptions(availableEnvironmentIds);
175 - const searchEnvironmentIds = useMemo(
176 - () =>
177 - options.selectedEnvironmentId === null
178 - ? workspaceEnvironments
179 - .filter((environment) => environment.connectionState === "connected")
180 - .map((environment) => environment.environmentId)
181 - : workspaceEnvironments.some(
182 - (environment) =>
183 - environment.environmentId === options.selectedEnvironmentId &&
184 - environment.connectionState === "connected",
185 - )
186 - ? [options.selectedEnvironmentId]
187 - : [],
188 - [options.selectedEnvironmentId, workspaceEnvironments],
189 - );
170 + const searchEnvironmentIds =
171 + options.selectedEnvironmentId === null
172 + ? workspaceEnvironments
173 + .filter((environment) => environment.connectionState === "connected")
174 + .map((environment) => environment.environmentId)
175 + : workspaceEnvironments.some(
176 + (environment) =>
177 + environment.environmentId === options.selectedEnvironmentId &&
178 + environment.connectionState === "connected",
179 + )
180 + ? [options.selectedEnvironmentId]
181 + : [];
182 const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery);
191 - const threadSearchMatchByKey = useMemo(() => {
183 + const threadSearchMatchByKey = (() => {
184 const matches = new Map<string, EnvironmentThreadSearchMatch>();
185 for (const match of threadSearch.matches) {
186 if (match.source === "user" || match.source === "assistant") {
@@ -196,11 +188,8 @@ function ThreadNavigationSidebarPane(
188 }
189 }
190 return matches;
199 - }, [threadSearch.matches]);
200 - const matchedThreadKeys = useMemo(
201 - () => new Set(threadSearch.matches.map(threadSearchMatchKey)),
202 - [threadSearch.matches],
203 - );
191 + })();
192 + const matchedThreadKeys = new Set(threadSearch.matches.map(threadSearchMatchKey));
193 const projectScopeKey = options.selectedProjectKey;
194 const resolvedProjectKey = resolveScratchProjectScopeKey(projectScopeKey, projects, {
195 sidebarProjectGroupingMode: options.projectGroupingMode,
@@ -211,75 +200,53 @@ function ThreadNavigationSidebarPane(
200 setSelectedProjectKey(resolvedProjectKey);
201 }
202 }, [projectScopeKey, resolvedProjectKey, setSelectedProjectKey]);
214 - const projectScopes = useMemo(
215 - () =>
216 - buildHomeProjectScopes({
217 - projects,
218 - environmentId: options.selectedEnvironmentId,
219 - projectGroupingMode: options.projectGroupingMode,
220 - }),
221 - [options.projectGroupingMode, options.selectedEnvironmentId, projects],
222 - );
223 - const projectFilterOptions = useMemo(
224 - () =>
225 - projectScopes.map((scope) => ({
226 - key: scope.key,
227 - label: scope.title,
228 - })),
229 - [projectScopes],
230 - );
231 - const projectTitleByProjectKey = useMemo(
232 - () =>
233 - new Map(
234 - projectScopes.flatMap((scope) =>
235 - scope.projectRefs.map(
236 - (projectRef) =>
237 - [
238 - scopedProjectKey(projectRef.environmentId, projectRef.projectId),
239 - scope.title,
240 - ] as const,
241 - ),
242 - ),
203 + const projectScopes = buildHomeProjectScopes({
204 + projects,
205 + environmentId: options.selectedEnvironmentId,
206 + projectGroupingMode: options.projectGroupingMode,
207 + });
208 + const projectFilterOptions = projectScopes.map((scope) => ({
209 + key: scope.key,
210 + label: scope.title,
211 + }));
212 + const projectTitleByProjectKey = new Map(
213 + projectScopes.flatMap((scope) =>
214 + scope.projectRefs.map(
215 + (projectRef) =>
216 + [scopedProjectKey(projectRef.environmentId, projectRef.projectId), scope.title] as const,
217 ),
244 - [projectScopes],
245 - );
246 - const selectedProjectScope = useMemo(
247 - () => projectScopes.find((scope) => scope.key === resolvedProjectKey) ?? null,
248 - [projectScopes, resolvedProjectKey],
218 + ),
219 );
220 + const selectedProjectScope =
221 + projectScopes.find((scope) => scope.key === resolvedProjectKey) ?? null;
222 const selectedProjectKey = selectedProjectScope?.key ?? null;
251 - const selectedProjectRefs = useMemo(
252 - () =>
253 - selectedProjectScope === null
254 - ? null
255 - : new Set(
256 - selectedProjectScope.projectRefs.map((projectRef) =>
257 - scopedProjectKey(projectRef.environmentId, projectRef.projectId),
258 - ),
223 + const selectedProjectRefs =
224 + selectedProjectScope === null
225 + ? null
226 + : new Set(
227 + selectedProjectScope.projectRefs.map((projectRef) =>
228 + scopedProjectKey(projectRef.environmentId, projectRef.projectId),
229 ),
260 - [selectedProjectScope],
261 - );
262 - const projectByKey = useMemo(() => {
230 + );
231 + const projectByKey = (() => {
232 const map = new Map<string, EnvironmentProject>();
233 for (const project of projects) {
234 map.set(scopedProjectKey(project.environmentId, project.id), project);
235 }
236 return map;
268 - }, [projects]);
237 + })();
238
239 const [settledVisibleCount, setSettledVisibleCount] = useState(
240 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
241 );
242 const settledResetKey = `${options.selectedEnvironmentId ?? "all"}:${selectedProjectKey ?? "all"}:${props.searchQuery.trim()}`;
274 - const lastSettledResetKeyRef = useRef(settledResetKey);
275 - if (lastSettledResetKeyRef.current !== settledResetKey) {
276 - lastSettledResetKeyRef.current = settledResetKey;
243 + const [lastSettledResetKey, setLastSettledResetKey] = useState(settledResetKey);
244 + if (lastSettledResetKey !== settledResetKey) {
245 + setLastSettledResetKey(settledResetKey);
246 setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
247 }
279 - const showMoreSettled = useCallback(
280 - () => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
281 - [],
282 - );
248 + const showMoreSettled = () =>
249 + setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT);
250 const {
251 loaded: shelfPreferencesLoaded,
252 settledShelfExpanded,
@@ -290,11 +257,15 @@ function ThreadNavigationSidebarPane(
257 toggleSnoozedShelf,
258 toggleWorkingShelf,
259 } = useThreadListV2ShelfPreferences();
293 - const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
260 + // The list's clock is state: the compiler caches anything computed from it on
261 + // its other inputs, so a render-time `new Date()` would stop moving. The minute
262 + // interval and the snooze-wake timer below both advance it.
263 + const [now, setNow] = useState(() => new Date().toISOString());
264 + const nowMinute = now.slice(0, 16);
265 const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
266 useEffect(() => {
296 - setNowMinute(new Date().toISOString().slice(0, 16));
297 - const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
267 + setNow(new Date().toISOString());
268 + const id = setInterval(() => setNow(new Date().toISOString()), 60_000);
269 return () => clearInterval(id);
270 }, []);
271 const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
@@ -314,7 +285,7 @@ function ThreadNavigationSidebarPane(
285 // Up/down menu availability for every card, computed once per section per
286 // rebuild (see computeThreadMoveAvailability): per-thread planner calls made
287 // list construction quadratic, and this list rebuilds on every minute tick.
317 - const threadMoveAvailability = useMemo(() => {
288 + const threadMoveAvailability = (() => {
289 const sectionAvailability = (section: "pinned" | "active") =>
290 computeThreadMoveAvailability({
291 allThreads: threads,
@@ -326,7 +297,7 @@ function ThreadNavigationSidebarPane(
297 threads,
298 section,
299 pendingOrder,
329 - now: new Date().toISOString(),
300 + now,
301 settlementEnvironmentIds,
302 snoozeEnvironmentIds,
303 queuedThreadKeys,
@@ -336,19 +307,8 @@ function ThreadNavigationSidebarPane(
307 ...sectionAvailability("pinned"),
308 ...(workingShelfEnabled ? [] : sectionAvailability("active")),
309 ]);
339 - }, [
340 - workingShelfEnabled,
341 - pinReorderEnvironmentIds,
342 - activeReorderEnvironmentIds,
343 - threads,
344 - pendingOrder,
345 - queuedThreadKeys,
346 - settlementEnvironmentIds,
347 - snoozeEnvironmentIds,
348 - nowMinute,
349 - snoozeWakeTick,
350 - ]);
351 - const threadListV2Layout = useMemo(() => {
310 + })();
311 + const threadListV2Layout = (() => {
312 threadListInboxReturns.observe(workingShelfEnabled ? threads : null);
313 return buildThreadListV2Items({
314 pendingOrder,
@@ -361,7 +321,7 @@ function ThreadNavigationSidebarPane(
321 snoozeEnvironmentIds,
322 queuedThreadKeys,
323 settledLimit: settledVisibleCount,
364 - now: new Date().toISOString(),
324 + now,
325 workingShelfEnabled,
326 workingShelfExpanded,
327 inboxReturnAt: threadListInboxReturns.returnedAt,
@@ -369,38 +329,23 @@ function ThreadNavigationSidebarPane(
329 settledShelfExpanded,
330 selectedThreadKey: props.selectedThreadKey ?? null,
331 });
372 - }, [
373 - workingShelfEnabled,
374 - workingShelfExpanded,
375 - pendingOrder,
376 - queuedThreadKeys,
377 - nowMinute,
378 - snoozeWakeTick,
379 - snoozedShelfExpanded,
380 - settledShelfExpanded,
381 - props.selectedThreadKey,
382 - options.selectedEnvironmentId,
383 - props.searchQuery,
384 - matchedThreadKeys,
385 - settledVisibleCount,
386 - settlementEnvironmentIds,
387 - snoozeEnvironmentIds,
388 - threads,
389 - selectedProjectScope,
390 - ]);
332 + })();
333 const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
334 useEffect(() => {
335 if (nextSnoozeWakeAt === null) return;
336 const wakeAtMs = Date.parse(nextSnoozeWakeAt);
337 if (Number.isNaN(wakeAtMs)) return;
338 const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
397 - const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
339 + const id = setTimeout(() => {
340 + setNow(new Date().toISOString());
341 + bumpSnoozeWakeTick((tick) => tick + 1);
342 + }, delayMs);
343 return () => clearTimeout(id);
344 // snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
345 // unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
346 // range) the boundary string is identical and the chain would die.
347 }, [nextSnoozeWakeAt, snoozeWakeTick]);
403 - const listItems = useMemo<readonly SidebarListItem[]>(() => {
348 + const listItems = ((): readonly SidebarListItem[] => {
349 const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
350 const v2PendingTasks = pendingTasks.filter(
351 (pendingTask) =>
@@ -439,95 +384,79 @@ function ThreadNavigationSidebarPane(
384 });
385 }
386 return items;
442 - }, [
443 - nowMinute,
444 - options.selectedEnvironmentId,
445 - pendingTasks,
446 - props.searchQuery,
447 - queuedThreadKeys,
448 - threadMoveAvailability,
449 - selectedProjectRefs,
450 - settledShelfExpanded,
451 - shelfPreferencesLoaded,
452 - snoozedShelfExpanded,
453 - snoozeEnvironmentIds,
454 - threadListV2Layout,
455 - workingShelfExpanded,
456 - ]);
457 - const listMenuActions = useMemo<MenuAction[]>(
458 - () => [
459 - {
460 - id: "environment",
461 - title: "Environment",
462 - subactions: [
387 + })();
388 + const listMenuActions = [
389 + {
390 + id: "environment",
391 + title: "Environment",
392 + subactions: [
393 + {
394 + id: "environment:all",
395 + title: "All environments",
396 + subtitle: "Show threads from every environment",
397 + state: options.selectedEnvironmentId === null ? "on" : "off",
398 + },
399 + ...environments.map((environment) => ({
400 + id: `environment:${environment.environmentId}`,
401 + title: environment.label,
402 + state:
403 + options.selectedEnvironmentId === environment.environmentId
404 + ? ("on" as const)
405 + : ("off" as const),
406 + })),
407 + ],
408 + },
409 + ...(projectFilterOptions.length === 0
410 + ? []
411 + : ([
412 {
464 - id: "environment:all",
465 - title: "All environments",
466 - subtitle: "Show threads from every environment",
467 - state: options.selectedEnvironmentId === null ? "on" : "off",
413 + id: "project",
414 + title: "Project",
415 + subactions: [
416 + {
417 + id: "project:all",
418 + title: "All projects",
419 + subtitle: "Show threads from every project",
420 + state: selectedProjectKey === null ? "on" : "off",
421 + },
422 + ...projectFilterOptions.map((project) => ({
423 + id: `project:${project.key}`,
424 + title: project.label,
425 + state: selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
426 + })),
427 + ],
428 },
469 - ...environments.map((environment) => ({
470 - id: `environment:${environment.environmentId}`,
471 - title: environment.label,
472 - state:
473 - options.selectedEnvironmentId === environment.environmentId
474 - ? ("on" as const)
475 - : ("off" as const),
476 - })),
477 - ],
478 - },
479 - ...(projectFilterOptions.length === 0
480 - ? []
481 - : ([
482 - {
483 - id: "project",
484 - title: "Project",
485 - subactions: [
486 - {
487 - id: "project:all",
488 - title: "All projects",
489 - subtitle: "Show threads from every project",
490 - state: selectedProjectKey === null ? "on" : "off",
491 - },
492 - ...projectFilterOptions.map((project) => ({
493 - id: `project:${project.key}`,
494 - title: project.label,
495 - state: selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
496 - })),
497 - ],
498 - },
499 - ] satisfies MenuAction[])),
500 - ],
501 - [environments, options, projectFilterOptions, selectedProjectKey],
502 - );
503 - const handleListMenuAction = useCallback(
504 - ({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
505 - const event = nativeEvent.event;
506 - if (event === "environment:all") {
507 - setSelectedEnvironmentId(null);
508 - return;
509 - }
510 - if (event.startsWith("environment:")) {
511 - const environment = environments.find(
512 - (candidate) => String(candidate.environmentId) === event.slice("environment:".length),
513 - );
514 - if (environment) setSelectedEnvironmentId(environment.environmentId);
515 - return;
516 - }
517 - if (event === "project:all") {
518 - setSelectedProjectKey(null);
519 - return;
520 - }
521 - if (event.startsWith("project:")) {
522 - const projectKey = event.slice("project:".length);
523 - if (projectFilterOptions.some((project) => project.key === projectKey)) {
524 - setSelectedProjectKey(projectKey);
525 - }
526 - return;
429 + ] satisfies MenuAction[])),
430 + ] satisfies MenuAction[];
431 + const handleListMenuAction = ({
432 + nativeEvent,
433 + }: {
434 + readonly nativeEvent: { readonly event: string };
435 + }) => {
436 + const event = nativeEvent.event;
437 + if (event === "environment:all") {
438 + setSelectedEnvironmentId(null);
439 + return;
440 + }
441 + if (event.startsWith("environment:")) {
442 + const environment = environments.find(
443 + (candidate) => String(candidate.environmentId) === event.slice("environment:".length),
444 + );
445 + if (environment) setSelectedEnvironmentId(environment.environmentId);
446 + return;
447 + }
448 + if (event === "project:all") {
449 + setSelectedProjectKey(null);
450 + return;
451 + }
452 + if (event.startsWith("project:")) {
453 + const projectKey = event.slice("project:".length);
454 + if (projectFilterOptions.some((project) => project.key === projectKey)) {
455 + setSelectedProjectKey(projectKey);
456 }
528 - },
529 - [environments, projectFilterOptions, setSelectedEnvironmentId, setSelectedProjectKey],
530 - );
457 + return;
458 + }
459 + };
460
461 const [measuredHeaderHeight, setMeasuredHeaderHeight] = useState<number | null>(null);
462 const { height, paddingTop, paddingBottom } = useToolbarLayout();
@@ -540,38 +469,35 @@ function ThreadNavigationSidebarPane(
469 ? paddingTop + height + paddingBottom
470 : insets.top + SIDEBAR_STICKY_HEADER_HEIGHT);
471 const topListInset = stickyHeaderHeight + 6;
543 - const handleStickyHeaderLayout = useCallback((event: LayoutChangeEvent) => {
472 + const handleStickyHeaderLayout = (event: LayoutChangeEvent) => {
473 const nextHeight = event.nativeEvent.layout.height;
474 setMeasuredHeaderHeight((current) => (current === nextHeight ? current : nextHeight));
546 - }, []);
547 - const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
475 + };
476 + const handleSwipeableWillOpen = (methods: SwipeableMethods) => {
477 if (openSwipeableRef.current !== methods) {
478 openSwipeableRef.current?.close();
479 openSwipeableRef.current = methods;
480 }
552 - }, []);
553 - const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
481 + };
482 + const handleSwipeableClose = (methods: SwipeableMethods) => {
483 if (openSwipeableRef.current === methods) {
484 openSwipeableRef.current = null;
485 }
557 - }, []);
558 - const handleSelectThread = useCallback(
559 - (thread: EnvironmentThreadShell) => {
560 - props.onSelectThread(thread);
561 - openSwipeableRef.current?.close();
562 - },
563 - [props.onSelectThread],
564 - );
565 - const handleOpenThreadPullRequests = useCallback(
566 - (thread: EnvironmentThreadShell, pr: ThreadPrPresentation) => {
567 - props.onOpenThreadPullRequests(thread, pr);
568 - openSwipeableRef.current?.close();
569 - },
570 - [props.onOpenThreadPullRequests],
571 - );
572 - const handleScrollBeginDrag = useCallback(() => {
486 + };
487 + const handleSelectThread = (thread: EnvironmentThreadShell) => {
488 + props.onSelectThread(thread);
489 openSwipeableRef.current?.close();
574 - }, []);
490 + };
491 + const handleOpenThreadPullRequests = (
492 + thread: EnvironmentThreadShell,
493 + pr: ThreadPrPresentation,
494 + ) => {
495 + props.onOpenThreadPullRequests(thread, pr);
496 + openSwipeableRef.current?.close();
497 + };
498 + const handleScrollBeginDrag = () => {
499 + openSwipeableRef.current?.close();
500 + };
501 const onFabScroll = useFabScroll();
502 const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
503 onScroll: onFabScroll,
@@ -582,40 +508,26 @@ function ThreadNavigationSidebarPane(
508 // blank favicon and fallback title it was first rendered with. The minute
509 // clock deliberately stays out: its per-row text lives on the items, so a
510 // tick only re-renders rows whose displayed text actually moved.
585 - const listExtraData = useMemo(
586 - () => ({
587 - selectedThreadKey: props.selectedThreadKey ?? "",
588 - projectByKey,
589 - projectTitleByProjectKey,
590 - savedConnectionsById,
591 - listEnvironments,
592 - threadSearchMatchByKey,
593 - workingShelfEnabled,
594 - }),
595 - [
596 - props.selectedThreadKey,
597 - projectByKey,
598 - projectTitleByProjectKey,
599 - savedConnectionsById,
600 - listEnvironments,
601 - threadSearchMatchByKey,
602 - workingShelfEnabled,
603 - ],
604 - );
511 + const listExtraData = {
512 + selectedThreadKey: props.selectedThreadKey ?? "",
513 + projectByKey,
514 + projectTitleByProjectKey,
515 + savedConnectionsById,
516 + listEnvironments,
517 + threadSearchMatchByKey,
518 + workingShelfEnabled,
519 + };
520 useThreadJumpShortcuts(listItems, handleSelectThread);
606 - const sidebarItemsAreEqual = useCallback(
607 - (previous: SidebarListItem, item: SidebarListItem): boolean => {
608 - if (isThreadListV2ListItem(previous) && isThreadListV2ListItem(item)) {
609 - return threadListV2ListItemsAreEqual(previous, item);
610 - }
611 - if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
612 - return previous.hiddenCount === item.hiddenCount;
613 - }
614 - return false;
615 - },
616 - [],
617 - );
618 - const focusSearch = useCallback(() => {
521 + const sidebarItemsAreEqual = (previous: SidebarListItem, item: SidebarListItem): boolean => {
522 + if (isThreadListV2ListItem(previous) && isThreadListV2ListItem(item)) {
523 + return threadListV2ListItemsAreEqual(previous, item);
524 + }
525 + if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
526 + return previous.hiddenCount === item.hiddenCount;
527 + }
528 + return false;
529 + };
530 + const focusSearch = () => {
531 if (Platform.OS === "android") return false;
532 const focus = () => {
533 if (props.nativeChrome) {
@@ -631,220 +543,156 @@ function ThreadNavigationSidebarPane(
543 focus();
544 }
545 return true;
634 - }, [props.nativeChrome, props.onRequestVisibility, props.visible]);
546 + };
547 useHardwareKeyboardCommand("focusSearch", focusSearch);
636 - const renderListItem = useCallback(
637 - ({ item }: { readonly item: SidebarListItem }) => {
638 - switch (item.type) {
639 - case "v2-pending": {
640 - const pendingScopeKey = scopedProjectKey(
641 - item.pendingTask.environmentId,
642 - item.pendingTask.projectId,
643 - );
644 - return (
645 - <ThreadListV2PendingRow
646 - pendingTask={item.pendingTask}
647 - project={projectByKey.get(pendingScopeKey) ?? null}
648 - projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}
649 - environmentLabel={
650 - Object.keys(savedConnectionsById).length > 1
651 - ? (savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? null)
652 - : null
653 - }
654 - environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
655 - pane="sidebar"
656 - showPendingDivider={item.showPendingDivider}
657 - onSelectPendingTask={openPendingTask}
658 - onDeletePendingTask={confirmDeletePendingTask}
659 - />
660 - );
661 - }
662 - case "v2-thread": {
663 - const thread = item.item.thread;
664 - const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId);
665 - return (
666 - <ThreadListV2Row
667 - onNewThreadOnBranch={props.onNewThreadOnBranch}
668 - thread={thread}
669 - variant={item.item.variant}
670 - hasQueuedMessages={item.hasQueuedMessages}
671 - snoozed={item.item.snoozed}
672 - pinned={item.item.pinned}
673 - snoozePresetMinute={item.snoozePresetMinute ?? ""}
674 - snoozeWakeLabelText={item.snoozeWakeLabelText}
675 - timeLabel={item.timeLabel}
676 - project={projectByKey.get(scopeKey) ?? null}
677 - projectTitle={projectTitleByProjectKey.get(scopeKey)}
678 - providerInstance={resolveProviderInstance(thread)}
679 - providers={providersByEnvironmentId.get(thread.environmentId)}
680 - environmentLabel={
681 - Object.keys(savedConnectionsById).length > 1
682 - ? (savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
683 - : null
684 - }
685 - environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
686 - searchMatch={threadSearchMatchByKey.get(
687 - threadSearchMatchKey({
688 - environmentId: thread.environmentId,
689 - threadId: thread.id,
690 - }),
691 - )}
692 - searchQuery={props.searchQuery}
693 - pane="sidebar"
694 - selected={
695 - scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
696 - }
697 - fullSwipeWidth={props.width - 20}
698 - onSelectThread={handleSelectThread}
699 - onOpenThreadPullRequests={handleOpenThreadPullRequests}
700 - onDeleteThread={confirmDeleteThread}
701 - onArchiveThread={archiveThread}
702 - onRenameThread={renameThread}
703 - onRegenerateThreadTitle={regenerateThreadTitle}
704 - titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
705 - settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
706 - onSettleThread={settleThread}
707 - snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
708 - pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
709 - autoSettleOptOutSupported={autoSettleOptOutEnvironmentIds.has(thread.environmentId)}
710 - reorderSupported={
711 - item.item.pinned
712 - ? pinReorderEnvironmentIds.has(thread.environmentId)
713 - : !workingShelfEnabled && activeReorderEnvironmentIds.has(thread.environmentId)
714 - }
715 - canMoveUp={item.canMoveUp}
716 - canMoveDown={item.canMoveDown}
717 - onSnoozeThread={snoozeThread}
718 - onUnsnoozeThread={unsnoozeThread}
719 - onUnsettleThread={unsettleThread}
720 - onPinThread={pinThread}
721 - onUnpinThread={unpinThread}
722 - onSetThreadAutoSettle={setThreadAutoSettle}
723 - onMoveThread={moveThread}
724 - onSwipeableClose={handleSwipeableClose}
725 - onSwipeableWillOpen={handleSwipeableWillOpen}
726 - simultaneousSwipeGesture={sidebarScrollGesture}
727 - />
728 - );
729 - }
730 - case "v2-working-shelf":
731 - return (
732 - <ThreadListV2WorkingShelfHeader
733 - count={item.count}
734 - disabled={item.disabled}
735 - expanded={item.expanded}
736 - onToggle={toggleWorkingShelf}
737 - pane="sidebar"
738 - />
739 - );
740 - case "v2-snoozed-shelf":
741 - return (
742 - <ThreadListV2SnoozedShelfHeader
743 - count={item.count}
744 - disabled={item.disabled}
745 - expanded={item.expanded}
746 - onToggle={toggleSnoozedShelf}
747 - pane="sidebar"
748 - />
749 - );
750 - case "v2-settled-shelf":
751 - return (
752 - <ThreadListV2SettledShelfHeader
753 - count={item.count}
754 - disabled={item.disabled}
755 - expanded={item.expanded}
756 - onToggle={toggleSettledShelf}
757 - pane="sidebar"
758 - />
759 - );
760 - case "v2-show-more":
761 - return (
762 - <ThreadListV2ShowMoreRow
763 - pane="sidebar"
764 - hiddenCount={item.hiddenCount}
765 - onPress={showMoreSettled}
766 - />
767 - );
548 + const renderListItem = ({ item }: { readonly item: SidebarListItem }) => {
549 + switch (item.type) {
550 + case "v2-pending": {
551 + const pendingScopeKey = scopedProjectKey(
552 + item.pendingTask.environmentId,
553 + item.pendingTask.projectId,
554 + );
555 + return (
556 + <ThreadListV2PendingRow
557 + pendingTask={item.pendingTask}
558 + project={projectByKey.get(pendingScopeKey) ?? null}
559 + projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}
560 + environmentLabel={
561 + Object.keys(savedConnectionsById).length > 1
562 + ? (savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? null)
563 + : null
564 + }
565 + environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
566 + pane="sidebar"
567 + showPendingDivider={item.showPendingDivider}
568 + onSelectPendingTask={openPendingTask}
569 + onDeletePendingTask={confirmDeletePendingTask}
570 + />
571 + );
572 }
769 - },
770 - [
771 - archiveThread,
772 - activeReorderEnvironmentIds,
773 - confirmDeletePendingTask,
774 - confirmDeleteThread,
775 - handleOpenThreadPullRequests,
776 - handleSelectThread,
777 - handleSwipeableClose,
778 - handleSwipeableWillOpen,
779 - machineByEnvironmentId,
780 - moveThread,
781 - openPendingTask,
782 - pinReorderEnvironmentIds,
783 - pinThread,
784 - pinningEnvironmentIds,
785 - autoSettleOptOutEnvironmentIds,
786 - autoSettleOptOutEnvironmentIds,
787 - setThreadAutoSettle,
788 - projectByKey,
789 - projectTitleByProjectKey,
790 - regenerateThreadTitle,
791 - renameThread,
792 - props.onNewThreadOnBranch,
793 - props.searchQuery,
794 - props.selectedThreadKey,
795 - props.width,
796 - savedConnectionsById,
797 - resolveProviderInstance,
798 - providersByEnvironmentId,
799 - threadSearchMatchByKey,
800 - titleRegenerationEnvironmentIds,
801 - settleThread,
802 - settlementEnvironmentIds,
803 - showMoreSettled,
804 - sidebarScrollGesture,
805 - snoozeEnvironmentIds,
806 - snoozeThread,
807 - toggleSettledShelf,
808 - toggleSnoozedShelf,
809 - toggleWorkingShelf,
810 - unpinThread,
811 - unsettleThread,
812 - unsnoozeThread,
813 - workingShelfEnabled,
814 - ],
815 - );
573 + case "v2-thread": {
574 + const thread = item.item.thread;
575 + const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId);
576 + return (
577 + <ThreadListV2Row
578 + onNewThreadOnBranch={props.onNewThreadOnBranch}
579 + thread={thread}
580 + variant={item.item.variant}
581 + hasQueuedMessages={item.hasQueuedMessages}
582 + snoozed={item.item.snoozed}
583 + pinned={item.item.pinned}
584 + snoozePresetMinute={item.snoozePresetMinute ?? ""}
585 + snoozeWakeLabelText={item.snoozeWakeLabelText}
586 + timeLabel={item.timeLabel}
587 + project={projectByKey.get(scopeKey) ?? null}
588 + projectTitle={projectTitleByProjectKey.get(scopeKey)}
589 + providerInstance={resolveProviderInstance(thread)}
590 + providers={providersByEnvironmentId.get(thread.environmentId)}
591 + environmentLabel={
592 + Object.keys(savedConnectionsById).length > 1
593 + ? (savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
594 + : null
595 + }
596 + environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
597 + searchMatch={threadSearchMatchByKey.get(
598 + threadSearchMatchKey({
599 + environmentId: thread.environmentId,
600 + threadId: thread.id,
601 + }),
602 + )}
603 + searchQuery={props.searchQuery}
604 + pane="sidebar"
605 + selected={scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey}
606 + fullSwipeWidth={props.width - 20}
607 + onSelectThread={handleSelectThread}
608 + onOpenThreadPullRequests={handleOpenThreadPullRequests}
609 + onDeleteThread={confirmDeleteThread}
610 + onArchiveThread={archiveThread}
611 + onRenameThread={renameThread}
612 + onRegenerateThreadTitle={regenerateThreadTitle}
613 + titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
614 + settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
615 + onSettleThread={settleThread}
616 + snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
617 + pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
618 + autoSettleOptOutSupported={autoSettleOptOutEnvironmentIds.has(thread.environmentId)}
619 + reorderSupported={
620 + item.item.pinned
621 + ? pinReorderEnvironmentIds.has(thread.environmentId)
622 + : !workingShelfEnabled && activeReorderEnvironmentIds.has(thread.environmentId)
623 + }
624 + canMoveUp={item.canMoveUp}
625 + canMoveDown={item.canMoveDown}
626 + onSnoozeThread={snoozeThread}
627 + onUnsnoozeThread={unsnoozeThread}
628 + onUnsettleThread={unsettleThread}
629 + onPinThread={pinThread}
630 + onUnpinThread={unpinThread}
631 + onSetThreadAutoSettle={setThreadAutoSettle}
632 + onMoveThread={moveThread}
633 + onSwipeableClose={handleSwipeableClose}
634 + onSwipeableWillOpen={handleSwipeableWillOpen}
635 + simultaneousSwipeGesture={sidebarScrollGesture}
636 + />
637 + );
638 + }
639 + case "v2-working-shelf":
640 + return (
641 + <ThreadListV2WorkingShelfHeader
642 + count={item.count}
643 + disabled={item.disabled}
644 + expanded={item.expanded}
645 + onToggle={toggleWorkingShelf}
646 + pane="sidebar"
647 + />
648 + );
649 + case "v2-snoozed-shelf":
650 + return (
651 + <ThreadListV2SnoozedShelfHeader
652 + count={item.count}
653 + disabled={item.disabled}
654 + expanded={item.expanded}
655 + onToggle={toggleSnoozedShelf}
656 + pane="sidebar"
657 + />
658 + );
659 + case "v2-settled-shelf":
660 + return (
661 + <ThreadListV2SettledShelfHeader
662 + count={item.count}
663 + disabled={item.disabled}
664 + expanded={item.expanded}
665 + onToggle={toggleSettledShelf}
666 + pane="sidebar"
667 + />
668 + );
669 + case "v2-show-more":
670 + return (
671 + <ThreadListV2ShowMoreRow
672 + pane="sidebar"
673 + hiddenCount={item.hiddenCount}
674 + onPress={showMoreSettled}
675 + />
676 + );
677 + }
678 + };
679 const filterCustomized = options.selectedEnvironmentId !== null || selectedProjectKey !== null;
680 const filterIcon = filterCustomized
681 ? "line.3.horizontal.decrease.circle.fill"
682 : "line.3.horizontal.decrease.circle";
820 - const filterMenu = useMemo(
821 - () =>
822 - buildHomeListFilterMenu({
823 - environments,
824 - projects: projectFilterOptions,
825 - selectedEnvironmentId: options.selectedEnvironmentId,
826 - selectedProjectKey,
827 - onEnvironmentChange: setSelectedEnvironmentId,
828 - onProjectChange: setSelectedProjectKey,
829 - }),
830 - [
831 - environments,
832 - options,
833 - projectFilterOptions,
834 - selectedProjectKey,
835 - setSelectedEnvironmentId,
836 - setSelectedProjectKey,
837 - ],
838 - );
839 - const nativeHeaderItems = useMemo(
840 - () =>
841 - createSidebarHeaderItems({
842 - filterIcon,
843 - filterMenu,
844 - onOpenSettings: props.onOpenSettings,
845 - }),
846 - [filterIcon, filterMenu, props.onOpenSettings],
847 - );
683 + const filterMenu = buildHomeListFilterMenu({
684 + environments,
685 + projects: projectFilterOptions,
686 + selectedEnvironmentId: options.selectedEnvironmentId,
687 + selectedProjectKey,
688 + onEnvironmentChange: setSelectedEnvironmentId,
689 + onProjectChange: setSelectedProjectKey,
690 + });
691 + const nativeHeaderItems = createSidebarHeaderItems({
692 + filterIcon,
693 + filterMenu,
694 + onOpenSettings: props.onOpenSettings,
695 + });
696 const listEmpty = (
697 <Text
698 className={
apps/mobile/src/features/threads/use-thread-list-v2-shelf-preferences.ts
+23 -26
@@ -1,13 +1,8 @@
1 import { useAtomSet, useAtomValue } from "@effect/atom-react";
2 import { AsyncResult } from "effect/reactivity";
3 -import { useCallback, useRef } from "react";
3
4 import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
5
7 -/**
8 - * Refs advance before persistence starts so consecutive presses always toggle the latest value,
9 - * even if React has not rendered the optimistic patch yet.
10 - */
6 export function useThreadListV2ShelfPreferences() {
7 const preferencesResult = useAtomValue(mobilePreferencesAtom);
8 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
@@ -19,31 +14,33 @@ export function useThreadListV2ShelfPreferences() {
14 const workingShelfEnabled = loaded && preferencesResult.value.workingShelfEnabled === true;
15 const workingShelfExpanded =
16 loaded && preferencesResult.value.threadListWorkingShelfExpanded === true;
22 - const snoozedShelfExpandedRef = useRef(snoozedShelfExpanded);
23 - const settledShelfExpandedRef = useRef(settledShelfExpanded);
24 - const workingShelfExpandedRef = useRef(workingShelfExpanded);
25 - snoozedShelfExpandedRef.current = snoozedShelfExpanded;
26 - settledShelfExpandedRef.current = settledShelfExpanded;
27 - workingShelfExpandedRef.current = workingShelfExpanded;
17
29 - const toggleSnoozedShelf = useCallback(() => {
18 + // A transform reads the optimistic value, so two presses before the next
19 + // render still toggle twice instead of writing the same value.
20 + const toggleSnoozedShelf = () => {
21 if (!loaded) return;
31 - const expanded = !snoozedShelfExpandedRef.current;
32 - snoozedShelfExpandedRef.current = expanded;
33 - savePreferences({ threadListSnoozedShelfExpanded: expanded });
34 - }, [loaded, savePreferences]);
35 - const toggleSettledShelf = useCallback(() => {
22 + savePreferences({
23 + transform: (current) => ({
24 + threadListSnoozedShelfExpanded: current.threadListSnoozedShelfExpanded !== true,
25 + }),
26 + });
27 + };
28 + const toggleSettledShelf = () => {
29 if (!loaded) return;
37 - const expanded = !settledShelfExpandedRef.current;
38 - settledShelfExpandedRef.current = expanded;
39 - savePreferences({ threadListSettledShelfExpanded: expanded });
40 - }, [loaded, savePreferences]);
41 - const toggleWorkingShelf = useCallback(() => {
30 + savePreferences({
31 + transform: (current) => ({
32 + threadListSettledShelfExpanded: current.threadListSettledShelfExpanded !== true,
33 + }),
34 + });
35 + };
36 + const toggleWorkingShelf = () => {
37 if (!loaded) return;
43 - const expanded = !workingShelfExpandedRef.current;
44 - workingShelfExpandedRef.current = expanded;
45 - savePreferences({ threadListWorkingShelfExpanded: expanded });
46 - }, [loaded, savePreferences]);
38 + savePreferences({
39 + transform: (current) => ({
40 + threadListWorkingShelfExpanded: current.threadListWorkingShelfExpanded !== true,
41 + }),
42 + });
43 + };
44
45 return {
46 loaded,
apps/mobile/src/reactCompilerCoverage.test.ts
-3
@@ -24,10 +24,7 @@ const KNOWN_BAILOUTS: Record<string, string> = {
24 "src/features/terminal/ThreadTerminalRouteScreen.tsx": "ref read during render",
25 "src/features/threads/PendingUserInputCard.tsx": "mutates a frozen value",
26 "src/features/threads/ThreadArrangementSheet.tsx": "ref read during render",
27 - "src/features/threads/ThreadDetailScreen.tsx": "mutates a frozen value",
27 "src/features/threads/ThreadFeed.tsx": "ref read during render, throw inside try, try/finally",
29 - "src/features/threads/ThreadNavigationSidebar.tsx": "ref read during render",
30 - "src/features/threads/use-thread-list-v2-shelf-preferences.ts": "ref read during render",
28 "src/features/voice-input/VoiceInputProvider.tsx": "ref read during render",
29 "src/features/voice-input/useVoiceInputController.ts": "ref read during render",
30 "src/native/StackHeader.tsx": "ref read during render",