TypeScript
perf(mobile): home, workspace layout and overlay pieces compile with the React Compiler (#21133)
Julius Marminge671719b25c5b
diff --git a/apps/mobile/src/components/ui/OverlayPortal.tsx b/apps/mobile/src/components/ui/OverlayPortal.tsxindex 1cc5b820e04..42ba1c5dec5 100644--- a/apps/mobile/src/components/ui/OverlayPortal.tsx+++ b/apps/mobile/src/components/ui/OverlayPortal.tsx@@ -1,4 +1,4 @@-import { type ReactNode, useEffect, useRef, useState } from "react";+import { type ReactNode, useEffect, useState } from "react";import { View } from "react-native";// AndroidAnchoredMenu projects its dropdown here instead of into an RN Modal: a Modal is a@@ -8,6 +8,10 @@ type Entries = ReadonlyMap<number, ReactNode>;type Listener = (entries: Entries) => void;let nextKey = 0;++function allocateKey() {+ return nextKey++;+}const entries = new Map<number, ReactNode>();const listeners = new Set<Listener>();@@ -19,9 +23,7 @@ function emit() {}export function OverlayPortal(props: { readonly children: ReactNode }) {- const keyRef = useRef<number | null>(null);- keyRef.current ??= nextKey++;- const key = keyRef.current;+ const [key] = useState(allocateKey);// No dependency array: re-project after every render so the host always// shows the current content (menus re-render while open — drill-in, theme).diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsxindex 12ff121e756..fa4059922bd 100644--- a/apps/mobile/src/features/home/HomeScreen.tsx+++ b/apps/mobile/src/features/home/HomeScreen.tsx@@ -14,7 +14,7 @@ import {import { type EnvironmentId, type SidebarProjectGroupingMode } from "@t3tools/contracts";import { useAtomValue } from "@effect/atom-react";import { useFocusEffect } from "@react-navigation/native";-import { use, useCallback, useEffect, useMemo, useRef, useState, type ComponentProps } from "react";+import { use, useEffect, useRef, useState, type ComponentProps } from "react";import {Platform,ScrollView,@@ -287,23 +287,20 @@ export function HomeScreen(props: HomeScreenProps) {24,workspace?.bottomClearance ?? 0,);- const searchEnvironmentIds = useMemo(- () =>- props.selectedEnvironmentId === null- ? props.environments- .filter((environment) => environment.connectionState === "connected")- .map((environment) => environment.environmentId)- : props.environments.some(- (environment) =>- environment.environmentId === props.selectedEnvironmentId &&- environment.connectionState === "connected",- )- ? [props.selectedEnvironmentId]- : [],- [props.environments, props.selectedEnvironmentId],- );+ const searchEnvironmentIds =+ props.selectedEnvironmentId === null+ ? props.environments+ .filter((environment) => environment.connectionState === "connected")+ .map((environment) => environment.environmentId)+ : props.environments.some(+ (environment) =>+ environment.environmentId === props.selectedEnvironmentId &&+ environment.connectionState === "connected",+ )+ ? [props.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") {@@ -311,35 +308,32 @@ export function HomeScreen(props: HomeScreenProps) {}}return matches;- }, [threadSearch.matches]);- const matchedThreadKeys = useMemo(- () => new Set(threadSearch.matches.map(threadSearchMatchKey)),- [threadSearch.matches],- );- const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {+ })();+ const matchedThreadKeys = new Set(threadSearch.matches.map(threadSearchMatchKey));+ 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 handleScrollBeginDrag = useCallback(() => {+ const handleScrollBeginDrag = () => {openSwipeableRef.current?.close();- }, []);+ };const openThreadPullRequests = useOpenThreadPullRequests();- const handleOpenThreadPullRequests = useCallback(- (thread: EnvironmentThreadShell, pr: ThreadPrPresentation) => {- openSwipeableRef.current?.close();- openThreadPullRequests(thread, pr);- },- [openThreadPullRequests],- );+ const handleOpenThreadPullRequests = (+ thread: EnvironmentThreadShell,+ pr: ThreadPrPresentation,+ ) => {+ openSwipeableRef.current?.close();+ openThreadPullRequests(thread, pr);+ };const onFabScroll = useFabScroll();const listRef = useRef<LegendListRef>(null);const searchMode = workspace?.state.tabs.threads.searchMode;@@ -351,163 +345,111 @@ export function HomeScreen(props: HomeScreenProps) {animated: false,});}, [searchMode, insets.top, restoredOffset]);- const swipeRowActivation = useMemo(() => createSwipeRowActivation(), []);- const activateVisibleRows = useCallback(- (rows: ReadonlyArray<ThreadListV2ListItem>) => {- const state = listRef.current?.getState();- if (state === undefined || !(state.end >= 0)) return;- swipeRowActivation.activate(- rows.slice(Math.max(0, state.start - 2), state.end + 3).map((row) => row.key),- );- },- [swipeRowActivation],- );+ const swipeRowActivation = createSwipeRowActivation();+ const activateVisibleRows = (rows: ReadonlyArray<ThreadListV2ListItem>) => {+ const state = listRef.current?.getState();+ if (state === undefined || !(state.end >= 0)) return;+ swipeRowActivation.activate(+ rows.slice(Math.max(0, state.start - 2), state.end + 3).map((row) => row.key),+ );+ };// Status-bar, accessibility and programmatic scrolls never arm the scroll// gate, so every scroll also activates the visible rows once it settles.const activationTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);useEffect(() => () => clearTimeout(activationTimerRef.current), []);- const handleListScroll = useCallback(- (event: NativeSyntheticEvent<NativeScrollEvent>) => {- onFabScroll?.(event);- if (workspace)- workspace.recordScrollOffset(- "threads",- Math.max(0, event.nativeEvent.contentOffset.y + (Platform.OS === "ios" ? insets.top : 0)),- );- clearTimeout(activationTimerRef.current);- activationTimerRef.current = setTimeout(- () => activateVisibleRows(listRef.current?.getState().data ?? []),- 200,+ const handleListScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {+ onFabScroll?.(event);+ if (workspace)+ workspace.recordScrollOffset(+ "threads",+ Math.max(0, event.nativeEvent.contentOffset.y + (Platform.OS === "ios" ? insets.top : 0)),);- },- [activateVisibleRows, onFabScroll, workspace, insets.top],- );- const trackListTouches = useCallback(- (event: GestureResponderEvent, started: boolean) => {- const { changedTouches, touches } = event.nativeEvent;- swipeRowActivation.trackTouches(- started ? changedTouches.map((touch) => String(touch.identifier)) : [],- touches.map((touch) => String(touch.identifier)),- );- },- [swipeRowActivation],- );+ clearTimeout(activationTimerRef.current);+ activationTimerRef.current = setTimeout(+ () => activateVisibleRows(listRef.current?.getState().data ?? []),+ 200,+ );+ };+ const trackListTouches = (event: GestureResponderEvent, started: boolean) => {+ const { changedTouches, touches } = event.nativeEvent;+ swipeRowActivation.trackTouches(+ started ? changedTouches.map((touch) => String(touch.identifier)) : [],+ touches.map((touch) => String(touch.identifier)),+ );+ };const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({onScroll: handleListScroll,onScrollBeginDrag: handleScrollBeginDrag,});- const projectScopes = useMemo(- () =>- buildHomeProjectScopes({- projects: props.projects,- environmentId: props.selectedEnvironmentId,- projectGroupingMode: props.projectGroupingMode,- }),- [props.projectGroupingMode, props.projects, props.selectedEnvironmentId],- );+ const projectScopes = buildHomeProjectScopes({+ projects: props.projects,+ environmentId: props.selectedEnvironmentId,+ projectGroupingMode: props.projectGroupingMode,+ });const hasSearchQuery = props.searchQuery.trim().length > 0;- const projectByKey = useMemo(() => {+ const projectByKey = (() => {const map = new Map<string, EnvironmentProject>();for (const project of props.projects) {map.set(scopedProjectKey(project.environmentId, project.id), project);}return map;- }, [props.projects]);+ })();const v2ProjectScopeKey = props.selectedProjectKey;- const v2ScopedProjectGroup = useMemo(- () => findHomeProjectScope(projectScopes, v2ProjectScopeKey),- [v2ProjectScopeKey, projectScopes],- );- const v2ProjectTitleByProjectKey = useMemo(- () =>- new Map(- projectScopes.flatMap((scope) =>- scope.projectRefs.map(- (projectRef) =>- [- scopedProjectKey(projectRef.environmentId, projectRef.projectId),- scope.title,- ] as const,- ),- ),+ const v2ScopedProjectGroup = findHomeProjectScope(projectScopes, v2ProjectScopeKey);+ const v2ProjectTitleByProjectKey = new Map(+ projectScopes.flatMap((scope) =>+ scope.projectRefs.map(+ (projectRef) =>+ [scopedProjectKey(projectRef.environmentId, projectRef.projectId), scope.title] as const,),- [projectScopes],+ ),);- const v2ScopedProjectKeys = useMemo(- () =>- v2ScopedProjectGroup === null- ? null- : new Set(- v2ScopedProjectGroup.projectRefs.map((projectRef) =>- scopedProjectKey(projectRef.environmentId, projectRef.projectId),- ),+ const v2ScopedProjectKeys =+ v2ScopedProjectGroup === null+ ? null+ : new Set(+ v2ScopedProjectGroup.projectRefs.map((projectRef) =>+ scopedProjectKey(projectRef.environmentId, projectRef.projectId),),- [v2ScopedProjectGroup],- );+ );const handleSettleThread = props.onSettleThread;- const handleSnoozeThread = useCallback(- (thread: EnvironmentThreadShell, snoozedUntil: string) => {- void props.onSnoozeThread(thread, snoozedUntil);- },- [props.onSnoozeThread],- );- const handleUnsnoozeThread = useCallback(- (thread: EnvironmentThreadShell) => {- void props.onUnsnoozeThread(thread);- },- [props.onUnsnoozeThread],- );- const handlePinThread = useCallback(- (thread: EnvironmentThreadShell) => {- void props.onPinThread(thread);- },- [props.onPinThread],- );- const handleMoveThread = useCallback(- (thread: EnvironmentThreadShell, direction: ThreadMoveDestination) => {- void props.onMoveThread(thread, direction);- },- [props.onMoveThread],- );- const handleUnpinThread = useCallback(- (thread: EnvironmentThreadShell) => {- void props.onUnpinThread(thread);- },- [props.onUnpinThread],- );- const handleSetThreadAutoSettle = useCallback(- (thread: EnvironmentThreadShell, enabled: boolean) => {- void props.onSetThreadAutoSettle(thread, enabled);- },- [props.onSetThreadAutoSettle],- );- const handleRegenerateThreadTitle = useCallback(- (thread: EnvironmentThreadShell) => {- void props.onRegenerateThreadTitle(thread);- },- [props.onRegenerateThreadTitle],- );- const handleRenameThread = useCallback(- (thread: EnvironmentThreadShell) => props.onRenameThread(thread),- [props.onRenameThread],- );+ const handleSnoozeThread = (thread: EnvironmentThreadShell, snoozedUntil: string) => {+ void props.onSnoozeThread(thread, snoozedUntil);+ };+ const handleUnsnoozeThread = (thread: EnvironmentThreadShell) => {+ void props.onUnsnoozeThread(thread);+ };+ const handlePinThread = (thread: EnvironmentThreadShell) => {+ void props.onPinThread(thread);+ };+ const handleMoveThread = (thread: EnvironmentThreadShell, direction: ThreadMoveDestination) => {+ void props.onMoveThread(thread, direction);+ };+ const handleUnpinThread = (thread: EnvironmentThreadShell) => {+ void props.onUnpinThread(thread);+ };+ const handleSetThreadAutoSettle = (thread: EnvironmentThreadShell, enabled: boolean) => {+ void props.onSetThreadAutoSettle(thread, enabled);+ };+ const handleRegenerateThreadTitle = (thread: EnvironmentThreadShell) => {+ void props.onRegenerateThreadTitle(thread);+ };+ const handleRenameThread = (thread: EnvironmentThreadShell) => props.onRenameThread(thread);const handleDeleteThread = props.onDeleteThread;const handleUnsettleThread = props.onUnsettleThread;const [settledVisibleCount, setSettledVisibleCount] = useState(THREAD_LIST_V2_SETTLED_INITIAL_COUNT,);const settledResetKey = `${props.selectedEnvironmentId ?? "all"}:${v2ProjectScopeKey ?? "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,@@ -518,15 +460,17 @@ export function HomeScreen(props: HomeScreenProps) {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);- useFocusEffect(- useCallback(() => {- setNowMinute(new Date().toISOString().slice(0, 16));- const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);- return () => clearInterval(id);- }, []),- );+ useFocusEffect(() => {+ setNow(new Date().toISOString());+ const id = setInterval(() => setNow(new Date().toISOString()), 60_000);+ return () => clearInterval(id);+ });const listEnvironments = useAtomValue(threadListEnvironmentsAtom);const {providersByEnvironmentId,@@ -544,7 +488,7 @@ export function HomeScreen(props: HomeScreenProps) {// 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: props.threads,@@ -556,7 +500,7 @@ export function HomeScreen(props: HomeScreenProps) {threads: props.threads,section,pendingOrder,- now: new Date().toISOString(),+ now,settlementEnvironmentIds,snoozeEnvironmentIds,queuedThreadKeys,@@ -566,19 +510,8 @@ export function HomeScreen(props: HomeScreenProps) {...sectionAvailability("pinned"),...(workingShelfEnabled ? [] : sectionAvailability("active")),]);- }, [- workingShelfEnabled,- pinReorderEnvironmentIds,- activeReorderEnvironmentIds,- props.threads,- pendingOrder,- queuedThreadKeys,- settlementEnvironmentIds,- snoozeEnvironmentIds,- nowMinute,- snoozeWakeTick,- ]);- const threadListV2Layout = useMemo(() => {+ })();+ const threadListV2Layout = (() => {threadListInboxReturns.observe(workingShelfEnabled ? props.threads : null);return buildThreadListV2Items({pendingOrder,@@ -591,7 +524,7 @@ export function HomeScreen(props: HomeScreenProps) {snoozeEnvironmentIds,queuedThreadKeys,settledLimit: settledVisibleCount,- now: new Date().toISOString(),+ now,workingShelfEnabled,workingShelfExpanded,inboxReturnAt: threadListInboxReturns.returnedAt,@@ -599,292 +532,196 @@ export function HomeScreen(props: HomeScreenProps) {settledShelfExpanded,selectedThreadKey,});- }, [- workingShelfEnabled,- workingShelfExpanded,- pendingOrder,- selectedThreadKey,- queuedThreadKeys,- nowMinute,- snoozeWakeTick,- snoozedShelfExpanded,- settledShelfExpanded,- settledVisibleCount,- settlementEnvironmentIds,- snoozeEnvironmentIds,- props.searchQuery,- props.selectedEnvironmentId,- props.threads,- matchedThreadKeys,- v2ScopedProjectGroup,- ]);+ })();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 v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();- const v2PendingTasks = useMemo(- () =>- props.pendingTasks.filter(- (pendingTask) =>- (props.selectedEnvironmentId === null ||- pendingTask.environmentId === props.selectedEnvironmentId) &&- (v2ScopedProjectKeys === null ||- v2ScopedProjectKeys.has(- scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),- )) &&- (v2SearchQuery.length === 0 ||- pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),- ),- [props.pendingTasks, props.selectedEnvironmentId, v2ScopedProjectKeys, v2SearchQuery],- );- const threadListV2Items = useMemo(- () =>- buildThreadListV2ListItems({- items: threadListV2Layout.items,- pendingTasks: v2PendingTasks,- workingCount: threadListV2Layout.workingCount,- workingShelfExpanded,- workingShelfHeaderIndex: threadListV2Layout.workingShelfHeaderIndex,- snoozedCount: threadListV2Layout.snoozedCount,- snoozedShelfExpanded,- snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,- settledCount: threadListV2Layout.settledCount,- settledShelfExpanded,- settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,- snoozeLabelNow: `${nowMinute}:00.000Z`,- snoozeEnvironmentIds,- queuedThreadKeys,- moveAvailability: threadMoveAvailability,- shelfPreferencesLoading: !shelfPreferencesLoaded,- }),- [- nowMinute,- queuedThreadKeys,- threadMoveAvailability,- settledShelfExpanded,- shelfPreferencesLoaded,- snoozedShelfExpanded,- snoozeEnvironmentIds,- threadListV2Layout,- v2PendingTasks,- workingShelfExpanded,- ],+ const v2PendingTasks = props.pendingTasks.filter(+ (pendingTask) =>+ (props.selectedEnvironmentId === null ||+ pendingTask.environmentId === props.selectedEnvironmentId) &&+ (v2ScopedProjectKeys === null ||+ v2ScopedProjectKeys.has(+ scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),+ )) &&+ (v2SearchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),);+ const threadListV2Items = buildThreadListV2ListItems({+ items: threadListV2Layout.items,+ pendingTasks: v2PendingTasks,+ workingCount: threadListV2Layout.workingCount,+ workingShelfExpanded,+ workingShelfHeaderIndex: threadListV2Layout.workingShelfHeaderIndex,+ snoozedCount: threadListV2Layout.snoozedCount,+ snoozedShelfExpanded,+ snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,+ settledCount: threadListV2Layout.settledCount,+ settledShelfExpanded,+ settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,+ snoozeLabelNow: `${nowMinute}:00.000Z`,+ snoozeEnvironmentIds,+ queuedThreadKeys,+ moveAvailability: threadMoveAvailability,+ shelfPreferencesLoading: !shelfPreferencesLoaded,+ });useThreadJumpShortcuts(threadListV2Items, props.onSelectThread);useEffect(() => {if (swipeEnabled) activateVisibleRows(threadListV2Items);}, [activateVisibleRows, swipeEnabled, threadListV2Items]);- const renderV2Item = useCallback(- ({ item }: { readonly item: ThreadListV2ListItem }) => {- if (item.type === "v2-pending") {- const pendingScopeKey = scopedProjectKey(- item.pendingTask.environmentId,- item.pendingTask.projectId,- );- return (- <ThreadListV2PendingRow- pendingTask={item.pendingTask}- project={projectByKey.get(pendingScopeKey) ?? null}- projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}- environmentLabel={- Object.keys(props.savedConnectionsById).length > 1- ? (props.savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ??- null)- : null- }- environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}- showPendingDivider={item.showPendingDivider}- showTrailingDivider={item.showTrailingDivider}- onSelectPendingTask={props.onSelectPendingTask}- onDeletePendingTask={props.onDeletePendingTask}- />- );- }- if (item.type === "v2-working-shelf") {- return (- <ThreadListV2WorkingShelfHeader- count={item.count}- disabled={item.disabled}- expanded={item.expanded}- onToggle={toggleWorkingShelf}- />- );- }- if (item.type === "v2-snoozed-shelf") {- return (- <ThreadListV2SnoozedShelfHeader- count={item.count}- disabled={item.disabled}- expanded={item.expanded}- onToggle={toggleSnoozedShelf}- />- );- }- if (item.type === "v2-settled-shelf") {- return (- <ThreadListV2SettledShelfHeader- count={item.count}- disabled={item.disabled}- expanded={item.expanded}- onToggle={toggleSettledShelf}- />- );- }- const thread = item.item.thread;+ const renderV2Item = ({ item }: { readonly item: ThreadListV2ListItem }) => {+ if (item.type === "v2-pending") {+ const pendingScopeKey = scopedProjectKey(+ item.pendingTask.environmentId,+ item.pendingTask.projectId,+ );return (- <ThreadListV2Row- pane={primaryColumn ? "sidebar" : "screen"}- selected={scopedThreadKey(thread.environmentId, thread.id) === selectedThreadKey}- fullSwipeWidth={fullSwipeWidth}- 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}- showTrailingDivider={item.showTrailingDivider}- project={- projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null- }- projectTitle={v2ProjectTitleByProjectKey.get(- scopedProjectKey(thread.environmentId, thread.projectId),- )}- providerInstance={resolveProviderInstance(thread)}- providers={providersByEnvironmentId.get(thread.environmentId)}+ <ThreadListV2PendingRow+ pendingTask={item.pendingTask}+ project={projectByKey.get(pendingScopeKey) ?? null}+ projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}environmentLabel={Object.keys(props.savedConnectionsById).length > 1- ? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)+ ? (props.savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ??+ null): null}- environmentMachine={machineByEnvironmentId.get(thread.environmentId)}- searchMatch={threadSearchMatchByKey.get(- threadSearchMatchKey({- environmentId: thread.environmentId,- threadId: thread.id,- }),- )}- searchQuery={props.searchQuery}- onSelectThread={props.onSelectThread}- onOpenThreadPullRequests={handleOpenThreadPullRequests}- onDeleteThread={handleDeleteThread}- onArchiveThread={props.onArchiveThread}- onRenameThread={handleRenameThread}- onRegenerateThreadTitle={handleRegenerateThreadTitle}- titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}- settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}- onSettleThread={handleSettleThread}- 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={handleSnoozeThread}- onUnsnoozeThread={handleUnsnoozeThread}- onUnsettleThread={handleUnsettleThread}- onPinThread={handlePinThread}- onUnpinThread={handleUnpinThread}- onSetThreadAutoSettle={handleSetThreadAutoSettle}- onMoveThread={handleMoveThread}- onSwipeableClose={handleSwipeableClose}- onSwipeableWillOpen={handleSwipeableWillOpen}- simultaneousSwipeGesture={homeScrollGesture}- activationKey={item.key}+ environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}+ showPendingDivider={item.showPendingDivider}+ showTrailingDivider={item.showTrailingDivider}+ onSelectPendingTask={props.onSelectPendingTask}+ onDeletePendingTask={props.onDeletePendingTask}/>);- },- [- handleDeleteThread,- handleOpenThreadPullRequests,- activeReorderEnvironmentIds,- handleMoveThread,- handlePinThread,- handleRegenerateThreadTitle,- handleRenameThread,- handleSettleThread,- handleSnoozeThread,- handleUnpinThread,- handleUnsnoozeThread,- handleSwipeableClose,- handleSwipeableWillOpen,- handleUnsettleThread,- handleSetThreadAutoSettle,- homeScrollGesture,- autoSettleOptOutEnvironmentIds,- pinningEnvironmentIds,- autoSettleOptOutEnvironmentIds,- machineByEnvironmentId,- pinReorderEnvironmentIds,- projectByKey,- props.onArchiveThread,- props.onDeletePendingTask,- props.onSelectPendingTask,- props.onSelectThread,- primaryColumn,- selectedThreadKey,- fullSwipeWidth,- props.onNewThreadOnBranch,- props.savedConnectionsById,- resolveProviderInstance,- providersByEnvironmentId,- settlementEnvironmentIds,- snoozeEnvironmentIds,- threadSearchMatchByKey,- titleRegenerationEnvironmentIds,- toggleSettledShelf,- toggleSnoozedShelf,- toggleWorkingShelf,- v2ProjectTitleByProjectKey,- props.searchQuery,- workingShelfEnabled,- ],- );- const v2KeyExtractor = useCallback((item: ThreadListV2ListItem) => item.key, []);+ }+ if (item.type === "v2-working-shelf") {+ return (+ <ThreadListV2WorkingShelfHeader+ count={item.count}+ disabled={item.disabled}+ expanded={item.expanded}+ onToggle={toggleWorkingShelf}+ />+ );+ }+ if (item.type === "v2-snoozed-shelf") {+ return (+ <ThreadListV2SnoozedShelfHeader+ count={item.count}+ disabled={item.disabled}+ expanded={item.expanded}+ onToggle={toggleSnoozedShelf}+ />+ );+ }+ if (item.type === "v2-settled-shelf") {+ return (+ <ThreadListV2SettledShelfHeader+ count={item.count}+ disabled={item.disabled}+ expanded={item.expanded}+ onToggle={toggleSettledShelf}+ />+ );+ }+ const thread = item.item.thread;+ return (+ <ThreadListV2Row+ pane={primaryColumn ? "sidebar" : "screen"}+ selected={scopedThreadKey(thread.environmentId, thread.id) === selectedThreadKey}+ fullSwipeWidth={fullSwipeWidth}+ 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}+ showTrailingDivider={item.showTrailingDivider}+ project={projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null}+ projectTitle={v2ProjectTitleByProjectKey.get(+ scopedProjectKey(thread.environmentId, thread.projectId),+ )}+ providerInstance={resolveProviderInstance(thread)}+ providers={providersByEnvironmentId.get(thread.environmentId)}+ environmentLabel={+ Object.keys(props.savedConnectionsById).length > 1+ ? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)+ : null+ }+ environmentMachine={machineByEnvironmentId.get(thread.environmentId)}+ searchMatch={threadSearchMatchByKey.get(+ threadSearchMatchKey({+ environmentId: thread.environmentId,+ threadId: thread.id,+ }),+ )}+ searchQuery={props.searchQuery}+ onSelectThread={props.onSelectThread}+ onOpenThreadPullRequests={handleOpenThreadPullRequests}+ onDeleteThread={handleDeleteThread}+ onArchiveThread={props.onArchiveThread}+ onRenameThread={handleRenameThread}+ onRegenerateThreadTitle={handleRegenerateThreadTitle}+ titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}+ settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}+ onSettleThread={handleSettleThread}+ 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={handleSnoozeThread}+ onUnsnoozeThread={handleUnsnoozeThread}+ onUnsettleThread={handleUnsettleThread}+ onPinThread={handlePinThread}+ onUnpinThread={handleUnpinThread}+ onSetThreadAutoSettle={handleSetThreadAutoSettle}+ onMoveThread={handleMoveThread}+ onSwipeableClose={handleSwipeableClose}+ onSwipeableWillOpen={handleSwipeableWillOpen}+ simultaneousSwipeGesture={homeScrollGesture}+ activationKey={item.key}+ />+ );+ };+ const v2KeyExtractor = (item: ThreadListV2ListItem) => item.key;// FlatList/LegendList treat a changed extraData identity as "re-render every// visible row", so an inline object literal would invalidate all rows on// every HomeScreen render — and the minute clock must stay out of it for// the same reason: the clock text is precomputed per item instead.- const v2ExtraData = useMemo(- () => ({- projectByKey,- projectTitleByProjectKey: v2ProjectTitleByProjectKey,- listEnvironments,- savedConnectionsById: props.savedConnectionsById,- searchQuery: props.searchQuery,- selectedThreadKey,- threadSearchMatchByKey,- workingShelfEnabled,- }),- [- projectByKey,- props.searchQuery,- selectedThreadKey,- props.savedConnectionsById,- listEnvironments,- threadSearchMatchByKey,- v2ProjectTitleByProjectKey,- workingShelfEnabled,- ],- );+ const v2ExtraData = {+ projectByKey,+ projectTitleByProjectKey: v2ProjectTitleByProjectKey,+ listEnvironments,+ savedConnectionsById: props.savedConnectionsById,+ searchQuery: props.searchQuery,+ selectedThreadKey,+ threadSearchMatchByKey,+ workingShelfEnabled,+ };const hasAnyThreads =props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;diff --git a/apps/mobile/src/features/home/WorkspaceConnectionTitle.tsx b/apps/mobile/src/features/home/WorkspaceConnectionTitle.tsxindex 774f725b2b1..f1b9bfd5b92 100644--- a/apps/mobile/src/features/home/WorkspaceConnectionTitle.tsx+++ b/apps/mobile/src/features/home/WorkspaceConnectionTitle.tsx@@ -1,5 +1,5 @@import type { NativeStackNavigationOptions } from "@react-navigation/native-stack";-import { useEffect, useRef, useState, type ReactNode } from "react";+import { useEffect, useState, type ReactNode } from "react";import { Animated, Platform, Pressable, View } from "react-native";import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";@@ -49,7 +49,7 @@ function StatusFadeIn(props: {readonly grow?: boolean;readonly maxWidth?: number;}) {- const opacity = useRef(new Animated.Value(0)).current;+ const [opacity] = useState(() => new Animated.Value(0));useEffect(() => {const animation = Animated.timing(opacity, {diff --git a/apps/mobile/src/features/home/home-list-options.ts b/apps/mobile/src/features/home/home-list-options.tsindex 078b0bc54e3..9ee8cadf676 100644--- a/apps/mobile/src/features/home/home-list-options.ts+++ b/apps/mobile/src/features/home/home-list-options.ts@@ -4,10 +4,8 @@ import { useAtomSet } from "@effect/atom-react";import {createContext,createElement,- useCallback,useContext,useEffect,- useMemo,useRef,useState,type PropsWithChildren,@@ -69,10 +67,7 @@ export function HomeListOptionsProvider({saved.current = { environmentId, projectKey };savePreferences({ threadListFilters: saved.current });}, [environmentId, projectKey, savePreferences]);- const value = useMemo(- () => ({ options, setOptions, projectGroupingMode }),- [options, projectGroupingMode],- );+ const value = { options, setOptions, projectGroupingMode };return createElement(HomeListOptionsContext, { value }, children);}@@ -95,18 +90,15 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<EnvironmprojectGroupingMode: shared?.projectGroupingMode ?? "repository",};- const setSelectedEnvironmentId = useCallback((value: EnvironmentId | null) => {+ const setSelectedEnvironmentId = (value: EnvironmentId | null) => {setOptions((current) => ({ ...current, selectedEnvironmentId: value }));- }, []);- const setSelectedProjectKey = useCallback(- (value: string | null) => {- setOptions((current) => ({ ...current, selectedProjectKey: value }));- },- [setOptions],- );- const setProjectSortOrder = useCallback((value: HomeProjectSortOrder) => {+ };+ const setSelectedProjectKey = (value: string | null) => {+ setOptions((current) => ({ ...current, selectedProjectKey: value }));+ };+ const setProjectSortOrder = (value: HomeProjectSortOrder) => {setOptions((current) => ({ ...current, projectSortOrder: value }));- }, []);+ };return {options: resolvedOptions,setSelectedEnvironmentId,diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.tsindex 71b4383132d..4ca0fc56140 100644--- a/apps/mobile/src/features/home/useThreadListActions.ts+++ b/apps/mobile/src/features/home/useThreadListActions.ts@@ -4,7 +4,7 @@ import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/threaimport { AuthOrchestrationOperateScope } from "@t3tools/contracts";import * as Cause from "effect/Cause";import * as Haptics from "expo-haptics";-import { useCallback, useRef } from "react";+import { useRef } from "react";import { withThreadDismissal } from "./thread-dismissal";import * as Dialog from "../../components/ui/Dialog";@@ -125,104 +125,92 @@ function useThreadActionExecutor(const unsettleMutation = useAtomCommand(threadEnvironment.unsettle, { reportFailure: false });const inFlightThreadKeys = useRef(new Set<string>());- const executeAction = useCallback(- async (action: ThreadListAction, thread: EnvironmentThreadShell) => {- if (!checkThreadOperationPermission(thread, actionFailureTitle(action))) return false;- const key = scopedThreadKey(thread.environmentId, thread.id);- if (inFlightThreadKeys.current.has(key)) {+ const executeAction = async (action: ThreadListAction, thread: EnvironmentThreadShell) => {+ if (!checkThreadOperationPermission(thread, actionFailureTitle(action))) return false;+ const key = scopedThreadKey(thread.environmentId, thread.id);+ if (inFlightThreadKeys.current.has(key)) {+ return false;+ }++ inFlightThreadKeys.current.add(key);+ selectionHaptic();+ const succeeded = await (async () => {+ if (+ (action === "settle" || action === "unsettle") &&+ !environmentSupportsSettlement(thread.environmentId)+ ) {+ Dialog.alert(+ actionFailureTitle(action),+ "This environment's server does not support settling yet. Update the server to use Settle.",+ );return false;}-- inFlightThreadKeys.current.add(key);- selectionHaptic();- try {- if (- (action === "settle" || action === "unsettle") &&- !environmentSupportsSettlement(thread.environmentId)- ) {- Dialog.alert(- actionFailureTitle(action),- "This environment's server does not support settling yet. Update the server to use Settle.",- );- return false;- }- if (action === "archive" && !threadCanArchive(thread.runtime)) {- Dialog.alert(- actionFailureTitle(action),- "This thread is working. Interrupt it first, then try again.",- );- return false;- }- const result = await withThreadDismissal(- key,- async () =>- action === "unsettle"- ? // reason "user" pins the thread active: auto-settle stays- // suppressed until real activity clears the pin server-side.- await unsettleMutation({- environmentId: thread.environmentId,- input: { threadId: thread.id, reason: "user" },- })- : await (- action === "settle"- ? settleMutation- : action === "archive"- ? archiveMutation- : action === "unarchive"- ? unarchiveMutation- : deleteMutation- )({- environmentId: thread.environmentId,- input: { threadId: thread.id },- }),- (result) => result._tag === "Success",+ if (action === "archive" && !threadCanArchive(thread.runtime)) {+ Dialog.alert(+ actionFailureTitle(action),+ "This thread is working. Interrupt it first, then try again.",);- if (result._tag === "Failure") {- Dialog.alert(actionFailureTitle(action), actionFailureMessage(action, result.cause));- return false;- }- if (action === "archive" || action === "unarchive" || action === "delete") {- refreshArchivedThreadsForEnvironment(thread.environmentId);- }- onCompleted?.(action, thread);- return true;- } finally {- inFlightThreadKeys.current.delete(key);+ return false;}- },- [- archiveMutation,- deleteMutation,- onCompleted,- settleMutation,- unarchiveMutation,- unsettleMutation,- ],- );+ const result = await withThreadDismissal(+ key,+ async () =>+ action === "unsettle"+ ? // reason "user" pins the thread active: auto-settle stays+ // suppressed until real activity clears the pin server-side.+ await unsettleMutation({+ environmentId: thread.environmentId,+ input: { threadId: thread.id, reason: "user" },+ })+ : await (+ action === "settle"+ ? settleMutation+ : action === "archive"+ ? archiveMutation+ : action === "unarchive"+ ? unarchiveMutation+ : deleteMutation+ )({+ environmentId: thread.environmentId,+ input: { threadId: thread.id },+ }),+ (result) => result._tag === "Success",+ );+ if (result._tag === "Failure") {+ Dialog.alert(actionFailureTitle(action), actionFailureMessage(action, result.cause));+ return false;+ }+ if (action === "archive" || action === "unarchive" || action === "delete") {+ refreshArchivedThreadsForEnvironment(thread.environmentId);+ }+ onCompleted?.(action, thread);+ return true;+ })();+ inFlightThreadKeys.current.delete(key);+ return succeeded;+ };return executeAction;}-function useConfirmDeleteThread(+// A plain function, not a hook: a `use*` function that calls no hooks is skipped by+// the compiler, so the delete handler it returned was a new closure every render.+function confirmThreadDeletion(executeAction: (action: ThreadListAction, thread: EnvironmentThreadShell) => Promise<boolean>,+ thread: EnvironmentThreadShell,) {- return useCallback(- (thread: EnvironmentThreadShell) => {- if (!checkThreadOperationPermission(thread, actionFailureTitle("delete"))) return;- const title = "Delete thread?";- const message = `“${thread.title}” will be permanently deleted, including its terminal history.`;- Dialog.confirm({- title,- message,- confirmText: "Delete",- destructive: true,- onConfirm: () => {- void executeAction("delete", thread);- },- });+ if (!checkThreadOperationPermission(thread, actionFailureTitle("delete"))) return;+ const title = "Delete thread?";+ const message = `“${thread.title}” will be permanently deleted, including its terminal history.`;+ Dialog.confirm({+ title,+ message,+ confirmText: "Delete",+ destructive: true,+ onConfirm: () => {+ void executeAction("delete", thread);},- [executeAction],- );+ });}export function useThreadListActions(): {@@ -259,296 +247,265 @@ export function useThreadListActions(): {const snoozeInFlightThreadKeys = useRef(new Set<string>());const titleRegenerationInFlightThreadKeys = useRef(new Set<string>());- const archiveThread = useCallback(- (thread: EnvironmentThreadShell) => {- void executeAction("archive", thread);- },- [executeAction],- );- const settleThread = useCallback(- async (thread: EnvironmentThreadShell) => (await executeAction("settle", thread)) === true,- [executeAction],- );- const snoozeThread = useCallback(- async (thread: EnvironmentThreadShell, snoozedUntil: string) => {- if (!checkThreadOperationPermission(thread, "Could not snooze thread")) return false;- const key = scopedThreadKey(thread.environmentId, thread.id);- if (snoozeInFlightThreadKeys.current.has(key)) {- return false;- }- snoozeInFlightThreadKeys.current.add(key);- try {- if (!environmentSupportsSnooze(thread.environmentId)) {- Dialog.alert(- "Could not snooze thread",- "This environment's server does not support snoozing yet. Update the server to use Snooze.",- );- return false;- }- if (!canSnooze(thread, { now: new Date().toISOString() })) {- Dialog.alert(- "Could not snooze thread",- thread.hasPendingApprovals ||- thread.hasPendingUserInput ||- thread.pendingSubagentRequest != null- ? "This thread is waiting on you. Respond to the pending request before snoozing it."- : "This thread is still starting a turn. Try again once it's running.",- );- return false;- }-- selectionHaptic();- const result = await withThreadDismissal(- key,- () =>- snoozeMutation({- environmentId: thread.environmentId,- input: {- threadId: thread.id,- snoozedUntil,- },- }),- (result) => result._tag === "Success",+ const archiveThread = (thread: EnvironmentThreadShell) => {+ void executeAction("archive", thread);+ };+ const settleThread = async (thread: EnvironmentThreadShell) =>+ (await executeAction("settle", thread)) === true;+ const snoozeThread = async (thread: EnvironmentThreadShell, snoozedUntil: string) => {+ if (!checkThreadOperationPermission(thread, "Could not snooze thread")) return false;+ const key = scopedThreadKey(thread.environmentId, thread.id);+ if (snoozeInFlightThreadKeys.current.has(key)) {+ return false;+ }+ snoozeInFlightThreadKeys.current.add(key);+ const succeeded = await (async () => {+ if (!environmentSupportsSnooze(thread.environmentId)) {+ Dialog.alert(+ "Could not snooze thread",+ "This environment's server does not support snoozing yet. Update the server to use Snooze.",);- if (result._tag === "Failure") {- const error = Cause.squash(result.cause);- Dialog.alert(- "Could not snooze thread",- error instanceof Error && error.message.trim().length > 0- ? error.message- : "The thread could not be snoozed.",- );- return false;- }- return true;- } finally {- snoozeInFlightThreadKeys.current.delete(key);- }- },- [snoozeMutation],- );- const unsnoozeThread = useCallback(- async (thread: EnvironmentThreadShell) => {- if (!checkThreadOperationPermission(thread, "Could not wake thread")) return false;- const key = scopedThreadKey(thread.environmentId, thread.id);- if (snoozeInFlightThreadKeys.current.has(key)) {return false;}- snoozeInFlightThreadKeys.current.add(key);- try {- if (!environmentSupportsSnooze(thread.environmentId)) {- Dialog.alert(- "Could not wake thread",- "This environment's server does not support snoozing yet. Update the server to wake this thread.",- );- return false;- }-- selectionHaptic();- const result = await withThreadDismissal(- key,- () =>- unsnoozeMutation({- environmentId: thread.environmentId,- input: { threadId: thread.id, reason: "user" },- }),- (result) => result._tag === "Success",- );- if (result._tag === "Failure") {- const error = Cause.squash(result.cause);- Dialog.alert(- "Could not wake thread",- error instanceof Error && error.message.trim().length > 0- ? error.message- : "The thread could not be woken.",- );- return false;- }- return true;- } finally {- snoozeInFlightThreadKeys.current.delete(key);- }- },- [unsnoozeMutation],- );- const unsettleThread = useCallback(- async (thread: EnvironmentThreadShell) => (await executeAction("unsettle", thread)) === true,- [executeAction],- );- const pinThread = useCallback(- async (thread: EnvironmentThreadShell) => {- if (!checkThreadOperationPermission(thread, "Could not pin thread")) return false;- if (!environmentSupportsPinning(thread.environmentId)) {+ if (!canSnooze(thread, { now: new Date().toISOString() })) {Dialog.alert(- "Could not pin thread",- "This environment's server does not support pinning yet. Update the server to use Pin.",+ "Could not snooze thread",+ thread.hasPendingApprovals ||+ thread.hasPendingUserInput ||+ thread.pendingSubagentRequest != null+ ? "This thread is waiting on you. Respond to the pending request before snoozing it."+ : "This thread is still starting a turn. Try again once it's running.",);return false;}+selectionHaptic();- // Same placement as web: a fresh pin takes the top of the arranged- // run. Servers that predate reordering get the bare pin (keyless).- let orderKey: string | undefined;- if (environmentSupportsPinReorder(thread.environmentId)) {- const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);- let firstKey: string | null = null;- for (const shell of shells) {- if (shell.pinnedAt == null || shell.pinOrderKey == null) continue;- if (firstKey === null || shell.pinOrderKey < firstKey) firstKey = shell.pinOrderKey;- }- orderKey = pinOrderKeyBetween(null, firstKey) ?? undefined;- }- const result = await pinMutation({- environmentId: thread.environmentId,- input: { threadId: thread.id, ...(orderKey !== undefined ? { orderKey } : {}) },- });+ const result = await withThreadDismissal(+ key,+ () =>+ snoozeMutation({+ environmentId: thread.environmentId,+ input: {+ threadId: thread.id,+ snoozedUntil,+ },+ }),+ (result) => result._tag === "Success",+ );if (result._tag === "Failure") {const error = Cause.squash(result.cause);Dialog.alert(- "Could not pin thread",+ "Could not snooze thread",error instanceof Error && error.message.trim().length > 0? error.message- : "The thread could not be pinned.",+ : "The thread could not be snoozed.",);return false;}return true;- },- [pinMutation],- );- const unpinThread = useCallback(- async (thread: EnvironmentThreadShell) => {- if (!checkThreadOperationPermission(thread, "Could not unpin thread")) return false;- if (!environmentSupportsPinning(thread.environmentId)) {+ })();+ snoozeInFlightThreadKeys.current.delete(key);+ return succeeded;+ };+ const unsnoozeThread = async (thread: EnvironmentThreadShell) => {+ if (!checkThreadOperationPermission(thread, "Could not wake thread")) return false;+ const key = scopedThreadKey(thread.environmentId, thread.id);+ if (snoozeInFlightThreadKeys.current.has(key)) {+ return false;+ }+ snoozeInFlightThreadKeys.current.add(key);+ const succeeded = await (async () => {+ if (!environmentSupportsSnooze(thread.environmentId)) {Dialog.alert(- "Could not unpin thread",- "This environment's server does not support pinning yet. Update the server to use Pin.",+ "Could not wake thread",+ "This environment's server does not support snoozing yet. Update the server to wake this thread.",);return false;}+selectionHaptic();- const result = await unpinMutation({- environmentId: thread.environmentId,- input: { threadId: thread.id },- });+ const result = await withThreadDismissal(+ key,+ () =>+ unsnoozeMutation({+ environmentId: thread.environmentId,+ input: { threadId: thread.id, reason: "user" },+ }),+ (result) => result._tag === "Success",+ );if (result._tag === "Failure") {const error = Cause.squash(result.cause);Dialog.alert(- "Could not unpin thread",+ "Could not wake thread",error instanceof Error && error.message.trim().length > 0? error.message- : "The thread could not be unpinned.",+ : "The thread could not be woken.",);return false;}return true;- },- [unpinMutation],- );- const setThreadAutoSettle = useCallback(- async (thread: EnvironmentThreadShell, enabled: boolean) => {- if (!environmentSupportsAutoSettleOptOut(thread.environmentId)) {- Dialog.alert(- "Could not update auto-settle",- "This environment's server does not support turning auto-settle off per thread yet. Update the server to use it.",- );- return false;+ })();+ snoozeInFlightThreadKeys.current.delete(key);+ return succeeded;+ };+ const unsettleThread = async (thread: EnvironmentThreadShell) =>+ (await executeAction("unsettle", thread)) === true;+ const pinThread = async (thread: EnvironmentThreadShell) => {+ if (!checkThreadOperationPermission(thread, "Could not pin thread")) return false;+ if (!environmentSupportsPinning(thread.environmentId)) {+ Dialog.alert(+ "Could not pin thread",+ "This environment's server does not support pinning yet. Update the server to use Pin.",+ );+ return false;+ }+ selectionHaptic();+ // Same placement as web: a fresh pin takes the top of the arranged+ // run. Servers that predate reordering get the bare pin (keyless).+ let orderKey: string | undefined;+ if (environmentSupportsPinReorder(thread.environmentId)) {+ const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);+ let firstKey: string | null = null;+ for (const shell of shells) {+ if (shell.pinnedAt == null || shell.pinOrderKey == null) continue;+ if (firstKey === null || shell.pinOrderKey < firstKey) firstKey = shell.pinOrderKey;}- selectionHaptic();- const result = await setAutoSettleMutation({+ orderKey = pinOrderKeyBetween(null, firstKey) ?? undefined;+ }+ const result = await pinMutation({+ environmentId: thread.environmentId,+ input: { threadId: thread.id, ...(orderKey !== undefined ? { orderKey } : {}) },+ });+ if (result._tag === "Failure") {+ const error = Cause.squash(result.cause);+ Dialog.alert(+ "Could not pin thread",+ error instanceof Error && error.message.trim().length > 0+ ? error.message+ : "The thread could not be pinned.",+ );+ return false;+ }+ return true;+ };+ const unpinThread = async (thread: EnvironmentThreadShell) => {+ if (!checkThreadOperationPermission(thread, "Could not unpin thread")) return false;+ if (!environmentSupportsPinning(thread.environmentId)) {+ Dialog.alert(+ "Could not unpin thread",+ "This environment's server does not support pinning yet. Update the server to use Pin.",+ );+ return false;+ }+ selectionHaptic();+ const result = await unpinMutation({+ environmentId: thread.environmentId,+ input: { threadId: thread.id },+ });+ if (result._tag === "Failure") {+ const error = Cause.squash(result.cause);+ Dialog.alert(+ "Could not unpin thread",+ error instanceof Error && error.message.trim().length > 0+ ? error.message+ : "The thread could not be unpinned.",+ );+ return false;+ }+ return true;+ };+ const setThreadAutoSettle = async (thread: EnvironmentThreadShell, enabled: boolean) => {+ if (!environmentSupportsAutoSettleOptOut(thread.environmentId)) {+ Dialog.alert(+ "Could not update auto-settle",+ "This environment's server does not support turning auto-settle off per thread yet. Update the server to use it.",+ );+ return false;+ }+ selectionHaptic();+ const result = await setAutoSettleMutation({+ environmentId: thread.environmentId,+ input: { threadId: thread.id, enabled },+ });+ if (result._tag === "Failure") {+ const error = Cause.squash(result.cause);+ Dialog.alert(+ "Could not update auto-settle",+ error instanceof Error && error.message.trim().length > 0+ ? error.message+ : "The auto-settle setting could not be changed.",+ );+ return false;+ }+ return true;+ };+ const regenerateThreadTitle = async (thread: EnvironmentThreadShell) => {+ if (!checkThreadOperationPermission(thread, "Could not regenerate title")) return false;+ const key = scopedThreadKey(thread.environmentId, thread.id);+ if (thread.titleRegeneration != null || titleRegenerationInFlightThreadKeys.current.has(key)) {+ return false;+ }+ if (!environmentSupportsTitleRegeneration(thread.environmentId)) {+ Dialog.alert(+ "Could not regenerate title",+ "This environment's server does not support title regeneration yet. Update the server to regenerate thread titles.",+ );+ return false;+ }++ titleRegenerationInFlightThreadKeys.current.add(key);+ selectionHaptic();+ const succeeded = await (async () => {+ const result = await updateThreadMetadata({environmentId: thread.environmentId,- input: { threadId: thread.id, enabled },+ input: { threadId: thread.id, regenerateTitle: true },});if (result._tag === "Failure") {const error = Cause.squash(result.cause);Dialog.alert(- "Could not update auto-settle",+ "Could not regenerate title",error instanceof Error && error.message.trim().length > 0? error.message- : "The auto-settle setting could not be changed.",+ : "The thread title could not be regenerated.",);return false;}return true;- },- [setAutoSettleMutation],- );- const regenerateThreadTitle = useCallback(- async (thread: EnvironmentThreadShell) => {- if (!checkThreadOperationPermission(thread, "Could not regenerate title")) return false;- const key = scopedThreadKey(thread.environmentId, thread.id);- if (- thread.titleRegeneration != null ||- titleRegenerationInFlightThreadKeys.current.has(key)- ) {- return false;+ })();+ titleRegenerationInFlightThreadKeys.current.delete(key);+ return succeeded;+ };+ const renameThread = (thread: EnvironmentThreadShell) => {+ const commit = (title: string) => {+ const resolution = resolveThreadTitleRename({ title, originalTitle: thread.title });+ if (resolution.action === "reject-empty") {+ Dialog.alert("Could not rename thread", "Thread title cannot be empty.");+ return;}- if (!environmentSupportsTitleRegeneration(thread.environmentId)) {+ if (resolution.action === "noop") return;+ selectionHaptic();+ void updateThreadMetadata({+ environmentId: thread.environmentId,+ input: { threadId: thread.id, title: resolution.title },+ }).then((result) => {+ if (result._tag === "Success") return;+ const error = Cause.squash(result.cause);Dialog.alert(- "Could not regenerate title",- "This environment's server does not support title regeneration yet. Update the server to regenerate thread titles.",+ "Could not rename thread",+ error instanceof Error && error.message.trim().length > 0+ ? error.message+ : "The thread could not be renamed.",);- return false;- }-- titleRegenerationInFlightThreadKeys.current.add(key);- selectionHaptic();- try {- const result = await updateThreadMetadata({- environmentId: thread.environmentId,- input: { threadId: thread.id, regenerateTitle: true },- });- if (result._tag === "Failure") {- const error = Cause.squash(result.cause);- Dialog.alert(- "Could not regenerate title",- error instanceof Error && error.message.trim().length > 0- ? error.message- : "The thread title could not be regenerated.",- );- return false;- }- return true;- } finally {- titleRegenerationInFlightThreadKeys.current.delete(key);- }- },- [updateThreadMetadata],- );- const renameThread = useCallback(- (thread: EnvironmentThreadShell) => {- const commit = (title: string) => {- const resolution = resolveThreadTitleRename({ title, originalTitle: thread.title });- if (resolution.action === "reject-empty") {- Dialog.alert("Could not rename thread", "Thread title cannot be empty.");- return;- }- if (resolution.action === "noop") return;- selectionHaptic();- void updateThreadMetadata({- environmentId: thread.environmentId,- input: { threadId: thread.id, title: resolution.title },- }).then((result) => {- if (result._tag === "Success") return;- const error = Cause.squash(result.cause);- Dialog.alert(- "Could not rename thread",- error instanceof Error && error.message.trim().length > 0- ? error.message- : "The thread could not be renamed.",- );- });- };-- Dialog.prompt({- title: "Rename thread",- initialValue: thread.title,- confirmText: "Rename",- onConfirm: commit,});- },- [updateThreadMetadata],- );+ };++ Dialog.prompt({+ title: "Rename thread",+ initialValue: thread.title,+ confirmText: "Rename",+ onConfirm: commit,+ });+ };// Plan against the complete section so filtering does not change a move.const reorderPinnedMutation = useAtomCommand(threadEnvironment.reorderPin, {@@ -557,172 +514,157 @@ export function useThreadListActions(): {const reorderActiveMutation = useAtomCommand(threadEnvironment.reorderActive, {reportFailure: false,});- const moveThread = useCallback(- async (thread: EnvironmentThreadShell, direction: ThreadMoveDestination) => {- if (!checkThreadOperationPermission(thread, "Could not move thread")) return false;- if (getPendingThreadOrder() !== null || appAtomRegistry.get(threadDropBusyAtom)) return false;- const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);- const current = shells.find(- (row) => row.id === thread.id && row.environmentId === thread.environmentId,+ const moveThread = async (thread: EnvironmentThreadShell, direction: ThreadMoveDestination) => {+ if (!checkThreadOperationPermission(thread, "Could not move thread")) return false;+ if (getPendingThreadOrder() !== null || appAtomRegistry.get(threadDropBusyAtom)) return false;+ const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);+ const current = shells.find(+ (row) => row.id === thread.id && row.environmentId === thread.environmentId,+ );+ if (!current || current.archivedAt !== null) return false;+ thread = current;+ const section =+ typeof direction === "object" && direction.section !== undefined+ ? direction.section+ : thread.pinnedAt != null+ ? "pinned"+ : "active";+ if (section === "settled") {+ if (!environmentSupportsSettlement(thread.environmentId)) return false;+ appAtomRegistry.set(threadDropBusyAtom, true);+ const settled = await settleThread(thread);+ appAtomRegistry.set(threadDropBusyAtom, false);+ return settled;+ }+ const configs = appAtomRegistry.get(environmentServerConfigsAtom);+ const supportsReorder = (environmentId: EnvironmentThreadShell["environmentId"]) => {+ const capabilities = configs.get(environmentId)?.environment.capabilities;+ return section === "pinned"+ ? capabilities?.threadPinReorder === true+ : capabilities?.threadActiveReorder === true;+ };+ if (!supportsReorder(thread.environmentId)) {+ Dialog.alert(+ "Could not move thread",+ "This environment's server does not support reordering these threads. Update the server to arrange them.",);- if (!current || current.archivedAt !== null) return false;- thread = current;- const section =- typeof direction === "object" && direction.section !== undefined- ? direction.section- : thread.pinnedAt != null- ? "pinned"- : "active";- if (section === "settled") {- if (!environmentSupportsSettlement(thread.environmentId)) return false;- appAtomRegistry.set(threadDropBusyAtom, true);- try {- return await settleThread(thread);- } finally {- appAtomRegistry.set(threadDropBusyAtom, false);- }- }- const configs = appAtomRegistry.get(environmentServerConfigsAtom);- const supportsReorder = (environmentId: EnvironmentThreadShell["environmentId"]) => {- const capabilities = configs.get(environmentId)?.environment.capabilities;- return section === "pinned"- ? capabilities?.threadPinReorder === true- : capabilities?.threadActiveReorder === true;- };- if (!supportsReorder(thread.environmentId)) {- Dialog.alert(- "Could not move thread",- "This environment's server does not support reordering these threads. Update the server to arrange them.",- );- return false;- }- const ordered = getThreadListV2OrderedSection({- threads: shells,- section,- now: new Date().toISOString(),- queuedThreadKeys: appAtomRegistry.get(queuedThreadKeysAtom),- settlementEnvironmentIds: new Set(- [...configs].flatMap(([id, config]) =>- config.environment.capabilities.threadSettlement === true ? [id] : [],- ),+ return false;+ }+ const ordered = getThreadListV2OrderedSection({+ threads: shells,+ section,+ now: new Date().toISOString(),+ queuedThreadKeys: appAtomRegistry.get(queuedThreadKeysAtom),+ settlementEnvironmentIds: new Set(+ [...configs].flatMap(([id, config]) =>+ config.environment.capabilities.threadSettlement === true ? [id] : [],),- snoozeEnvironmentIds: new Set(- [...configs].flatMap(([id, config]) =>- config.environment.capabilities.threadSnooze === true ? [id] : [],- ),+ ),+ snoozeEnvironmentIds: new Set(+ [...configs].flatMap(([id, config]) =>+ config.environment.capabilities.threadSnooze === true ? [id] : [],),- });- const assignments = createThreadMovePlanner({- allThreads: shells,- ordered,- section,- reorderableEnvironmentIds: new Set([...configs.keys()].filter(supportsReorder)),- })(scopedThreadKey(thread.environmentId, thread.id), direction);- if (assignments === null) return false;- const lifecycle = threadDropLifecycle(thread, section, new Date().toISOString());- const crossSection = !ordered.some(- (row) => row.id === thread.id && row.environmentId === thread.environmentId,- );- if (- crossSection &&- (((section === "pinned" || thread.pinnedAt != null) &&- !environmentSupportsPinning(thread.environmentId)) ||- (thread.settledOverride === "settled" &&- !environmentSupportsSettlement(thread.environmentId)) ||- (effectiveSnoozed(thread, { now: new Date().toISOString() }) &&- !environmentSupportsSnooze(thread.environmentId)))- )- return false;- const shellByKey = new Map(- shells.map((shell) => [scopedThreadKey(shell.environmentId, shell.id), shell]),- );- for (const assignment of assignments) {- const target = shellByKey.get(assignment.id);- if (target && !checkThreadOperationPermission(target, "Could not move thread"))- return false;- }- selectionHaptic();- appAtomRegistry.set(threadDropBusyAtom, true);- const pending = crossSection- ? null- : beginPendingThreadOrder(- createPendingThreadOrder({- section,- ordered,- movedId: scopedThreadKey(thread.environmentId, thread.id),- direction,- assignments,- }),- );- let succeeded = false;- const reorder = section === "pinned" ? reorderPinnedMutation : reorderActiveMutation;- try {- if (crossSection) {- if (section === "pinned") {- const orderKey = assignments.find(- ({ id }) => id === scopedThreadKey(thread.environmentId, thread.id),- )?.orderKey;- const result = await pinMutation({- environmentId: thread.environmentId,- input: { threadId: thread.id, ...(orderKey === undefined ? {} : { orderKey }) },- });- if (result._tag === "Failure") {- Dialog.alert("Could not pin thread", String(Cause.squash(result.cause)));- return false;- }- } else {- if (lifecycle.unpin && !(await unpinThread(thread))) return false;- if (lifecycle.unsettle && !(await unsettleThread(thread))) return false;- if (lifecycle.unsnooze && !(await unsnoozeThread(thread))) return false;- }- }- for (const assignment of assignments) {- if (- crossSection &&- section === "pinned" &&- thread.pinnedAt == null &&- assignment.id === scopedThreadKey(thread.environmentId, thread.id)- )- continue;- if (pending !== null && !pending.isPending()) return false;- const target = shellByKey.get(assignment.id);- if (target === undefined) continue;- if (!checkThreadOperationPermission(target, "Could not move thread")) return false;- const result = await reorder({- environmentId: target.environmentId,- input: { threadId: target.id, orderKey: assignment.orderKey },+ ),+ });+ const assignments = createThreadMovePlanner({+ allThreads: shells,+ ordered,+ section,+ reorderableEnvironmentIds: new Set([...configs.keys()].filter(supportsReorder)),+ })(scopedThreadKey(thread.environmentId, thread.id), direction);+ if (assignments === null) return false;+ const lifecycle = threadDropLifecycle(thread, section, new Date().toISOString());+ const crossSection = !ordered.some(+ (row) => row.id === thread.id && row.environmentId === thread.environmentId,+ );+ if (+ crossSection &&+ (((section === "pinned" || thread.pinnedAt != null) &&+ !environmentSupportsPinning(thread.environmentId)) ||+ (thread.settledOverride === "settled" &&+ !environmentSupportsSettlement(thread.environmentId)) ||+ (effectiveSnoozed(thread, { now: new Date().toISOString() }) &&+ !environmentSupportsSnooze(thread.environmentId)))+ )+ return false;+ const shellByKey = new Map(+ shells.map((shell) => [scopedThreadKey(shell.environmentId, shell.id), shell]),+ );+ for (const assignment of assignments) {+ const target = shellByKey.get(assignment.id);+ if (target && !checkThreadOperationPermission(target, "Could not move thread")) return false;+ }+ selectionHaptic();+ appAtomRegistry.set(threadDropBusyAtom, true);+ const pending = crossSection+ ? null+ : beginPendingThreadOrder(+ createPendingThreadOrder({+ section,+ ordered,+ movedId: scopedThreadKey(thread.environmentId, thread.id),+ direction,+ assignments,+ }),+ );+ const reorder = section === "pinned" ? reorderPinnedMutation : reorderActiveMutation;+ const moved = await (async () => {+ if (crossSection) {+ if (section === "pinned") {+ const orderKey = assignments.find(+ ({ id }) => id === scopedThreadKey(thread.environmentId, thread.id),+ )?.orderKey;+ const result = await pinMutation({+ environmentId: thread.environmentId,+ input: { threadId: thread.id, ...(orderKey === undefined ? {} : { orderKey }) },});if (result._tag === "Failure") {- const error = Cause.squash(result.cause);- Dialog.alert(- "Could not move thread",- error instanceof Error && error.message.trim().length > 0- ? error.message- : "The thread could not be moved.",- );+ Dialog.alert("Could not pin thread", String(Cause.squash(result.cause)));return false;}+ } else {+ if (lifecycle.unpin && !(await unpinThread(thread))) return false;+ if (lifecycle.unsettle && !(await unsettleThread(thread))) return false;+ if (lifecycle.unsnooze && !(await unsnoozeThread(thread))) return false;}- succeeded = true;- pending?.complete();- return true;- } finally {- if (!succeeded) pending?.cancel();- appAtomRegistry.set(threadDropBusyAtom, false);}- },- [- settleThread,- reorderActiveMutation,- reorderPinnedMutation,- pinMutation,- unpinThread,- unsettleThread,- unsnoozeThread,- ],- );+ for (const assignment of assignments) {+ if (+ crossSection &&+ section === "pinned" &&+ thread.pinnedAt == null &&+ assignment.id === scopedThreadKey(thread.environmentId, thread.id)+ )+ continue;+ if (pending !== null && !pending.isPending()) return false;+ const target = shellByKey.get(assignment.id);+ if (target === undefined) continue;+ if (!checkThreadOperationPermission(target, "Could not move thread")) return false;+ const result = await reorder({+ environmentId: target.environmentId,+ input: { threadId: target.id, orderKey: assignment.orderKey },+ });+ if (result._tag === "Failure") {+ const error = Cause.squash(result.cause);+ Dialog.alert(+ "Could not move thread",+ error instanceof Error && error.message.trim().length > 0+ ? error.message+ : "The thread could not be moved.",+ );+ return false;+ }+ }+ pending?.complete();+ return true;+ })();+ if (!moved) pending?.cancel();+ appAtomRegistry.set(threadDropBusyAtom, false);+ return moved;+ };- const confirmDeleteThread = useConfirmDeleteThread(executeAction);+ const confirmDeleteThread = (thread: EnvironmentThreadShell) =>+ confirmThreadDeletion(executeAction, thread);return {archiveThread,@@ -746,20 +688,15 @@ export function useArchivedThreadListActions(readonly unarchiveThread: (thread: EnvironmentThreadShell) => void;readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;} {- const handleCompleted = useCallback(- (_action: ThreadListAction, thread: EnvironmentThreadShell) => {- onCompleted(thread);- },- [onCompleted],- );+ const handleCompleted = (_action: ThreadListAction, thread: EnvironmentThreadShell) => {+ onCompleted(thread);+ };const executeAction = useThreadActionExecutor(handleCompleted);- const unarchiveThread = useCallback(- (thread: EnvironmentThreadShell) => {- void executeAction("unarchive", thread);- },- [executeAction],- );- const confirmDeleteThread = useConfirmDeleteThread(executeAction);+ const unarchiveThread = (thread: EnvironmentThreadShell) => {+ void executeAction("unarchive", thread);+ };+ const confirmDeleteThread = (thread: EnvironmentThreadShell) =>+ confirmThreadDeletion(executeAction, thread);return { unarchiveThread, confirmDeleteThread };}diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsxindex 58110d6a586..82bd286cbdb 100644--- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx+++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx@@ -15,9 +15,8 @@ import {import {createContext,use,- useCallback,useEffect,- useMemo,+ useEffectEvent,useRef,useState,type ReactNode,@@ -126,9 +125,7 @@ export function useAdaptiveWorkspaceLayout(): AdaptiveWorkspaceContextValue {export function useAdaptiveWorkspacePaneRole(role: WorkspaceAuxiliaryPaneRole) {const { activateAuxiliaryPaneRole } = useAdaptiveWorkspaceLayout();- useFocusEffect(- useCallback(() => activateAuxiliaryPaneRole(role), [activateAuxiliaryPaneRole, role]),- );+ useFocusEffect(() => activateAuxiliaryPaneRole(role));}/**@@ -146,7 +143,7 @@ export function useRegisterWorkspaceInspector(render: (() => ReactNode) | undeficonst navigation = use(NavigationContext);const route = use(NavigationRouteContext);- const wrappedRender = useMemo(() => {+ const wrappedRender = (() => {if (render === undefined) {return undefined;}@@ -155,37 +152,35 @@ export function useRegisterWorkspaceInspector(render: (() => ReactNode) | undefi<NavigationRouteContext.Provider value={route}>{render()}</NavigationRouteContext.Provider></NavigationContext.Provider>);- }, [navigation, render, route]);+ })();- const wrappedRenderRef = useRef(wrappedRender);- wrappedRenderRef.current = wrappedRender;const focusedRef = useRef(false);const deactivateRef = useRef<(() => void) | null>(null);- const syncRegistration = useCallback(() => {- if (!focusedRef.current || wrappedRenderRef.current === undefined) {+ // An effect event reads this render's pane without making the focus+ // subscription re-run (and deactivate) every time the pane closure changes.+ const syncRegistration = useEffectEvent(() => {+ if (!focusedRef.current || wrappedRender === undefined) {deactivateRef.current?.();return;}- deactivateRef.current = registerWorkspaceInspector(wrappedRenderRef.current);- }, [registerWorkspaceInspector]);+ deactivateRef.current = registerWorkspaceInspector(wrappedRender);+ });- useFocusEffect(- useCallback(() => {- focusedRef.current = true;+ useFocusEffect(() => {+ focusedRef.current = true;+ syncRegistration();+ return () => {+ focusedRef.current = false;syncRegistration();- return () => {- focusedRef.current = false;- syncRegistration();- };- }, [syncRegistration]),- );+ };+ });useEffect(() => {if (focusedRef.current) {syncRegistration();}- }, [syncRegistration, wrappedRender]);+ }, [wrappedRender]);useEffect(() => () => {@@ -252,10 +247,7 @@ function AdaptiveWorkspaceLayoutContent(const [primarySidebarSearchQuery, setPrimarySidebarSearchQuery] = useState("");const [focusedAuxiliaryPaneRole, setFocusedAuxiliaryPaneRole] =useState<WorkspaceAuxiliaryPaneRole | null>(null);- const baseLayout = useMemo(- () => deriveLayout({ width: viewportWidth, height, nativeMetrics }),- [height, viewportWidth, nativeMetrics],- );+ const baseLayout = deriveLayout({ width: viewportWidth, height, nativeMetrics });const primarySidebarPinned = isPrimarySidebarPinned({pathname,nativeWorkspace,@@ -264,37 +256,21 @@ function AdaptiveWorkspaceLayoutContent(const showPrimarySidebar = primarySidebarPinned || primarySidebarPreferredVisible;const [hinge, setHinge] = useState<VerticalHinge | null>(null);const [windowHinge, setWindowHinge] = useState<VerticalHinge | null>(null);- const handleHingeChange = useCallback(- (next: VerticalHinge | null, nextWindow: VerticalHinge | null) => {- setHinge(next);- setWindowHinge(nextWindow);- },- [],- );- const layout = useMemo(- () => alignListPaneToHinge({ layout: baseLayout, hinge, viewportWidth }),- [baseLayout, hinge, viewportWidth],- );+ const handleHingeChange = (next: VerticalHinge | null, nextWindow: VerticalHinge | null) => {+ setHinge(next);+ setWindowHinge(nextWindow);+ };+ const layout = alignListPaneToHinge({ layout: baseLayout, hinge, viewportWidth });const shouldRenderPrimarySidebar = layout.usesSplitView;- const fileInspector = useMemo(- () =>- deriveFileInspectorPaneLayout({- layout,- viewportWidth,- preferredWidth: fileInspectorPreferredWidth ?? undefined,- reservedLeadingWidth:- shouldRenderPrimarySidebar && showPrimarySidebar- ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0)- : 0,- }),- [- fileInspectorPreferredWidth,- layout,- showPrimarySidebar,- shouldRenderPrimarySidebar,- viewportWidth,- ],- );+ const fileInspector = deriveFileInspectorPaneLayout({+ layout,+ viewportWidth,+ preferredWidth: fileInspectorPreferredWidth ?? undefined,+ reservedLeadingWidth:+ shouldRenderPrimarySidebar && showPrimarySidebar+ ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0)+ : 0,+ });const auxiliaryPaneRole: WorkspaceAuxiliaryPaneRole =focusedAuxiliaryPaneRole ?? (/\/files(?:\/|$)/.test(pathname) ? "inspector" : "supplementary");const auxiliaryPanePreferredVisible =@@ -305,29 +281,18 @@ function AdaptiveWorkspaceLayoutContent(auxiliaryPaneRole === "inspector"? fileInspectorPreferredWidth: supplementaryPanePreferredWidth;- const panes = useMemo(- () =>- deriveWorkspacePaneLayout({- layout,- viewportWidth,- primarySidebarPreferredVisible: showPrimarySidebar,- auxiliaryPanePreferredVisible,- auxiliaryPaneRole,- auxiliaryPanePreferredWidth: auxiliaryPanePreferredWidth ?? undefined,- }),- [- auxiliaryPanePreferredVisible,- auxiliaryPaneRole,- auxiliaryPanePreferredWidth,- layout,- showPrimarySidebar,- viewportWidth,- ],- );+ const panes = deriveWorkspacePaneLayout({+ layout,+ viewportWidth,+ primarySidebarPreferredVisible: showPrimarySidebar,+ auxiliaryPanePreferredVisible,+ auxiliaryPaneRole,+ auxiliaryPanePreferredWidth: auxiliaryPanePreferredWidth ?? undefined,+ });const activeThread = parseActiveThreadPath(pathname);const environmentId = activeThread?.environmentId ?? null;const threadId = activeThread?.threadId ?? null;- const selectedThreadKey = useMemo(() => {+ const selectedThreadKey = (() => {if (environmentId === null || threadId === null) {return null;}@@ -336,13 +301,13 @@ function AdaptiveWorkspaceLayoutContent(} catch {return null;}- }, [environmentId, threadId]);+ })();const [workspaceInspector, setWorkspaceInspector] = useState<{readonly render: () => ReactNode;readonly active: boolean;} | null>(null);const workspaceInspectorOwner = useRef<symbol | null>(null);- const registerWorkspaceInspector = useCallback((render: () => ReactNode) => {+ const registerWorkspaceInspector = (render: () => ReactNode) => {const owner = Symbol("workspace-inspector");workspaceInspectorOwner.current = owner;setWorkspaceInspector({ render, active: true });@@ -355,11 +320,11 @@ function AdaptiveWorkspaceLayoutContent(}setWorkspaceInspector((current) => (current === null ? null : { ...current, active: false }));};- }, []);- const handleWorkspaceInspectorClosed = useCallback(() => {+ };+ const handleWorkspaceInspectorClosed = () => {setWorkspaceInspector((current) => (current !== null && !current.active ? null : current));- }, []);- const activateAuxiliaryPaneRole = useCallback((role: WorkspaceAuxiliaryPaneRole) => {+ };+ const activateAuxiliaryPaneRole = (role: WorkspaceAuxiliaryPaneRole) => {const owner = Symbol(role);activeRoleOwner.current = owner;setFocusedAuxiliaryPaneRole(role);@@ -371,8 +336,8 @@ function AdaptiveWorkspaceLayoutContent(activeRoleOwner.current = null;setFocusedAuxiliaryPaneRole(null);};- }, []);- const togglePrimarySidebar = useCallback(() => {+ };+ const togglePrimarySidebar = () => {if (primarySidebarPinned) {return;}@@ -382,27 +347,20 @@ function AdaptiveWorkspaceLayoutContent(return;}setPrimarySidebarPreferredVisible((current) => !current);- }, [- panes.primarySidebarSuppressedByAuxiliary,- panes.primarySidebarVisible,- primarySidebarPinned,- ]);- const revealPrimarySidebar = useCallback(() => {+ };+ const revealPrimarySidebar = () => {if (panes.primarySidebarSuppressedByAuxiliary) {setFileInspectorPreferredVisible(false);}setPrimarySidebarPreferredVisible(true);- }, [panes.primarySidebarSuppressedByAuxiliary]);- const handleToggleSidebarCommand = useCallback(() => {+ };+ const handleToggleSidebarCommand = () => {togglePrimarySidebar();return true;- }, [togglePrimarySidebar]);- const sidebarCommands = useMemo(- () => (primarySidebarPinned ? [] : (["toggleSidebar"] as const)),- [primarySidebarPinned],- );+ };+ const sidebarCommands = primarySidebarPinned ? [] : (["toggleSidebar"] as const);useHardwareKeyboardCommand(sidebarCommands, handleToggleSidebarCommand);- const showAuxiliaryPane = useCallback((role: WorkspaceAuxiliaryPaneRole) => {+ const showAuxiliaryPane = (role: WorkspaceAuxiliaryPaneRole) => {if (role === "inspector") {setFocusedAuxiliaryPaneRole("inspector");setFileInspectorPreferredVisible(true);@@ -410,8 +368,8 @@ function AdaptiveWorkspaceLayoutContent(}setFocusedAuxiliaryPaneRole("supplementary");setSupplementaryPanePreferredVisible(true);- }, []);- const handleOpenFilesCommand = useCallback(() => {+ };+ const handleOpenFilesCommand = () => {const activeThread = parseActiveThreadPath(pathname);if (!layout.usesSplitView || !fileInspector.supported || activeThread === null) {return false;@@ -422,75 +380,66 @@ function AdaptiveWorkspaceLayoutContent(}navigation.navigate("ThreadFiles", activeThread);return true;- }, [fileInspector.supported, layout.usesSplitView, pathname, navigation, showAuxiliaryPane]);+ };useHardwareKeyboardCommand("files", handleOpenFilesCommand);- const toggleAuxiliaryPane = useCallback(() => {+ const toggleAuxiliaryPane = () => {if (auxiliaryPaneRole === "inspector") {setFileInspectorPreferredVisible((current) => !current);return;}setSupplementaryPanePreferredVisible((current) => !current);- }, [auxiliaryPaneRole]);- const setAuxiliaryPaneWidth = useCallback(- (nextWidth: number) => {- if (auxiliaryPaneRole === "inspector") {- setFileInspectorPreferredWidth(nextWidth);- return;- }- setSupplementaryPanePreferredWidth(nextWidth);- },- [auxiliaryPaneRole],- );- const handleOpenSettings = useCallback(() => {+ };+ const setAuxiliaryPaneWidth = (nextWidth: number) => {+ if (auxiliaryPaneRole === "inspector") {+ setFileInspectorPreferredWidth(nextWidth);+ return;+ }+ setSupplementaryPanePreferredWidth(nextWidth);+ };+ const handleOpenSettings = () => {navigation.navigate("SettingsSheet", {screen: "SettingsContent",params: { screen: "Settings" },});- }, [navigation]);+ };- const handleStartNewTask = useCallback(() => {+ const handleStartNewTask = () => {navigation.navigate("NewTaskSheet", { screen: "NewTask" });- }, [navigation]);+ };// Minted here (root stack navigation) so the sidebar pane stays free of// navigation hooks — on iOS it renders inside an independent nav tree.- const handleOpenEnvironmentSettings = useCallback(() => {+ const handleOpenEnvironmentSettings = () => {navigation.navigate("SettingsSheet", {screen: "SettingsContent",params: { screen: "SettingsEnvironments" },});- }, [navigation]);+ };const handleOpenThreadPullRequests = useOpenThreadPullRequests();- const handleNewThreadOnBranch = useCallback(- (thread: EnvironmentThreadShell) => {- navigation.navigate("NewTaskSheet", {- screen: "NewTaskDraft",- params: {- environmentId: String(thread.environmentId),- projectId: String(thread.projectId),- branch: thread.branch,- worktreePath: thread.worktreePath,- },- });- },- [navigation],- );+ const handleNewThreadOnBranch = (thread: EnvironmentThreadShell) => {+ navigation.navigate("NewTaskSheet", {+ screen: "NewTaskDraft",+ params: {+ environmentId: String(thread.environmentId),+ projectId: String(thread.projectId),+ branch: thread.branch,+ worktreePath: thread.worktreePath,+ },+ });+ };- const handleNewThreadInProject = useCallback(- (project: EnvironmentProject) => {- navigation.navigate("NewTaskSheet", {- screen: "NewTaskDraft",- params: {- environmentId: String(project.environmentId),- projectId: String(project.id),- title: project.title,- },- });- },- [navigation],- );+ const handleNewThreadInProject = (project: EnvironmentProject) => {+ navigation.navigate("NewTaskSheet", {+ screen: "NewTaskDraft",+ params: {+ environmentId: String(project.environmentId),+ projectId: String(project.id),+ title: project.title,+ },+ });+ };const inspectorColumnTargetWidth =workspaceInspector !== null && workspaceInspector.active && panes.auxiliaryPaneVisible@@ -550,7 +499,7 @@ function AdaptiveWorkspaceLayoutContent(revision: contentSizing.revision + 1,});}- const settleContentWidth = useCallback((revision: number) => {+ const settleContentWidth = (revision: number) => {setContentSizing((current) =>current.revision !== revision ||(current.width === current.target &&@@ -564,7 +513,7 @@ function AdaptiveWorkspaceLayoutContent(listPaneCeiling: current.listPaneTarget,},);- }, []);+ };const listPaneFloor = contentSizing.listPaneFloor ?? 0;const listPaneCeiling = contentSizing.listPaneCeiling ?? 0;const contentSettledWidth = Platform.OS === "android" ? contentSizing.width : contentTargetWidth;@@ -614,88 +563,62 @@ function AdaptiveWorkspaceLayoutContent();const selectAndroidWorkspace = useAndroidWorkspaceSelection();- const handleSelectThread = useCallback(- (thread: EnvironmentThreadShell) => {- const params = {- environmentId: String(thread.environmentId),- threadId: String(thread.id),- };- if (Platform.OS === "android") {- setFileInspectorPreferredVisible(false);- selectAndroidWorkspace({ name: "Thread", params });- return;- }- const navigationAction = resolveThreadSelectionNavigationAction({- usesSplitView: layout.usesSplitView,- pathname,- });- const overlayState = resolveThreadSelectionOverlayState({- state: navigation.getState(),- workspaceRouteKey: props.workspaceRouteKey,- action: navigationAction,- params,- });- if (overlayState !== null) {- setFileInspectorPreferredVisible(false);- navigation.dispatch(CommonActions.reset(overlayState));- return;- }- if (navigationAction === "set-params") {- const nextThreadKey = scopedThreadKey(thread.environmentId, thread.id);- if (nextThreadKey === selectedThreadKey) {- return;- }- setFileInspectorPreferredVisible(false);- navigation.navigate("Thread", params);- return;- }- if (navigationAction === "replace") {- setFileInspectorPreferredVisible(false);- navigation.dispatch(StackActions.replace("Thread", params));+ const handleSelectThread = (thread: EnvironmentThreadShell) => {+ const params = {+ environmentId: String(thread.environmentId),+ threadId: String(thread.id),+ };+ if (Platform.OS === "android") {+ setFileInspectorPreferredVisible(false);+ selectAndroidWorkspace({ name: "Thread", params });+ return;+ }+ const navigationAction = resolveThreadSelectionNavigationAction({+ usesSplitView: layout.usesSplitView,+ pathname,+ });+ const overlayState = resolveThreadSelectionOverlayState({+ state: navigation.getState(),+ workspaceRouteKey: props.workspaceRouteKey,+ action: navigationAction,+ params,+ });+ if (overlayState !== null) {+ setFileInspectorPreferredVisible(false);+ navigation.dispatch(CommonActions.reset(overlayState));+ return;+ }+ if (navigationAction === "set-params") {+ const nextThreadKey = scopedThreadKey(thread.environmentId, thread.id);+ if (nextThreadKey === selectedThreadKey) {return;}+ setFileInspectorPreferredVisible(false);navigation.navigate("Thread", params);- },- [- layout.usesSplitView,- pathname,- navigation,- selectedThreadKey,- props.workspaceRouteKey,- selectAndroidWorkspace,- ],- );+ return;+ }+ if (navigationAction === "replace") {+ setFileInspectorPreferredVisible(false);+ navigation.dispatch(StackActions.replace("Thread", params));+ return;+ }+ navigation.navigate("Thread", params);+ };- const contextValue = useMemo(- () => ({- layout,- panes,- fileInspector,- primarySidebarSearchQuery,- selectThread: handleSelectThread,- activateAuxiliaryPaneRole,- registerWorkspaceInspector,- setPrimarySidebarSearchQuery,- showAuxiliaryPane,- toggleAuxiliaryPane,- togglePrimarySidebar,- setAuxiliaryPaneWidth,- }),- [- activateAuxiliaryPaneRole,- fileInspector,- handleSelectThread,- layout,- panes,- primarySidebarSearchQuery,- registerWorkspaceInspector,- showAuxiliaryPane,- setPrimarySidebarSearchQuery,- setAuxiliaryPaneWidth,- toggleAuxiliaryPane,- togglePrimarySidebar,- ],- );+ const contextValue = {+ layout,+ panes,+ fileInspector,+ primarySidebarSearchQuery,+ selectThread: handleSelectThread,+ activateAuxiliaryPaneRole,+ registerWorkspaceInspector,+ setPrimarySidebarSearchQuery,+ showAuxiliaryPane,+ toggleAuxiliaryPane,+ togglePrimarySidebar,+ setAuxiliaryPaneWidth,+ };if (nativeWorkspace) {return (diff --git a/apps/mobile/src/features/layout/workspace-inspector-pane.tsx b/apps/mobile/src/features/layout/workspace-inspector-pane.tsxindex 7e12fb53bd2..c88b28db2ff 100644--- a/apps/mobile/src/features/layout/workspace-inspector-pane.tsx+++ b/apps/mobile/src/features/layout/workspace-inspector-pane.tsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";+import { useEffect, useRef, useState, type ReactNode } from "react";import Animated, {runOnJS,useAnimatedStyle,@@ -49,9 +49,9 @@ export function WorkspaceInspectorPane(props: {},);const targetWidth = inspectorVisible ? (inspectorWidth ?? 0) : 0;- renderedInspectorWidth.value = resizing- ? targetWidth- : withTiming(targetWidth, WORKSPACE_PANE_TIMING);+ renderedInspectorWidth.set(+ resizing ? targetWidth : withTiming(targetWidth, WORKSPACE_PANE_TIMING),+ );}, [inspectorProgress,inspectorVisible,@@ -79,24 +79,21 @@ export function WorkspaceInspectorPane(props: {[],);const inspectorContentStyle = useAnimatedStyle(() => ({ width: renderedContentWidth.value }), []);- const beginResize = useCallback(() => {+ const beginResize = () => {resizeStartWidth.current = inspectorWidth ?? 0;setResizing(true);- }, [inspectorWidth]);- const resizeBy = useCallback(- (delta: number) => {- setAuxiliaryPaneWidth(- constrainAuxiliaryPaneWidth({- preferredWidth: resizeStartWidth.current + delta,- availableWidth: panes.contentPaneWidth,- }),- );- },- [panes.contentPaneWidth, setAuxiliaryPaneWidth],- );- const endResize = useCallback(() => {+ };+ const resizeBy = (delta: number) => {+ setAuxiliaryPaneWidth(+ constrainAuxiliaryPaneWidth({+ preferredWidth: resizeStartWidth.current + delta,+ availableWidth: panes.contentPaneWidth,+ }),+ );+ };+ const endResize = () => {setResizing(false);- }, []);+ };return (<>diff --git a/apps/mobile/src/features/layout/workspace-pane-divider.tsx b/apps/mobile/src/features/layout/workspace-pane-divider.tsxindex fb21dfca470..62e488b2bee 100644--- a/apps/mobile/src/features/layout/workspace-pane-divider.tsx+++ b/apps/mobile/src/features/layout/workspace-pane-divider.tsx@@ -1,4 +1,4 @@-import { useCallback, useMemo, useRef, useState } from "react";+import { useEffectEvent, useState } from "react";import { Platform, Pressable, StyleSheet, View, type AccessibilityActionEvent } from "react-native";import { Gesture, GestureDetector } from "react-native-gesture-handler";import { runOnJS } from "react-native-reanimated";@@ -16,35 +16,33 @@ interface WorkspacePaneDividerProps {}export function WorkspacePaneDivider(props: WorkspacePaneDividerProps) {- const latestProps = useRef(props);- latestProps.current = props;const [dragging, setDragging] = useState(false);- const handleResizeStart = useCallback(() => {+ // The pan callbacks fire after render, so effect events read the latest props+ // while the gesture object stays stable across renders.+ const handleResizeStart = useEffectEvent(() => {setDragging(true);- latestProps.current.onResizeStart?.();- }, []);- const handleResize = useCallback((translationX: number) => {- latestProps.current.onResizeBy(translationX * latestProps.current.resizeDirection);- }, []);- const handleResizeEnd = useCallback(() => {+ props.onResizeStart?.();+ });+ const handleResize = useEffectEvent((translationX: number) => {+ props.onResizeBy(translationX * props.resizeDirection);+ });+ const handleResizeEnd = useEffectEvent(() => {setDragging(false);- latestProps.current.onResizeEnd?.();- }, []);- const resizeGesture = useMemo(- () =>- Gesture.Pan()- .activeOffsetX([-4, 4])- .failOffsetY([-24, 24])- .onStart(() => {- runOnJS(handleResizeStart)();- })- .onUpdate((event) => {- runOnJS(handleResize)(event.translationX);- })- .onFinalize(() => {- runOnJS(handleResizeEnd)();- }),- [handleResize, handleResizeEnd, handleResizeStart],+ props.onResizeEnd?.();+ });+ const [resizeGesture] = useState(() =>+ Gesture.Pan()+ .activeOffsetX([-4, 4])+ .failOffsetY([-24, 24])+ .onStart(() => {+ runOnJS(handleResizeStart)();+ })+ .onUpdate((event) => {+ runOnJS(handleResize)(event.translationX);+ })+ .onFinalize(() => {+ runOnJS(handleResizeEnd)();+ }),);const handleAccessibilityAction = (event: AccessibilityActionEvent) => {diff --git a/apps/mobile/src/reactCompilerCoverage.test.ts b/apps/mobile/src/reactCompilerCoverage.test.tsindex 2179ab4d440..7d47342f70c 100644--- a/apps/mobile/src/reactCompilerCoverage.test.ts+++ b/apps/mobile/src/reactCompilerCoverage.test.ts@@ -24,17 +24,9 @@ const KNOWN_BAILOUTS: Record<string, string> = {"src/components/VideoPreviewModal.tsx": "ref read during render","src/components/ui/AndroidAnchoredMenu.tsx": "ref read during render","src/components/ui/Menu.tsx": "ref read during render",- "src/components/ui/OverlayPortal.tsx": "unsupported syntax","src/features/connection/ConnectionsNewRouteScreen.tsx": "try without catch","src/features/diffs/nativeReviewDiffSurface.ts": "ref read during render",- "src/features/home/HomeScreen.tsx": "ref read during render",- "src/features/home/WorkspaceConnectionTitle.tsx": "ref read during render",- "src/features/home/home-list-options.ts": "manual memo not preserved","src/features/home/thread-swipe-actions.tsx": "ref read during render",- "src/features/home/useThreadListActions.ts": "try without catch",- "src/features/layout/AdaptiveWorkspaceLayout.tsx": "ref read during render",- "src/features/layout/workspace-inspector-pane.tsx": "mutates a frozen value",- "src/features/layout/workspace-pane-divider.tsx": "ref read during render","src/features/projects/AddProjectScreen.tsx": "try without catch","src/features/pull-requests/PullRequestDiscussionScreen.tsx": "try/finally","src/features/pull-requests/PullRequestInlineCommentScreen.tsx": "try without catch",