diff --git a/apps/mobile/src/features/browser/ThreadBrowserFloat.tsx b/apps/mobile/src/features/browser/ThreadBrowserFloat.tsx index 58a3dce64b418..1ff0cd0dbf44c 100644 --- a/apps/mobile/src/features/browser/ThreadBrowserFloat.tsx +++ b/apps/mobile/src/features/browser/ThreadBrowserFloat.tsx @@ -12,6 +12,7 @@ import { useAppForeground } from "../../lib/appState"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; import { browserTabTitle } from "./browserTabs"; import { PreviewStreamWebView } from "./PreviewStreamWebView"; +import { useThreadServerBrowserTabs } from "../../state/preview"; import { usePreparedConnection } from "../../state/session"; const PLAYER_LONG_SIDE = 184; @@ -21,11 +22,13 @@ const PLAYER_EXITING = FadeOut.duration(120).reduceMotion(ReduceMotion.System); export function ThreadBrowserFloat(props: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId; - readonly tabs: ReadonlyArray; - readonly loaded: boolean; + /** Whether the environment serves browser tabs. */ + readonly enabled: boolean; readonly top: number; readonly onOpen: (tabId: string) => void; }) { + // Read here rather than by the thread screen, so a list read re-renders only the float. + const { tabs, loaded } = useThreadServerBrowserTabs(props); const [tabId, setTabId] = useState(null); // The reveal requests already seen, so only a tab revealed after the first // list pops the player. @@ -33,16 +36,16 @@ export function ThreadBrowserFloat(props: { readonly tabs: ReadonlyArray; readonly reveals: ReadonlyMap; } | null>(null); - if (props.loaded && seen?.tabs !== props.tabs) { + if (loaded && seen?.tabs !== tabs) { setSeen({ - tabs: props.tabs, - reveals: new Map(props.tabs.map((tab) => [tab.tabId, tab.revealRequest?.id])), + tabs, + reveals: new Map(tabs.map((tab) => [tab.tabId, tab.revealRequest?.id])), }); const previous = seen?.reveals; const opened = previous === undefined ? undefined - : props.tabs.findLast( + : tabs.findLast( (tab) => tab.reveal === true && (tab.revealRequest @@ -53,7 +56,7 @@ export function ThreadBrowserFloat(props: { } const focused = useIsFocused(); const foreground = useAppForeground(); - const tab = props.tabs.find((entry) => entry.tabId === tabId) ?? null; + const tab = tabs.find((entry) => entry.tabId === tabId) ?? null; const onOpen = props.onOpen; const open = () => { if (tabId === null) return; diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.ts index 968c4d5683caf..407ff615e165e 100644 --- a/apps/mobile/src/features/home/useThreadListActions.test.ts +++ b/apps/mobile/src/features/home/useThreadListActions.test.ts @@ -42,6 +42,9 @@ vi.mock("react", () => ({ useCallback: (callback: unknown) => callback, useRef: (current: unknown) => ({ current }), })); +vi.mock("../../lib/useStableCallback", () => ({ + useStableCallback: (callback: unknown) => callback, +})); vi.mock("react-native", () => ({ Alert: { alert: (title: string, _message: string, buttons?: { text: string; onPress?: () => void }[]) => diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index 205097182914f..c9744ec41df80 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -42,6 +42,7 @@ import { import { getThreadListV2OrderedSection } from "../threads/threadListV2"; import { threadCanArchive } from "./threadArchive"; import { resolveThreadTitleRename } from "../threads/thread-title-rename"; +import { useStableCallback } from "../../lib/useStableCallback"; function environmentConfigLoaded(environmentId: EnvironmentThreadShell["environmentId"]) { return appAtomRegistry.get(environmentServerConfigsAtom).has(environmentId); @@ -833,20 +834,41 @@ export function useThreadListActions(): { const confirmDeleteThread = (thread: EnvironmentThreadShell) => confirmThreadDeletion(executeAction, thread); + // Stable, so a list that re-renders does not re-render every row these reach. // `moveThread` looks up its own row, and refuses while a list holds older rows. return { - archiveThread: (thread) => archiveThread(liveThread(thread)), - confirmDeleteThread: (thread) => confirmDeleteThread(liveThread(thread)), - settleThread: (thread) => settleThread(liveThread(thread)), - snoozeThread: (thread, snoozedUntil) => snoozeThread(liveThread(thread), snoozedUntil), - unsnoozeThread: (thread) => unsnoozeThread(liveThread(thread)), - unsettleThread: (thread) => unsettleThread(liveThread(thread)), - pinThread: (thread) => pinThread(liveThread(thread)), - unpinThread: (thread) => unpinThread(liveThread(thread)), - setThreadAutoSettle: (thread, enabled) => setThreadAutoSettle(liveThread(thread), enabled), - moveThread, - renameThread: (thread) => renameThread(liveThread(thread)), - regenerateThreadTitle: (thread) => regenerateThreadTitle(liveThread(thread)), + archiveThread: useStableCallback((thread: EnvironmentThreadShell) => + archiveThread(liveThread(thread)), + ), + confirmDeleteThread: useStableCallback((thread: EnvironmentThreadShell) => + confirmDeleteThread(liveThread(thread)), + ), + settleThread: useStableCallback((thread: EnvironmentThreadShell) => + settleThread(liveThread(thread)), + ), + snoozeThread: useStableCallback((thread: EnvironmentThreadShell, snoozedUntil: string) => + snoozeThread(liveThread(thread), snoozedUntil), + ), + unsnoozeThread: useStableCallback((thread: EnvironmentThreadShell) => + unsnoozeThread(liveThread(thread)), + ), + unsettleThread: useStableCallback((thread: EnvironmentThreadShell) => + unsettleThread(liveThread(thread)), + ), + pinThread: useStableCallback((thread: EnvironmentThreadShell) => pinThread(liveThread(thread))), + unpinThread: useStableCallback((thread: EnvironmentThreadShell) => + unpinThread(liveThread(thread)), + ), + setThreadAutoSettle: useStableCallback((thread: EnvironmentThreadShell, enabled: boolean) => + setThreadAutoSettle(liveThread(thread), enabled), + ), + moveThread: useStableCallback(moveThread), + renameThread: useStableCallback((thread: EnvironmentThreadShell) => + renameThread(liveThread(thread)), + ), + regenerateThreadTitle: useStableCallback((thread: EnvironmentThreadShell) => + regenerateThreadTitle(liveThread(thread)), + ), }; } diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx index 86565d3600b89..cc013343188bb 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx @@ -123,12 +123,12 @@ function RetainedWorkspaceTab(props: { ); return () => cancelAnimationFrame(frame); }, [headerOnly, optionsByRoute, slot, setPrewarmRequests]); + // Built apart from the providers: a header option write re-renders their readers, not the tab. + const body = content ? content.children(content.workspace, content.headerOnly) : null; return content ? ( - - {content.children(content.workspace, content.headerOnly)} - + {body} ) : null; diff --git a/apps/mobile/src/features/pull-requests/PullRequestFiles.tsx b/apps/mobile/src/features/pull-requests/PullRequestFiles.tsx index a380a468ff6c7..bf4411420d6c2 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestFiles.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestFiles.tsx @@ -4,7 +4,7 @@ import { AnimatedLegendList } from "@legendapp/list/reanimated"; import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native"; import type { PullRequestChangeBreakdown } from "@t3tools/contracts"; import { msg, T, useGT, useMessages, Var } from "gt-react-native"; -import { useState } from "react"; +import { memo, useState } from "react"; import { View } from "react-native"; import Animated from "react-native-reanimated"; import { PierreEntryIcon } from "../../components/PierreEntryIcon"; @@ -108,12 +108,13 @@ function describeFiles( .join(" ยท "); } -function FileRow(props: { +// Memoized: a pull request's rows rebuild as its detail, diff and viewed reads land. +const FileRow = memo(function FileRow(props: { readonly file: ReviewRenderableFile; readonly viewed: boolean; /** Shown under the file name where files aren't grouped by directory. */ readonly directory?: string; - readonly onPress: () => void; + readonly onPress: (path: string) => void; }) { const { file } = props; const gt = useGT(); @@ -126,7 +127,7 @@ function FileRow(props: { ? gt("View diff for {path}, {additions} additions, {deletions} deletions, viewed", values) : gt("View diff for {path}, {additions} additions, {deletions} deletions", values) } - onPress={props.onPress} + onPress={() => props.onPress(file.path)} className="min-h-14 flex-row items-center gap-3 border-b border-border-subtle py-3 active:opacity-70" > @@ -158,7 +159,7 @@ function FileRow(props: { ); -} +}); function FileRowSkeleton(props: { readonly index: number }) { return ( @@ -289,6 +290,7 @@ export function usePullRequestFilesSection(params: PullRequestParams) { composerPullRequests.changeBreakdown(pullRequestTarget(params)), ).data; const expected = pr ?? params.initialSummary; + const openFile = (path: string) => navigation.navigate("PullRequestFile", { ...params, path }); return { refresh: diff.refresh, header: ( @@ -363,7 +365,7 @@ export function usePullRequestFilesSection(params: PullRequestParams) { file={file} directory={fileDirectory(file.path)} viewed={viewed.isViewed(file.path)} - onPress={() => navigation.navigate("PullRequestFile", { ...params, path: file.path })} + onPress={openFile} /> ), })), @@ -461,14 +463,10 @@ export function PullRequestFilesSheet({ route }: StaticScreenProps { - requestPullRequestFileJump(navigation.getState()?.routes ?? [], item.file.path); + onPress={(path) => { + requestPullRequestFileJump(navigation.getState()?.routes ?? [], path); navigation.dispatch( - StackActions.popTo("PullRequestFile", { - ...params, - path: item.file.path, - focus: undefined, - }), + StackActions.popTo("PullRequestFile", { ...params, path, focus: undefined }), ); }} /> diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx index c0a644321a66f..52d23483231e0 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx @@ -70,7 +70,7 @@ import { import { PullRequestOverviewLoading } from "./PullRequestOverviewLoading"; import { copyPullRequestLink, sharePullRequestLink } from "./pullRequestLink"; import { pullRequestStatus } from "./pullRequestStatus"; -import { use, useEffect, useEffectEvent, useMemo, useRef, useState } from "react"; +import { use, useEffect, useEffectEvent, useMemo, useRef, useState, type ReactNode } from "react"; import { Platform, Pressable, StyleSheet, View } from "react-native"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { RefreshControl } from "../../components/ui/RefreshControl"; @@ -393,6 +393,8 @@ function PullRequestOverview(props: { ); } +const NO_TAB_ROWS: ReadonlyArray<{ readonly key: string; readonly content: ReactNode }> = []; + function usePullRequestToolbarHeight(bottomInset: number) { const { buttonSize } = useAndroidControlSizing(); return useState(() => (Platform.OS === "android" ? bottomInset + buttonSize + 40 : 0)); @@ -730,6 +732,72 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps + {identity ? ( + + + {pr ? ( + { + descriptionY.current = y; + }} + onDescriptionCollapse={() => { + pendingDescriptionJump.current = true; + }} + /> + ) : summary ? ( + + ) : null} + { + filesY.current = event.nativeEvent.layout.y; + if (pendingFilesJump.current) { + requestAnimationFrame(() => { + if (shown(requestedSection.current) === "overview") jumpToFiles(); + }); + } + }} + > + {filesContent.header} + + + ) : null} + + ); + const guideBody = guidesEnabled ? ( + + + + ) : null; + const activityBody = ( + + + + + ); return ( @@ -824,94 +892,25 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps - {tab === "overview" && identity ? ( - - - {pr ? ( - { - descriptionY.current = y; - }} - onDescriptionCollapse={() => { - pendingDescriptionJump.current = true; - }} - /> - ) : summary ? ( - - ) : null} - { - filesY.current = event.nativeEvent.layout.y; - if (pendingFilesJump.current) { - requestAnimationFrame(() => { - if (shown(requestedSection.current) === "overview") - jumpToFiles(); - }); - } - }} - > - {filesContent.header} - - - ) : null} - {tab === "guide" ? ( - - ) : null} - {tab === "activity" ? ( - - ) : null} - {tab === "activity" ? ( - - ) : null} - - ), + content: + tab === "overview" + ? overviewBody + : tab === "guide" + ? guideBody + : activityBody, }, + // Each tab has its own list, so rows keep their own keys and, unchanged, + // their identity: a list re-renders only the rows that changed. ...(tab === "overview" ? identity ? filesContent.rows - : [] + : NO_TAB_ROWS : tab === "activity" ? tabContent.rows - : [] - ).map((row) => ({ - ...row, - key: `${tab}:${row.key}`, - content: row.content, - })), + : NO_TAB_ROWS), ]} keyExtractor={(row) => row.key} - getItemType={(row) => - row.key.endsWith(":body") ? row.key : row.key.split(":")[0] - } + getItemType={(row) => (row.key === `${tab}:body` ? row.key : tab)} // Animating overview fights clipped markdown and collapse scroll correction; file rows can still fade. itemLayoutAnimation={tab === "overview" ? undefined : PR_ROW_LAYOUT} onLoad={() => setListAnimationsReady(true)} @@ -919,12 +918,10 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 387b35befcc9d..7ba8e46067148 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -147,11 +147,9 @@ import { } from "../../lib/layout"; import { editPendingThreadMessage } from "../../state/edit-pending-thread-message"; import { environmentCatalog } from "../../connection/catalog"; -import { deviceEnvironment } from "../../state/device"; -import { useEnvironmentQuery } from "../../state/query"; -import { threadDevicePreviews } from "../devices/threadDevicePreviews"; +import { useThreadDevicePreviewCount } from "../../state/device"; import { ThreadBrowserFloat } from "../browser/ThreadBrowserFloat"; -import { useThreadServerBrowserTabs } from "../../state/preview"; +import { useThreadServerBrowserTabCount } from "../../state/preview"; import type { QueuedThreadMessage } from "../../state/thread-outbox-model"; import { scopedThreadKey } from "../../lib/scopedEntities"; import { @@ -227,7 +225,6 @@ import type { OrchestrationV2ProviderSession } from "@t3tools/contracts"; import { voiceInputBlocksSubmission } from "@t3tools/client-runtime/voice-input"; export interface ThreadDetailScreenProps { - readonly header?: React.ReactNode; readonly draftMode?: { /** viewportHeight excludes the composer so draft chrome can resize it without feedback. */ readonly content: ( @@ -435,10 +432,10 @@ function ThreadDetailBody( const openInspector = useOpenThreadInspector(); const { session: voiceInputSession } = useGlobalVoiceInput(); const reportedModelSelection = useThreadReportedModelSelection(props.selectedThreadDetailRef); - const deviceState = useEnvironmentQuery( - deviceEnvironment.state({ environmentId: props.environmentId, input: {} }), + const devicePreviewCount = useThreadDevicePreviewCount( + props.environmentId, + props.selectedThread.id, ); - const devicePreviews = threadDevicePreviews(deviceState.data, props.selectedThread.id); const openDevicePreview = () => { Keyboard.dismiss(); if ( @@ -453,11 +450,12 @@ function ThreadDetailBody( threadId: props.selectedThread.id, }); }; - const browserTabs = useThreadServerBrowserTabs({ + const serverBrowserEnabled = + !props.draftMode && props.serverConfig?.environment.capabilities.serverBrowser === true; + const browserTabCount = useThreadServerBrowserTabCount({ environmentId: props.environmentId, threadId: props.selectedThread.id, - enabled: - !props.draftMode && props.serverConfig?.environment.capabilities.serverBrowser === true, + enabled: serverBrowserEnabled, }); const openBrowserPreview = (tabId?: string) => { Keyboard.dismiss(); @@ -931,8 +929,8 @@ function ThreadDetailBody( showWorkingControl || queuedCount > 0 || agentsSegment !== null || - devicePreviews.length > 0 || - browserTabs.tabs.length > 0; + devicePreviewCount > 0 || + browserTabCount > 0; const selectedThreadFeed = props.selectedThreadFeed; // A palette message result opens the thread at that message: earlier // history loads until the message is in the feed, which then scrolls to it. @@ -1610,8 +1608,7 @@ function ThreadDetailBody( key={selectedThreadKey} environmentId={props.environmentId} threadId={props.selectedThread.id} - tabs={browserTabs.tabs} - loaded={browserTabs.loaded} + enabled={serverBrowserEnabled} top={navigationHeaderHeight + 8} onOpen={openBrowserPreview} /> @@ -1687,13 +1684,13 @@ function ThreadDetailBody( } lift={floatingControlLift} devicePreview={ - devicePreviews.length > 0 - ? { count: devicePreviews.length, onPress: openDevicePreview } + devicePreviewCount > 0 + ? { count: devicePreviewCount, onPress: openDevicePreview } : null } browserPreview={ - browserTabs.tabs.length > 0 - ? { count: browserTabs.tabs.length, onPress: () => openBrowserPreview() } + browserTabCount > 0 + ? { count: browserTabCount, onPress: () => openBrowserPreview() } : null } showScrollToEnd={showScrollToEndButton} diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 8f509de9e674a..8f111fc2c69c8 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -105,6 +105,7 @@ import { import { useProjects } from "../../state/entities"; import { projectThreadContentPresentation, + THREAD_CONTENT_READY, threadSyncStatusLabel, } from "./threadContentPresentation"; import { @@ -972,7 +973,7 @@ function ThreadRouteContent( // Queued creation displays its prompt before server creation; temporary not-found is expected. const contentPresentation = creationState !== null - ? { kind: "ready" as const } + ? THREAD_CONTENT_READY : projectThreadContentPresentation({ hasDetail: selectedThreadDetail !== null, detailError: Option.getOrNull(selectedThreadDetailState.error), @@ -1028,122 +1029,6 @@ function ThreadRouteContent( } const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null; - const renderThreadRouteBody = () => ( - <> - dismissGitActionResult(gitActionThreadRef)} - onOpenPullRequest={openPullRequest} - /> - - <> - - ) - } - canOperateThread={canOperateThread} - selectedThread={selectedThreadWithDraftSettings ?? selectedThread} - selectedThreadDetailRef={selectedThreadDetailRef} - contentPresentation={contentPresentation} - screenTone={connectionTone( - routeConnectionState, - routeEnvironmentRuntime?.connectionAwaitingApproval === true, - m, - )} - connectionError={routeConnectionError} - environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null} - feedbackSubmissions={composer.feedbackSubmissions} - onDismissFeedback={composer.dismissFeedback} - selectedThreadFeed={composer.selectedThreadFeed} - pendingHandoff={composer.pendingHandoff} - activityRun={composer.selectedThreadActivityRun} - activeWorkStartedAt={ - creationState?.kind === "preparing" || - (worktreeSetup !== null && setupTurnStartedAt === null) - ? null - : composer.activeWorkStartedAt - } - isCompacting={composer.isCompacting} - compactBeforeSend={composer.compactBeforeSend} - runlessWorkActive={composer.runlessWorkActive} - extensionStatuses={composer.extensionStatuses} - providerSubagentStatus={composer.providerSubagentStatus} - creationState={creationState} - worktreeSetup={ - worktreeSetup - ? { - snapshot: worktreeSetup, - turnStarted: setupTurnStartedAt !== null, - onCancel: handleCancelWorktreeSetup, - onWorkLocally: setupMessage && selectedThreadProject ? handleWorkLocally : null, - } - : null - } - activePendingApproval={requests.activePendingApproval} - activePendingApprovals={requests.activePendingApprovals} - respondingApprovalId={requests.respondingApprovalId} - activePendingUserInput={requests.activePendingUserInput} - activePendingUserInputDrafts={requests.activePendingUserInputDrafts} - activePendingUserInputAnswers={requests.activePendingUserInputAnswers} - respondingUserInputId={requests.respondingUserInputId} - connectionStateLabel={routeConnectionState} - historyControls={historyControls} - activeThreadBusy={composer.activeThreadBusy} - canStopThread={awaitingBootstrapTurn || composer.interruptibleRunId !== null} - queuedRunEdit={composer.queuedRunEdit} - composerDraftKey={composer.composerDraftKey} - followUpBehavior={composer.followUpBehavior} - canSteerActiveTurn={composer.canSteerActiveTurn} - isSavingQueuedEdit={composer.isSavingQueuedEdit} - onCancelQueuedRunEdit={composer.cancelQueuedRunEdit} - onRemoveQueuedEditAttachment={composer.onRemoveQueuedEditAttachment} - environmentId={selectedThread.environmentId} - projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null} - threadCwd={selectedThreadCwd} - selectedThreadQueueCount={composer.selectedThreadQueueCount} - queuedMessages={ - selectedThreadCreation && selectedThreadCreation.outcome?.kind !== "delivered" - ? [selectedThreadCreation.message, ...composer.selectedThreadQueuedMessages] - : composer.selectedThreadQueuedMessages - } - dispatchingMessageId={composer.dispatchingQueuedMessageId} - layoutVariant={layout.variant} - usesAutomaticContentInsets={usesNativeHeaderGlass} - onOpenConnectionEditor={handleOpenConnectionEditor} - onChangeDraftMessage={composer.onChangeDraftMessage} - onPickDraftMedia={composer.onPickDraftMedia} - onPickDraftFiles={composer.onPickDraftFiles} - onNativePasteImages={composer.onNativePasteImages} - onNativePasteText={composer.onNativePasteText} - onRemoveDraftImage={composer.onRemoveDraftImage} - serverConfig={serverConfig} - onStopThread={awaitingBootstrapTurn ? handleCancelWorktreeSetup : handleStopThread} - onResumeQueue={composer.canResume ? handleResumeQueue : null} - onSendMessage={composer.onSendMessage} - offersSideChat={composer.sideChatUnavailableReason === null} - onSendCommand={composer.onSendCommand} - onReconnectEnvironment={handleReconnectEnvironment} - canSwitchThreadProvider={composer.canSwitchThreadProvider} - onRespondToApproval={requests.onRespondToApproval} - onSelectUserInputOption={requests.onSelectUserInputOption} - onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer} - onSubmitUserInput={requests.onSubmitUserInput} - onDismissUserInput={requests.onDismissUserInput} - /> - - - ); - return ( <> {inspectorHeader} @@ -1158,8 +1043,114 @@ function ThreadRouteContent( content={inspectorContent} /> ) : null} - - {renderThreadRouteBody()} + dismissGitActionResult(gitActionThreadRef)} + onOpenPullRequest={openPullRequest} + /> + + ) + } + canOperateThread={canOperateThread} + selectedThread={selectedThreadWithDraftSettings ?? selectedThread} + selectedThreadDetailRef={selectedThreadDetailRef} + contentPresentation={contentPresentation} + screenTone={connectionTone( + routeConnectionState, + routeEnvironmentRuntime?.connectionAwaitingApproval === true, + m, + )} + connectionError={routeConnectionError} + environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null} + feedbackSubmissions={composer.feedbackSubmissions} + onDismissFeedback={composer.dismissFeedback} + selectedThreadFeed={composer.selectedThreadFeed} + pendingHandoff={composer.pendingHandoff} + activityRun={composer.selectedThreadActivityRun} + activeWorkStartedAt={ + creationState?.kind === "preparing" || + (worktreeSetup !== null && setupTurnStartedAt === null) + ? null + : composer.activeWorkStartedAt + } + isCompacting={composer.isCompacting} + compactBeforeSend={composer.compactBeforeSend} + runlessWorkActive={composer.runlessWorkActive} + extensionStatuses={composer.extensionStatuses} + providerSubagentStatus={composer.providerSubagentStatus} + creationState={creationState} + worktreeSetup={ + worktreeSetup + ? { + snapshot: worktreeSetup, + turnStarted: setupTurnStartedAt !== null, + onCancel: handleCancelWorktreeSetup, + onWorkLocally: setupMessage && selectedThreadProject ? handleWorkLocally : null, + } + : null + } + activePendingApproval={requests.activePendingApproval} + activePendingApprovals={requests.activePendingApprovals} + respondingApprovalId={requests.respondingApprovalId} + activePendingUserInput={requests.activePendingUserInput} + activePendingUserInputDrafts={requests.activePendingUserInputDrafts} + activePendingUserInputAnswers={requests.activePendingUserInputAnswers} + respondingUserInputId={requests.respondingUserInputId} + connectionStateLabel={routeConnectionState} + historyControls={historyControls} + activeThreadBusy={composer.activeThreadBusy} + canStopThread={awaitingBootstrapTurn || composer.interruptibleRunId !== null} + queuedRunEdit={composer.queuedRunEdit} + composerDraftKey={composer.composerDraftKey} + followUpBehavior={composer.followUpBehavior} + canSteerActiveTurn={composer.canSteerActiveTurn} + isSavingQueuedEdit={composer.isSavingQueuedEdit} + onCancelQueuedRunEdit={composer.cancelQueuedRunEdit} + onRemoveQueuedEditAttachment={composer.onRemoveQueuedEditAttachment} + environmentId={selectedThread.environmentId} + projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null} + threadCwd={selectedThreadCwd} + selectedThreadQueueCount={composer.selectedThreadQueueCount} + queuedMessages={ + selectedThreadCreation && selectedThreadCreation.outcome?.kind !== "delivered" + ? [selectedThreadCreation.message, ...composer.selectedThreadQueuedMessages] + : composer.selectedThreadQueuedMessages + } + dispatchingMessageId={composer.dispatchingQueuedMessageId} + layoutVariant={layout.variant} + usesAutomaticContentInsets={usesNativeHeaderGlass} + onOpenConnectionEditor={handleOpenConnectionEditor} + onChangeDraftMessage={composer.onChangeDraftMessage} + onPickDraftMedia={composer.onPickDraftMedia} + onPickDraftFiles={composer.onPickDraftFiles} + onNativePasteImages={composer.onNativePasteImages} + onNativePasteText={composer.onNativePasteText} + onRemoveDraftImage={composer.onRemoveDraftImage} + serverConfig={serverConfig} + onStopThread={awaitingBootstrapTurn ? handleCancelWorktreeSetup : handleStopThread} + onResumeQueue={composer.canResume ? handleResumeQueue : null} + onSendMessage={composer.onSendMessage} + offersSideChat={composer.sideChatUnavailableReason === null} + onSendCommand={composer.onSendCommand} + onReconnectEnvironment={handleReconnectEnvironment} + canSwitchThreadProvider={composer.canSwitchThreadProvider} + onRespondToApproval={requests.onRespondToApproval} + onSelectUserInputOption={requests.onSelectUserInputOption} + onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer} + onSubmitUserInput={requests.onSubmitUserInput} + onDismissUserInput={requests.onDismissUserInput} + /> ); } diff --git a/apps/mobile/src/features/threads/ThreadScreenHost.test.tsx b/apps/mobile/src/features/threads/ThreadScreenHost.test.tsx new file mode 100644 index 0000000000000..c4edc836db37c --- /dev/null +++ b/apps/mobile/src/features/threads/ThreadScreenHost.test.tsx @@ -0,0 +1,104 @@ +import { act, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import type { ThreadDetailScreenProps } from "./ThreadDetailScreen"; +import { ThreadScreenBinding, ThreadScreenHost } from "./ThreadScreenHost"; + +const screen = vi.hoisted(() => ({ + renders: 0, + props: null as null | Record, +})); + +vi.mock("react-native", () => ({ + View: ({ children }: { children: ReactNode }) =>
{children}
, +})); +vi.mock("../../components/ui/ScreenContent", () => ({ + ScreenContent: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("./ThreadDetailScreen", () => ({ + ThreadDetailScreen: (props: Record) => { + screen.renders += 1; + screen.props = props; + return null; + }, +})); + +function Controller(props: { + readonly title: string; + readonly feed: ReadonlyArray; + readonly onSendMessage: () => string; + readonly threadId?: string; +}) { + return ( + {props.title}} + {...({ + selectedThread: { environmentId: "env", id: props.threadId ?? "a" }, + selectedThreadFeed: props.feed, + onSendMessage: props.onSendMessage, + } as unknown as ThreadDetailScreenProps)} + /> + ); +} + +describe("ThreadScreenHost", () => { + it("re-renders the thread screen only when its data changes", () => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + using _globals = { [Symbol.dispose]: () => vi.unstubAllGlobals() }; + const container = document.createElement("div"); + const root = createRoot(container); + using _root = { [Symbol.dispose]: () => act(() => root.unmount()) }; + const render = (title: string, feed: ReadonlyArray, reply: string) => + act(() => + root.render( + + reply} /> + , + ), + ); + + render("First", ["a", "b"], "first"); + expect(screen.renders).toBe(1); + const firstFeed = screen.props?.selectedThreadFeed; + + // A new handler and an equal feed array keep the screen as it is. + render("First", ["a", "b"], "second"); + expect(screen.renders).toBe(1); + const onSendMessage = screen.props?.onSendMessage as () => string; + expect(onSendMessage()).toBe("second"); + + // A header-only change updates the header without the screen. + render("Renamed", ["a", "b"], "second"); + expect(screen.renders).toBe(1); + expect(container.textContent).toBe("Renamed"); + + render("Renamed", ["a", "b", "c"], "second"); + expect(screen.renders).toBe(2); + expect(screen.props?.selectedThreadFeed).not.toBe(firstFeed); + expect(screen.props?.selectedThreadFeed).toEqual(["a", "b", "c"]); + }); + + it("keeps a handler taken on one thread bound to that thread", () => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + using _globals = { [Symbol.dispose]: () => vi.unstubAllGlobals() }; + const root = createRoot(document.createElement("div")); + using _root = { [Symbol.dispose]: () => act(() => root.unmount()) }; + const render = (threadId: string, reply: string) => + act(() => + root.render( + + reply} /> + , + ), + ); + + render("a", "from a"); + const sendOnA = screen.props!.onSendMessage as () => string; + // A send awaiting input on thread A must not run thread B's handler once B is shown. + render("b", "from b"); + expect(sendOnA()).toBe("from a"); + const sendOnB = screen.props!.onSendMessage as () => string; + expect(sendOnB()).toBe("from b"); + }); +}); diff --git a/apps/mobile/src/features/threads/ThreadScreenHost.tsx b/apps/mobile/src/features/threads/ThreadScreenHost.tsx index ff94ad39bd5fb..81c32fbadb685 100644 --- a/apps/mobile/src/features/threads/ThreadScreenHost.tsx +++ b/apps/mobile/src/features/threads/ThreadScreenHost.tsx @@ -12,11 +12,30 @@ import { ScreenContent } from "../../components/ui/ScreenContent"; import { ThreadDetailScreen, type ThreadDetailScreenProps } from "./ThreadDetailScreen"; type ThreadScreenContent = - | { readonly props: ThreadDetailScreenProps } + | { readonly props: ThreadDetailScreenProps; readonly header?: ReactNode } | { readonly fallback: ReactNode; readonly header?: ReactNode }; +type Handler = (...args: never[]) => unknown; + function createThreadScreenStore() { let current: ThreadScreenContent | null = null; + // One function per handler prop that calls the controller's latest handler, so a handler the + // controller recreates does not re-render the thread screen. Each thread gets its own set, so a + // send that awaits before calling its handler still reaches the thread it started on. + let handlers = { + thread: null as string | null, + latest: {} as Record, + stable: new Map(), + }; + const handler = (key: string) => { + const set = handlers; + let stable = set.stable.get(key); + if (stable === undefined) { + stable = (...args) => (set.latest[key] as Handler | undefined)?.(...args); + set.stable.set(key, stable); + } + return stable; + }; const listeners = new Set<() => void>(); return { getSnapshot: () => current, @@ -27,22 +46,83 @@ function createThreadScreenStore() { }; }, publish: (content: ThreadScreenContent) => { - current = content; + let next = content; + if ("props" in content) { + const latest = content.props as unknown as Record; + const thread = threadKey(content.props); + if (thread !== handlers.thread) handlers = { thread, latest, stable: new Map() }; + else handlers.latest = latest; + const shown = current !== null && "props" in current ? current : null; + const shownProps = (shown?.props ?? {}) as Record; + // Controllers rebuild arrays and records with the same contents on most renders; the + // screen keeps the ones it has, so its memoized feed and composer skip the update. + const props = Object.fromEntries( + Object.entries(latest).map(([key, value]) => [ + key, + typeof value === "function" + ? handler(key) + : sameContents(shownProps[key], value) + ? shownProps[key] + : value, + ]), + ) as unknown as ThreadDetailScreenProps; + const sameProps = shown !== null && shallowEqual(shown.props, props); + // Unchanged props keep their identity, so only the header re-renders when it alone changed. + if (sameProps && shown.header === content.header) return; + next = { props: sameProps ? shown.props : props, header: content.header }; + } + current = next; for (const listener of listeners) listener(); }, }; } + +function threadKey(props: ThreadDetailScreenProps): string | null { + const thread = props.selectedThread as ThreadDetailScreenProps["selectedThread"] | undefined; + return thread === undefined ? null : `${thread.environmentId}:${thread.id}`; +} + +function sameContents(previous: unknown, next: unknown): boolean { + if (Object.is(previous, next)) return true; + if (Array.isArray(previous) && Array.isArray(next)) { + return previous.length === next.length && previous.every((item, index) => item === next[index]); + } + return isPlainRecord(previous) && isPlainRecord(next) && shallowEqual(previous, next); +} + +function isPlainRecord(value: unknown): value is object { + if (typeof value !== "object" || value === null) return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} + +function shallowEqual(previous: object, next: object): boolean { + const previousRecord = previous as Record; + const nextRecord = next as Record; + const keys = Object.keys(nextRecord); + return ( + keys.length === Object.keys(previousRecord).length && + keys.every( + (key) => + Object.hasOwn(previousRecord, key) && Object.is(previousRecord[key], nextRecord[key]), + ) + ); +} + const ThreadScreenContext = createContext | null>(null); function ThreadScreenOutlet() { const store = useContext(ThreadScreenContext)!; const content = useSyncExternalStore(store.subscribe, store.getSnapshot); if (content === null) return null; - const body = "props" in content ? : content.fallback; + const screenProps = "props" in content ? content.props : null; + const fallback = "fallback" in content ? content.fallback : null; return ( <> - {"props" in content ? content.props.header : content.header} - {body} + {content.header} + + {screenProps === null ? fallback : } + ); } @@ -61,11 +141,15 @@ export function ThreadScreenHost({ children }: { readonly children: ReactNode }) ); } -export function ThreadScreenBinding(props: ThreadDetailScreenProps) { +/** Handler props reach the screen as stable functions; call them from handlers and effects only. */ +export function ThreadScreenBinding({ + header, + ...props +}: ThreadDetailScreenProps & { readonly header?: ReactNode }) { const store = useContext(ThreadScreenContext)!; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the route's thread screen props to the external store the outlet reads useLayoutEffect(() => { - store.publish({ props }); + store.publish({ props, header }); }); return null; } diff --git a/apps/mobile/src/features/threads/threadContentPresentation.ts b/apps/mobile/src/features/threads/threadContentPresentation.ts index a6157d43ad79b..cc3a9ec98f351 100644 --- a/apps/mobile/src/features/threads/threadContentPresentation.ts +++ b/apps/mobile/src/features/threads/threadContentPresentation.ts @@ -13,6 +13,10 @@ export type ThreadContentPresentation = readonly detail: string; }; +// Shared so the thread screen's props keep their identity across renders. +export const THREAD_CONTENT_READY: ThreadContentPresentation = { kind: "ready" }; +const THREAD_CONTENT_LOADING: ThreadContentPresentation = { kind: "loading" }; + export function projectThreadContentPresentation(input: { readonly hasDetail: boolean; readonly detailError: string | null; @@ -22,7 +26,7 @@ export function projectThreadContentPresentation(input: { }): ThreadContentPresentation { const resolve = input.resolve ?? m; if (input.hasDetail) { - return { kind: "ready" }; + return THREAD_CONTENT_READY; } if (input.detailDeleted) { return { @@ -43,7 +47,7 @@ export function projectThreadContentPresentation(input: { input.connectionState === "connecting" || input.connectionState === "reconnecting" ) { - return { kind: "loading" }; + return THREAD_CONTENT_LOADING; } return { kind: "unavailable", diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 41248bf9c1e88..b0610d37349f6 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -513,6 +513,22 @@ describe("buildThreadFeed", () => { }, ); + it("returns the cached feed when its rows have not changed", () => { + const message = (id: string, role: "user" | "assistant"): OrchestrationV2TurnItem => ({ + ...(role === "user" ? userMessage() : assistantMessage()), + id: TurnItemId.make(id), + messageId: MessageId.make(id), + }); + const rows = [ + projected(message("ask", "user"), 0), + projected(message("reply", "assistant"), 1), + ]; + const cache = createThreadFeedCache(); + const feed = buildThreadFeed(rows, { cache }); + expect(buildThreadFeed(rows, { cache })).toBe(feed); + expect(buildThreadFeed([...rows], { cache })).not.toBe(feed); + }); + it.each([false, true])( "keeps answered questions outside settled work (attachments only: %s)", (attachmentsOnly) => { diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 0d8e5d30b9b67..7767b085bdd8c 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -2515,7 +2515,7 @@ export function buildThreadFeed( /** Keys the caches; text comes from `resolve`. */ readonly locale?: string; }, -): ThreadFeedEntry[] { +): ReadonlyArray { const anchoredMessages = options?.anchoredMessages ?? []; const resolve = options?.resolve ?? m; const locale = options?.locale; @@ -2572,6 +2572,8 @@ export function buildThreadFeed( restartIndex -= 1; } } + // Unchanged rows rebuild the same feed; returning it keeps the screen's props equal. + if (restartIndex !== -1 && previous!.rows === visibleTurnItems) return previous!.feed; const restart = restartIndex === -1 ? null : previous!.restarts[restartIndex]!; const prefix = restart === null ? [] : previous!.feed.slice(0, restart.feedLength); const restarts = restart === null ? [] : previous!.restarts.slice(0, restartIndex + 1); diff --git a/apps/mobile/src/lib/useStableCallback.ts b/apps/mobile/src/lib/useStableCallback.ts new file mode 100644 index 0000000000000..b300259aef764 --- /dev/null +++ b/apps/mobile/src/lib/useStableCallback.ts @@ -0,0 +1,20 @@ +import { useInsertionEffect, useRef, useState } from "react"; + +/** Call only from handlers and effects; render sees the previous commit's fn. */ +export function useStableCallback, Result>( + fn: (...args: Args) => Result, +): (...args: Args) => Result { + const latest = useRef(fn); + // Insertion effects run before every layout effect in the commit, so a + // child's layout effect already calls this render's fn. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- updates the ref during commit, before any layout effect can call the stable callback + useInsertionEffect(() => { + latest.current = fn; + }); + const [stable] = useState( + () => + (...args: Args) => + latest.current(...args), + ); + return stable; +} diff --git a/apps/mobile/src/state/device.ts b/apps/mobile/src/state/device.ts index 0de502b5928c3..1d31bb14caa4e 100644 --- a/apps/mobile/src/state/device.ts +++ b/apps/mobile/src/state/device.ts @@ -1,9 +1,10 @@ import { createDeviceEnvironmentAtoms } from "@t3tools/client-runtime/state/device"; import { resolveDeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess"; -import type { EnvironmentId } from "@t3tools/contracts"; +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; -import { Atom } from "effect/reactivity"; +import { AsyncResult, Atom } from "effect/reactivity"; +import { useAtomValue } from "@effect/atom-react"; import { connectionAtomRuntime } from "../connection/runtime"; import { useEnvironmentQuery } from "./query"; @@ -11,6 +12,23 @@ import { environmentSession, usePreparedConnection } from "./session"; export const deviceEnvironment = createDeviceEnvironmentAtoms(connectionAtomRuntime); +// A number, so a device state read that leaves the thread's previews as they were re-renders nothing. +const threadDevicePreviewCountAtom = Atom.family((key: string) => { + const [environmentId, threadId] = JSON.parse(key) as [EnvironmentId, ThreadId]; + return Atom.make((get) => { + const state = AsyncResult.getOrElse( + get(deviceEnvironment.state({ environmentId, input: {} })), + () => null, + ); + return (state?.sessions ?? []).filter((session) => session.threadId === threadId).length; + }); +}); + +/** How many device previews belong to the thread. */ +export function useThreadDevicePreviewCount(environmentId: EnvironmentId, threadId: ThreadId) { + return useAtomValue(threadDevicePreviewCountAtom(JSON.stringify([environmentId, threadId]))); +} + // Hub tickets are single use, so each viewer resolves its own access: a new // viewer (a reload, a device switch, a return to the screen) never reuses a // ticket an earlier connection already spent. diff --git a/apps/mobile/src/state/preview.ts b/apps/mobile/src/state/preview.ts index f82235eaaf339..3d5b87b4e31b8 100644 --- a/apps/mobile/src/state/preview.ts +++ b/apps/mobile/src/state/preview.ts @@ -123,20 +123,60 @@ const threadPreviewTabsAtom = Atom.family((threadKey: string) => { }).pipe(Atom.setIdleTTL(1_000), Atom.withLabel(`mobile-preview-tabs:${threadKey}`)); }); +interface ServerBrowserTabs { + readonly tabs: ReadonlyArray; + readonly loaded: boolean; +} + +const sameServerBrowserTabs = (previous: ServerBrowserTabs, next: ServerBrowserTabs) => + previous.loaded === next.loaded && + previous.tabs.length === next.tabs.length && + previous.tabs.every((tab, index) => tab === next.tabs[index]); + +// A list or event that leaves the thread's server tabs as they were notifies no one, so the +// thread screen does not re-render each time it reads the list again. +const serverBrowserTabsAtom = Atom.family((threadKey: string) => + Atom.make((get): ServerBrowserTabs => { + const tabs = get(threadPreviewTabsAtom(threadKey)); + return { + tabs: tabs.sessions.filter((session) => session.runtime === "server"), + loaded: tabs.listed, + }; + }).pipe(Atom.withEquality(sameServerBrowserTabs), Atom.setIdleTTL(1_000)), +); +const emptyServerBrowserTabsAtom = Atom.make({ tabs: [], loaded: false }); +const serverBrowserTabCountAtom = Atom.family((threadKey: string) => + Atom.make((get) => get(serverBrowserTabsAtom(threadKey)).tabs.length), +); +const noServerBrowserTabsAtom = Atom.make(0); + export function useThreadServerBrowserTabs(input: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId; readonly enabled: boolean; -}) { - const tabs = useAtomValue( +}): ServerBrowserTabs { + return useAtomValue( + input.enabled + ? serverBrowserTabsAtom( + scopedThreadKey({ environmentId: input.environmentId, threadId: input.threadId }), + ) + : emptyServerBrowserTabsAtom, + ); +} + +/** How many server browser tabs the thread has, for screens that only show the count. */ +export function useThreadServerBrowserTabCount(input: { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly enabled: boolean; +}): number { + return useAtomValue( input.enabled - ? threadPreviewTabsAtom( + ? serverBrowserTabCountAtom( scopedThreadKey({ environmentId: input.environmentId, threadId: input.threadId }), ) - : emptyTabsAtom, + : noServerBrowserTabsAtom, ); - const sessions = tabs.sessions.filter((session) => session.runtime === "server"); - return { tabs: sessions, loaded: tabs.listed }; } // The earliest time the next access request may go out. diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index c3dd6195f3f03..6a0a7f5d96ea3 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -56,6 +56,7 @@ const reactTests = [ "src/features/threads/use-thread-list-now.test.tsx", "src/features/threads/use-composer-command-menu.select.test.tsx", "src/features/threads/useSidebarRowThreadKey.test.tsx", + "src/features/threads/ThreadScreenHost.test.tsx", "src/features/threads/useThreadListV2.test.tsx", "src/features/home/home-list-options.test.tsx", "src/features/home/home-route-visibility.test.tsx",