TypeScript
perf(mobile): files, review and remaining settings screens compile with the React Compiler (#21124)
Julius Marminge0ee07e32ab35
diff --git a/apps/mobile/src/features/files/AttachmentFileScreen.tsx b/apps/mobile/src/features/files/AttachmentFileScreen.tsxindex d3e07e40fa2..5a92ea913b5 100644--- a/apps/mobile/src/features/files/AttachmentFileScreen.tsx+++ b/apps/mobile/src/features/files/AttachmentFileScreen.tsx@@ -6,7 +6,7 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native"import type { MenuAction } from "@react-native-menu/menu";import { EnvironmentId } from "@t3tools/contracts";import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useEffect, useRef, useState } from "react";import { Platform, ScrollView, View } from "react-native";import {@@ -196,9 +196,9 @@ export function AttachmentFileScreen(props: AttachmentFileScreenProps) {);const [nativeError, setNativeError] = useState<string | null>(null);const pendingNativeError = useRef<string | null>(null);- const handleBack = useCallback(() => {+ const handleBack = () => {if (navigation.canGoBack()) navigation.goBack();- }, [navigation]);+ };const { uri, resource } = document;useEffect(() => {if (nativeViewer !== "pending" || !uri) return;@@ -208,17 +208,17 @@ export function AttachmentFileScreen(props: AttachmentFileScreenProps) {}, [nativeViewer, uri]);// The viewer mints its own fresh URL from the resource, so a link that expired while this// screen sat in the background is never handed to Quick Look or ACTION_VIEW.- const nativeSource = useMemo<FilePreviewSource | null>(() => {+ const nativeSource = ((): FilePreviewSource | null => {const kind = nativeKind ?? "document";const base = { kind, name: params.name, mimeType: params.mimeType };if (localAttachment) return { ...base, attachment: localAttachment };if (environmentId) return { ...base, environmentId, resource };return uri ? { ...base, uri } : null;- }, [environmentId, localAttachment, nativeKind, params.mimeType, params.name, resource, uri]);- const handleNativeOpenError = useCallback((error: unknown) => {+ })();+ const handleNativeOpenError = (error: unknown) => {pendingNativeError.current = nativeViewerErrorMessage(error);- }, []);- const handleNativeClose = useCallback(() => {+ };+ const handleNativeClose = () => {setNativeOpen(false);const message = pendingNativeError.current;pendingNativeError.current = null;@@ -233,117 +233,94 @@ export function AttachmentFileScreen(props: AttachmentFileScreenProps) {return;}handleBack();- }, [handleBack, nativeViewer]);- const removeFromDraft = useCallback(() => {+ };+ const removeFromDraft = () => {if (!draftKey) return;removeComposerDraftAttachment(draftKey, params.attachmentId);handleBack();- }, [draftKey, handleBack, params.attachmentId]);+ };const { content, renderedMode, activeMode, setRendered, share, sharing } = document;- const menuActions = useMemo(- () =>- [- renderedMode- ? ({- id: "preview",- title: renderedMode === "table" ? "Table" : "Preview",- icon: renderedMode === "table" ? "tablecells" : "eye",- inline: true,- onPress: () => setRendered(true),- } as const)- : null,- renderedMode- ? ({- id: "source",- title: "Source",- icon: "doc.text",- inline: true,- onPress: () => setRendered(false),- } as const)- : null,- content && activeMode === "source"- ? ({- id: "word-wrap",- title: appearance.codeWordBreak ? "Disable word wrap" : "Enable word wrap",- icon: "text.alignleft",- inline: false,- onPress: () => setCodeWordBreak(!appearance.codeWordBreak),- } as const)- : null,- content- ? ({- id: "copy",- title: content.truncated ? "Copy preview" : "Copy contents",- icon: "doc.on.doc",- inline: false,- onPress: () => copyTextWithHaptic(content.text),- } as const)- : null,- uri- ? ({- id: "share",- title: sharing ? "Opening share sheet…" : "Save or share",- icon: "square.and.arrow.up",- inline: false,- onPress: () => void share(),- } as const)- : null,- uri- ? ({- id: "open-viewer",- title: "Open in file viewer",- icon: "arrow.up.left.and.arrow.down.right",- inline: false,- onPress: () => {- setNativeViewer((current) => (current === null ? null : "open"));- setNativeOpen(true);- },- } as const)- : null,- draftKey- ? ({- id: "remove",- title: "Remove from draft",- icon: "trash",- inline: false,- destructive: true,- onPress: removeFromDraft,- } as const)- : null,- ].filter((action) => action !== null),- [- appearance.codeWordBreak,- setCodeWordBreak,- content,- draftKey,- removeFromDraft,- activeMode,- renderedMode,- setRendered,- share,- sharing,- uri,- ],- );+ const menuActions = [+ renderedMode+ ? ({+ id: "preview",+ title: renderedMode === "table" ? "Table" : "Preview",+ icon: renderedMode === "table" ? "tablecells" : "eye",+ inline: true,+ onPress: () => setRendered(true),+ } as const)+ : null,+ renderedMode+ ? ({+ id: "source",+ title: "Source",+ icon: "doc.text",+ inline: true,+ onPress: () => setRendered(false),+ } as const)+ : null,+ content && activeMode === "source"+ ? ({+ id: "word-wrap",+ title: appearance.codeWordBreak ? "Disable word wrap" : "Enable word wrap",+ icon: "text.alignleft",+ inline: false,+ onPress: () => setCodeWordBreak(!appearance.codeWordBreak),+ } as const)+ : null,+ content+ ? ({+ id: "copy",+ title: content.truncated ? "Copy preview" : "Copy contents",+ icon: "doc.on.doc",+ inline: false,+ onPress: () => copyTextWithHaptic(content.text),+ } as const)+ : null,+ uri+ ? ({+ id: "share",+ title: sharing ? "Opening share sheet…" : "Save or share",+ icon: "square.and.arrow.up",+ inline: false,+ onPress: () => void share(),+ } as const)+ : null,+ uri+ ? ({+ id: "open-viewer",+ title: "Open in file viewer",+ icon: "arrow.up.left.and.arrow.down.right",+ inline: false,+ onPress: () => {+ setNativeViewer((current) => (current === null ? null : "open"));+ setNativeOpen(true);+ },+ } as const)+ : null,+ draftKey+ ? ({+ id: "remove",+ title: "Remove from draft",+ icon: "trash",+ inline: false,+ destructive: true,+ onPress: removeFromDraft,+ } as const)+ : null,+ ].filter((action) => action !== null);const selectedAction = activeMode === "source" ? "source" : "preview";- const androidMenuActions = useMemo<MenuAction[]>(- () =>- menuActions.map((action) => ({- id: action.id,- title: action.title,- image: action.icon,- state: action.inline ? (action.id === selectedAction ? "on" : "off") : undefined,- ...("destructive" in action ? { attributes: { destructive: true } } : {}),- })),- [selectedAction, menuActions],- );- const handleAndroidMenuAction = useCallback(- (event: { nativeEvent: { event: string } }) => {- menuActions.find(({ id }) => id === event.nativeEvent.event)?.onPress();- },- [menuActions],- );+ const androidMenuActions = menuActions.map((action) => ({+ id: action.id,+ title: action.title,+ image: action.icon,+ state: action.inline ? (action.id === selectedAction ? "on" : "off") : undefined,+ ...("destructive" in action ? { attributes: { destructive: true } } : {}),+ })) satisfies MenuAction[];+ const handleAndroidMenuAction = (event: { nativeEvent: { event: string } }) => {+ menuActions.find(({ id }) => id === event.nativeEvent.event)?.onPress();+ };const subtitle = `${draftKey ? "Draft attachment" : "Attachment"}${sizeBytes > 0 ? ` · ${formatAttachmentSize(sizeBytes)}` : ""}`;return (diff --git a/apps/mobile/src/features/files/FileMarkdownPreview.tsx b/apps/mobile/src/features/files/FileMarkdownPreview.tsxindex f2c30e59f12..f279c6d8ceb 100644--- a/apps/mobile/src/features/files/FileMarkdownPreview.tsx+++ b/apps/mobile/src/features/files/FileMarkdownPreview.tsx@@ -1,7 +1,8 @@+import { settlePromise } from "@t3tools/client-runtime/state/runtime";import type { EnvironmentId, ThreadId } from "@t3tools/contracts";import { resolveMobileMarkdownMediaSource } from "../../lib/markdownMediaSource";import { getBrowseDirectoryPath } from "@t3tools/client-runtime/state/projects";-import { useCallback, useMemo, useState } from "react";+import { useState } from "react";import { RefreshControl, ScrollView, View } from "react-native";import { tryOpenExternalUrl } from "../../lib/openExternalUrl";@@ -33,10 +34,7 @@ interface MarkdownPreviewStyles {export function useMarkdownPreviewStyles(): MarkdownPreviewStyles {const { appearance } = useAppearancePreferences();- const nativeMarkdownTypography = useMemo(- () => resolveNativeMarkdownTypography(appearance.baseFontSize),- [appearance.baseFontSize],- );+ const nativeMarkdownTypography = resolveNativeMarkdownTypography(appearance.baseFontSize);const theme = useUniwindTheme();const body = theme["--color-md-body"];const strong = theme["--color-md-strong"];@@ -48,41 +46,28 @@ export function useMarkdownPreviewStyles(): MarkdownPreviewStyles {const regularFontFamily = FONT_FAMILIES.regular;const boldFontFamily = FONT_FAMILIES.bold;- return useMemo(() => {- return {- nativeTextStyle: {- color: body,- strongColor: strong,- mutedColor: body,- linkColor: link,- inlineCodeColor: codeText,- codeColor: codeText,- codeBackgroundColor: codeBackground,- codeBlockBackgroundColor: codeBackground,- fileTextColor: codeText,- skillTextColor: codeText,- quoteMarkerColor: blockquoteBorder,- dividerColor: horizontalRule,- fontSize: nativeMarkdownTypography.fontSize,- lineHeight: nativeMarkdownTypography.lineHeight,- headingFontSizes: nativeMarkdownTypography.headingFontSizes,- fontFamily: regularFontFamily,- headingFontFamily: boldFontFamily,- boldFontFamily,- },- };- }, [- blockquoteBorder,- body,- codeBackground,- codeText,- horizontalRule,- link,- nativeMarkdownTypography,- regularFontFamily,- strong,- boldFontFamily,- ]);+ return {+ nativeTextStyle: {+ color: body,+ strongColor: strong,+ mutedColor: body,+ linkColor: link,+ inlineCodeColor: codeText,+ codeColor: codeText,+ codeBackgroundColor: codeBackground,+ codeBlockBackgroundColor: codeBackground,+ fileTextColor: codeText,+ skillTextColor: codeText,+ quoteMarkerColor: blockquoteBorder,+ dividerColor: horizontalRule,+ fontSize: nativeMarkdownTypography.fontSize,+ lineHeight: nativeMarkdownTypography.lineHeight,+ headingFontSizes: nativeMarkdownTypography.headingFontSizes,+ fontFamily: regularFontFamily,+ headingFontFamily: boldFontFamily,+ boldFontFamily,+ },+ };}export function FileMarkdownPreview(props: {@@ -97,85 +82,79 @@ export function FileMarkdownPreview(props: {const [isPullRefreshing, setIsPullRefreshing] = useState(false);const [expandedFile, setExpandedFile] = useState<FilePreviewSource | null>(null);const [expandedVideo, setExpandedVideo] = useState<VideoPreviewSource | null>(null);- const handlePullToRefresh = useCallback(async () => {+ const handlePullToRefresh = async () => {if (!props.onRefresh) {return;}setIsPullRefreshing(true);- try {- await props.onRefresh();- } finally {- setIsPullRefreshing(false);- }- }, [props.onRefresh]);- const markdownDirectory = useMemo(- () => getBrowseDirectoryPath(resolveWorkspaceFilePath(props.cwd, props.relativePath)),- [props.cwd, props.relativePath],+ // RefreshControl only needs the spinner cleared; the caller surfaces its own errors.+ await settlePromise(async () => props.onRefresh?.());+ setIsPullRefreshing(false);+ };+ const markdownDirectory = getBrowseDirectoryPath(+ resolveWorkspaceFilePath(props.cwd, props.relativePath),);- const renderImage = useCallback<MarkdownImageRenderer>(- (image) => {- const media = resolveMobileMarkdownMediaSource(image.href, {- threadId: props.threadId ?? undefined,- workspaceRoot: markdownDirectory,- imageEmbed: true,- });- const preview = resolveMarkdownMediaPreview(image.href, {- environmentId: props.environmentId,- threadId: props.threadId ?? undefined,- workspaceRoot: markdownDirectory,- captured: props.captured,- imageEmbed: true,- });- if (media?.access === "direct") {- if (media.kind === "video") {- return (- <ThreadMarkdownVideo- source={{- type: "media",- name: media.name,- mimeType: media.mimeType,- uri: normalizeNativeMarkdownUrl(media.uri),- actionsSource: preview?.source.actionsSource,- }}- thumbnailVisible- />- );- }+ const renderImage: MarkdownImageRenderer = (image) => {+ const media = resolveMobileMarkdownMediaSource(image.href, {+ threadId: props.threadId ?? undefined,+ workspaceRoot: markdownDirectory,+ imageEmbed: true,+ });+ const preview = resolveMarkdownMediaPreview(image.href, {+ environmentId: props.environmentId,+ threadId: props.threadId ?? undefined,+ workspaceRoot: markdownDirectory,+ captured: props.captured,+ imageEmbed: true,+ });+ if (media?.access === "direct") {+ if (media.kind === "video") {return (- <ThreadMarkdownImageView- uri={normalizeNativeMarkdownUrl(media.uri)}- sourceKey={media.uri}- unavailable={false}- alt={image.alt}- format={media.mimeType === "image/svg+xml" ? "svg" : undefined}- actionsSource={preview?.source.actionsSource}- onPressPreview={setExpandedFile}+ <ThreadMarkdownVideo+ source={{+ type: "media",+ name: media.name,+ mimeType: media.mimeType,+ uri: normalizeNativeMarkdownUrl(media.uri),+ actionsSource: preview?.source.actionsSource,+ }}+ thumbnailVisible/>);}- if (props.captured || media === null || media.access === "unavailable") {- return <ThreadMarkdownImageUnavailable alt={image.alt} />;- }- if (media.kind === "video") {- return preview?.kind === "video" ? (- <ThreadMarkdownVideo source={preview.source} thumbnailVisible />- ) : (- <ThreadMarkdownImageUnavailable alt={image.alt} />- );- }return (- <ThreadMarkdownImage- environmentId={props.environmentId}- resource={media.resource}+ <ThreadMarkdownImageView+ uri={normalizeNativeMarkdownUrl(media.uri)}+ sourceKey={media.uri}+ unavailable={false}alt={image.alt}- srcFragment={media.srcFragment}+ format={media.mimeType === "image/svg+xml" ? "svg" : undefined}actionsSource={preview?.source.actionsSource}onPressPreview={setExpandedFile}/>);- },- [markdownDirectory, props.environmentId, props.threadId, props.captured],- );+ }+ if (props.captured || media === null || media.access === "unavailable") {+ return <ThreadMarkdownImageUnavailable alt={image.alt} />;+ }+ if (media.kind === "video") {+ return preview?.kind === "video" ? (+ <ThreadMarkdownVideo source={preview.source} thumbnailVisible />+ ) : (+ <ThreadMarkdownImageUnavailable alt={image.alt} />+ );+ }+ return (+ <ThreadMarkdownImage+ environmentId={props.environmentId}+ resource={media.resource}+ alt={image.alt}+ srcFragment={media.srcFragment}+ actionsSource={preview?.source.actionsSource}+ onPressPreview={setExpandedFile}+ />+ );+ };const styles = useMarkdownPreviewStyles();const resolveImageSource = useMarkdownImageSource({environmentId: props.environmentId,@@ -183,34 +162,25 @@ export function FileMarkdownPreview(props: {workspaceRoot: markdownDirectory,captured: props.captured,});- const openMedia = useCallback(- (href: string, imageEmbed = false) => {- const media = resolveMarkdownMediaPreview(href, {- environmentId: props.environmentId,- threadId: props.threadId ?? undefined,- workspaceRoot: markdownDirectory,- captured: props.captured,- imageEmbed,- });- if (!media) return false;- if (media.kind === "video") setExpandedVideo(media.source);- else setExpandedFile(media.source);- return true;- },- [markdownDirectory, props.environmentId, props.threadId, props.captured],- );- const onImagePress = useCallback(- (href: string) => {- openMedia(href, true);- },- [openMedia],- );- const onLinkPress = useCallback(- (href: string) => {- if (!openMedia(href)) void tryOpenExternalUrl(href, "markdown-link");- },- [openMedia],- );+ const openMedia = (href: string, imageEmbed = false) => {+ const media = resolveMarkdownMediaPreview(href, {+ environmentId: props.environmentId,+ threadId: props.threadId ?? undefined,+ workspaceRoot: markdownDirectory,+ captured: props.captured,+ imageEmbed,+ });+ if (!media) return false;+ if (media.kind === "video") setExpandedVideo(media.source);+ else setExpandedFile(media.source);+ return true;+ };+ const onImagePress = (href: string) => {+ openMedia(href, true);+ };+ const onLinkPress = (href: string) => {+ if (!openMedia(href)) void tryOpenExternalUrl(href, "markdown-link");+ };return (<ScrollViewdiff --git a/apps/mobile/src/features/files/FileTreeBrowser.tsx b/apps/mobile/src/features/files/FileTreeBrowser.tsxindex ba96fbbdf29..dd3fd1a574c 100644--- a/apps/mobile/src/features/files/FileTreeBrowser.tsx+++ b/apps/mobile/src/features/files/FileTreeBrowser.tsx@@ -2,7 +2,7 @@ import { LegendList } from "@legendapp/list/react-native";import type { ProjectEntry } from "@t3tools/contracts";import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";import { SymbolView } from "../../components/ui/AppSymbol";-import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useEffect, useRef, useState } from "react";import { Platform, Pressable, RefreshControl, View } from "react-native";import { useSafeAreaInsets } from "react-native-safe-area-context";@@ -39,7 +39,7 @@ function ancestorPaths(path: string): ReadonlyArray<string> {return ancestors;}-const FileTreeRow = memo(function FileTreeRow(props: {+const FileTreeRow = function FileTreeRow(props: {readonly item: VisibleFileTreeNode;readonly selected: boolean;readonly expanded: boolean;@@ -102,7 +102,7 @@ const FileTreeRow = memo(function FileTreeRow(props: {) : null}</Pressable>);-});+};export function FileTreeBrowser(props: {readonly entries: ReadonlyArray<ProjectEntry>;@@ -134,24 +134,18 @@ export function FileTreeBrowser(props: {loadingDirectories,selectedPath: controlledSelectedPath,} = props;- const controlledSelectedPathRef = useRef(controlledSelectedPath);const pendingSelectionTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);- controlledSelectedPathRef.current = controlledSelectedPath;const selectedPath =pendingSelection?.selectedPathAtPress === controlledSelectedPath? pendingSelection.path: controlledSelectedPath;- const tree = useMemo(() => cachedFileTree(props.entries), [props.entries]);- const visibleNodes = useMemo(- () =>- flattenFileTree({- nodes: tree,- expanded: expandedPaths,- searchResultPaths: props.searchResultPaths,- }),- [expandedPaths, props.searchResultPaths, tree],- );+ const tree = cachedFileTree(props.entries);+ const visibleNodes = flattenFileTree({+ nodes: tree,+ expanded: expandedPaths,+ searchResultPaths: props.searchResultPaths,+ });useEffect(() => {if (!controlledSelectedPath) {@@ -183,64 +177,45 @@ export function FileTreeBrowser(props: {[],);- const toggleDirectory = useCallback(- (path: string, expand: boolean) => {- if (expand) onLoadDirectory(path);- setExpandedPaths((current) => {- const next = new Set(current);- if (next.has(path)) {- next.delete(path);- } else {- next.add(path);- }- return next;- });- },- [onLoadDirectory],- );- const handleSelectFile = useCallback(- (path: string) => {- if (pendingSelectionTimeoutRef.current !== null) {- clearTimeout(pendingSelectionTimeoutRef.current);+ const toggleDirectory = (path: string, expand: boolean) => {+ if (expand) onLoadDirectory(path);+ setExpandedPaths((current) => {+ const next = new Set(current);+ if (next.has(path)) {+ next.delete(path);+ } else {+ next.add(path);}- setPendingSelection({- path,- selectedPathAtPress: controlledSelectedPathRef.current,- });- pendingSelectionTimeoutRef.current = setTimeout(() => {- pendingSelectionTimeoutRef.current = null;- setPendingSelection((current) => (current?.path === path ? null : current));- }, OPTIMISTIC_SELECTION_TIMEOUT_MS);- onSelectFile(path);- },- [onSelectFile],- );- const renderItem = useCallback(- ({ item }: { readonly item: VisibleFileTreeNode }) => (- <FileTreeRow- item={item}- selected={item.node.kind === "file" && item.node.path === selectedPath}- expanded={expandedPaths.has(item.node.path)}- loading={loadingDirectories.has(item.node.path)}- onPressDirectory={toggleDirectory}- onPreviewFile={onPreviewFile}- onPressFile={handleSelectFile}- />- ),- [- expandedPaths,- handleSelectFile,- onPreviewFile,- loadingDirectories,- selectedPath,- toggleDirectory,- ],+ return next;+ });+ };+ const handleSelectFile = (path: string) => {+ if (pendingSelectionTimeoutRef.current !== null) {+ clearTimeout(pendingSelectionTimeoutRef.current);+ }+ setPendingSelection({+ path,+ selectedPathAtPress: controlledSelectedPath,+ });+ pendingSelectionTimeoutRef.current = setTimeout(() => {+ pendingSelectionTimeoutRef.current = null;+ setPendingSelection((current) => (current?.path === path ? null : current));+ }, OPTIMISTIC_SELECTION_TIMEOUT_MS);+ onSelectFile(path);+ };+ const renderItem = ({ item }: { readonly item: VisibleFileTreeNode }) => (+ <FileTreeRow+ item={item}+ selected={item.node.kind === "file" && item.node.path === selectedPath}+ expanded={expandedPaths.has(item.node.path)}+ loading={loadingDirectories.has(item.node.path)}+ onPressDirectory={toggleDirectory}+ onPreviewFile={onPreviewFile}+ onPressFile={handleSelectFile}+ />);- const extraData = useMemo(- () => ({ expandedPaths, loadingDirectories, selectedPath }),- [expandedPaths, loadingDirectories, selectedPath],- );+ const extraData = { expandedPaths, loadingDirectories, selectedPath };// UIKit owns the header inset on every supported iOS version. Keep the// list as direct screen content so automatic inset adjustment can find it.diff --git a/apps/mobile/src/features/files/SourceFileSurface.tsx b/apps/mobile/src/features/files/SourceFileSurface.tsxindex bdc95a02fb9..d1d92092a55 100644--- a/apps/mobile/src/features/files/SourceFileSurface.tsx+++ b/apps/mobile/src/features/files/SourceFileSurface.tsx@@ -1,7 +1,8 @@+import { settlePromise } from "@t3tools/client-runtime/state/runtime";import { useAtomValue } from "@effect/atom-react";import { AsyncResult } from "effect/reactivity";import type { ComponentType } from "react";-import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useEffect, useRef, useState } from "react";import {FlatList,Platform,@@ -49,7 +50,7 @@ interface SourceFileSurfaceProps {type SourceHighlightStatus = "highlighting" | "ready" | "error";-const HighlightedSourceLine = memo(function HighlightedSourceLine(props: {+const HighlightedSourceLine = function HighlightedSourceLine(props: {readonly codeSurface: ResolvedMobileCodeSurface;readonly index: number;readonly line: string;@@ -124,20 +125,21 @@ const HighlightedSourceLine = memo(function HighlightedSourceLine(props: {</NativeText></View>);-});+};function useSourceFileModel(props: SourceFileSurfaceProps) {const { themeAppearance: theme } = useAppearancePreferences();- const document = useMemo(() => prepareSourceFileDocument(props.contents), [props.contents]);+ const document = prepareSourceFileDocument(props.contents);const { contents: normalizedContents, lines, rowsJson } = document;const targetIndex =props.initialLine !== null && props.initialLine !== undefined && props.initialLine > 0? Math.min(Math.floor(props.initialLine) - 1, Math.max(0, lines.length - 1)): null;- const highlightAtom = useMemo(- () => sourceHighlightAtom({ path: props.path, contents: normalizedContents, theme }),- [normalizedContents, props.path, theme],- );+ const highlightAtom = sourceHighlightAtom({+ path: props.path,+ contents: normalizedContents,+ theme,+ });const highlightResult = useAtomValue(highlightAtom);const tokens = AsyncResult.isSuccess(highlightResult) ? highlightResult.value : null;const status: SourceHighlightStatus = AsyncResult.isFailure(highlightResult)@@ -165,17 +167,15 @@ function SourceHighlightStatusView(props: { readonly status: SourceHighlightStatfunction useSourceFileRefresh(onRefresh: SourceFileSurfaceProps["onRefresh"]) {const [isPullRefreshing, setIsPullRefreshing] = useState(false);- const handlePullToRefresh = useCallback(async () => {+ const handlePullToRefresh = async () => {if (!onRefresh) {return;}setIsPullRefreshing(true);- try {- await onRefresh();- } finally {- setIsPullRefreshing(false);- }- }, [onRefresh]);+ // RefreshControl only needs the spinner cleared; the caller surfaces its own errors.+ await settlePromise(async () => onRefresh());+ setIsPullRefreshing(false);+ };return { isPullRefreshing, handlePullToRefresh };}@@ -194,16 +194,12 @@ function NativeSourceFileSurface(const { width: viewportWidth } = useWindowDimensions();const { rowsJson, status, targetIndex, tokens } = useSourceFileModel(props);const { isPullRefreshing, handlePullToRefresh } = useSourceFileRefresh(onRefresh);- const tokensJson = useMemo(() => JSON.stringify(buildNativeSourceTokens(tokens)), [tokens]);- const selectedRowIdsJson = useMemo(- () => JSON.stringify(targetIndex === null ? [] : [nativeSourceRowId(targetIndex)]),- [targetIndex],- );- const themeJson = useMemo(- () => JSON.stringify(createNativeReviewDiffTheme(themeAppearance, themeId, appTheme)),- [appTheme, themeAppearance, themeId],+ const tokensJson = JSON.stringify(buildNativeSourceTokens(tokens));+ const selectedRowIdsJson = JSON.stringify(+ targetIndex === null ? [] : [nativeSourceRowId(targetIndex)],);- const styleJson = useMemo(() => JSON.stringify(nativeSourceStyle), [nativeSourceStyle]);+ const themeJson = JSON.stringify(createNativeReviewDiffTheme(themeAppearance, themeId, appTheme));+ const styleJson = JSON.stringify(nativeSourceStyle);const contentWidth = codeWordBreak? Math.max(240, viewportWidth - codeSurface.gutterWidth - 24): NATIVE_SOURCE_CONTENT_WIDTH;@@ -243,10 +239,7 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {const foreground = useUniwindTheme()["--color-foreground"];const { codeSurface, codeWordBreak } = useAppearanceCodeSurface();const { normalizedContents, lines, status, targetIndex, tokens } = useSourceFileModel(props);- const selectableTokens = useMemo(- () => (props.selectable ? boundedSelectableSourceTokens(tokens) : null),- [props.selectable, tokens],- );+ const selectableTokens = props.selectable ? boundedSelectableSourceTokens(tokens) : null;const listRef = useRef<FlatList<string>>(null);const { isPullRefreshing, handlePullToRefresh } = useSourceFileRefresh(props.onRefresh);const refreshControl = props.onRefresh ? (@@ -263,18 +256,15 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {return () => cancelAnimationFrame(frame);}, [props.path, targetIndex]);- const renderLine = useCallback(- ({ item, index }: { item: string; index: number }) => (- <HighlightedSourceLine- codeSurface={codeSurface}- index={index}- line={item}- tokens={tokens?.[index] ?? null}- highlighted={index === targetIndex}- wordBreak={codeWordBreak}- />- ),- [codeSurface, codeWordBreak, targetIndex, tokens],+ const renderLine = ({ item, index }: { item: string; index: number }) => (+ <HighlightedSourceLine+ codeSurface={codeSurface}+ index={index}+ line={item}+ tokens={tokens?.[index] ?? null}+ highlighted={index === targetIndex}+ wordBreak={codeWordBreak}+ />);// On iOS `uiTextView` renders a real `UITextView`, which selects across every line,diff --git a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsxindex 5150473f508..a95f8ea8e99 100644--- a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx+++ b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx@@ -2,7 +2,7 @@ import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesimport { environmentSession } from "../../state/session";import { NativeStackScreenOptions } from "../../native/StackHeader";import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";-import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";+import { useEffect, useId, useRef, useState } from "react";import { Platform, View } from "react-native";import { useSafeAreaInsets } from "react-native-safe-area-context";import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";@@ -442,7 +442,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {cwd: !canReadFiles || fileInspector.supported ? null : cwd,searchQuery,});- const handleReturnToThread = useCallback(() => {+ const handleReturnToThread = () => {if (navigation.canGoBack()) {navigation.goBack();return;@@ -455,57 +455,48 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {}),);}- }, [environmentId, navigation, threadId]);+ };- const handleSelectFile = useCallback(- (path: string) => {- if (environmentId === null || threadId === null) {- return;- }- const params = {- environmentId: String(environmentId),- threadId: String(threadId),- path: path.split("/").filter((segment) => segment.length > 0),- };- const navigationAction = resolveFileSelectionNavigationAction({- hasPersistentFileInspector: fileInspector.supported,- });- if (navigationAction === "replace") {- navigation.dispatch(StackActions.replace("ThreadFile", params));- return;- }- navigation.navigate("ThreadFile", params);- },- [environmentId, fileInspector.supported, navigation, threadId],- );- const renderInspector = useCallback(- (headerInset: number) =>- environmentId !== null && cwd !== null ? (- <ThreadFileNavigatorPane- cwd={cwd}- environmentId={environmentId}- headerInset={headerInset}- projectName={projectName}- selectedPath={null}- onSelectFile={handleSelectFile}- />- ) : null,- [cwd, environmentId, handleSelectFile, projectName],- );- const handlePreviewFile = useCallback(- (relativePath: string) => {- if (environmentId === null || cwd === null) {- return;- }- preloadWorkspaceFileContents({- cwd,- environmentId,- relativePath,- theme: highlightTheme,- });- },- [cwd, environmentId, highlightTheme],- );+ const handleSelectFile = (path: string) => {+ if (environmentId === null || threadId === null) {+ return;+ }+ const params = {+ environmentId: String(environmentId),+ threadId: String(threadId),+ path: path.split("/").filter((segment) => segment.length > 0),+ };+ const navigationAction = resolveFileSelectionNavigationAction({+ hasPersistentFileInspector: fileInspector.supported,+ });+ if (navigationAction === "replace") {+ navigation.dispatch(StackActions.replace("ThreadFile", params));+ return;+ }+ navigation.navigate("ThreadFile", params);+ };+ const renderInspector = (headerInset: number) =>+ environmentId !== null && cwd !== null ? (+ <ThreadFileNavigatorPane+ cwd={cwd}+ environmentId={environmentId}+ headerInset={headerInset}+ projectName={projectName}+ selectedPath={null}+ onSelectFile={handleSelectFile}+ />+ ) : null;+ const handlePreviewFile = (relativePath: string) => {+ if (environmentId === null || cwd === null) {+ return;+ }+ preloadWorkspaceFileContents({+ cwd,+ environmentId,+ relativePath,+ theme: highlightTheme,+ });+ };useEffect(() => {if (fileInspector.supported && cwd !== null && !revealedInspectorRef.current) {revealedInspectorRef.current = true;@@ -630,45 +621,39 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {draftCwd: threadId === null ? cwd : null,});const assetPreviewUri = assetPreview._tag === "Success" ? assetPreview.url : null;- const mediaSource = useMemo<MediaActionsSource | undefined>(- () =>- environmentId !== null &&- relativePath !== null &&- assetPreview.resource !== null &&- "path" in assetPreview.resource &&- typeof assetPreview.resource.path === "string" &&- (isImageFile || isVideoFile)- ? {- reference: mediaFileReference(assetPreview.resource.path, cwd),- name: basename(relativePath),- mimeType:- mediaMimeTypeFromExtension(relativePath.slice(relativePath.lastIndexOf("."))) ??- "application/octet-stream",- environmentId,- ...(threadId === null ? {} : { threadId }),- resource: assetPreview.resource,- }- : undefined,- [assetPreview.resource, cwd, environmentId, isImageFile, isVideoFile, relativePath, threadId],- );+ const mediaSource: MediaActionsSource | undefined =+ environmentId !== null &&+ relativePath !== null &&+ assetPreview.resource !== null &&+ "path" in assetPreview.resource &&+ typeof assetPreview.resource.path === "string" &&+ (isImageFile || isVideoFile)+ ? {+ reference: mediaFileReference(assetPreview.resource.path, cwd),+ name: basename(relativePath),+ mimeType:+ mediaMimeTypeFromExtension(relativePath.slice(relativePath.lastIndexOf("."))) ??+ "application/octet-stream",+ environmentId,+ ...(threadId === null ? {} : { threadId }),+ resource: assetPreview.resource,+ }+ : undefined;const mediaActions = useMediaActions(mediaSource);- const videoSource = useMemo<MediaVideoPreviewSource | null>(- () =>- environmentId !== null &&- relativePath !== null &&- (assetPreview.resource?._tag === "media-file" ||- assetPreview.resource?._tag === "draft-workspace-file")- ? {- type: "media",- environmentId,- resource: assetPreview.resource,- name: basename(relativePath),- mimeType: videoMimeType({ name: relativePath, mimeType: "" }) ?? "video/mp4",- actionsSource: mediaSource,- }- : null,- [assetPreview.resource, environmentId, relativePath, mediaSource],- );+ const videoSource: MediaVideoPreviewSource | null =+ environmentId !== null &&+ relativePath !== null &&+ (assetPreview.resource?._tag === "media-file" ||+ assetPreview.resource?._tag === "draft-workspace-file")+ ? {+ type: "media",+ environmentId,+ resource: assetPreview.resource,+ name: basename(relativePath),+ mimeType: videoMimeType({ name: relativePath, mimeType: "" }) ?? "video/mp4",+ actionsSource: mediaSource,+ }+ : null;const previewUri =assetPreviewUri === null || previewRevision === 0? assetPreviewUri@@ -707,59 +692,50 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {);const fileData = fileQuery.data as ProjectReadFileResult | null;- const handleSelectFile = useCallback(- (path: string) => {- const segments = path.split("/").filter(Boolean);- // A draft has no thread. `ThreadFile` would stringify null and then wait forever for a- // thread to resolve, so a draft stays on its own route and carries its workspace along.- if (threadId === null) {- navigation.dispatch(- StackActions.push("NewTaskFile", {- environmentId: String(environmentId),- ...(cwd === null ? {} : { cwd }),- projectName,- path: segments,- }),- );- return;- }- navigation.navigate("ThreadFile", {- environmentId: String(environmentId),- threadId: String(threadId),- path: segments,- });- },- [cwd, environmentId, navigation, projectName, threadId],- );- const renderInspector = useCallback(- (headerInset: number) =>- fileInspector.supported && environmentId !== null && cwd !== null ? (- <ThreadFileNavigatorPane- cwd={cwd}- environmentId={environmentId}- headerInset={headerInset}- projectName={projectName}- selectedPath={relativePath}- onSelectFile={handleSelectFile}- />- ) : undefined,- [cwd, environmentId, fileInspector.supported, handleSelectFile, projectName, relativePath],- );+ const handleSelectFile = (path: string) => {+ const segments = path.split("/").filter(Boolean);+ // A draft has no thread. `ThreadFile` would stringify null and then wait forever for a+ // thread to resolve, so a draft stays on its own route and carries its workspace along.+ if (threadId === null) {+ navigation.dispatch(+ StackActions.push("NewTaskFile", {+ environmentId: String(environmentId),+ ...(cwd === null ? {} : { cwd }),+ projectName,+ path: segments,+ }),+ );+ return;+ }+ navigation.navigate("ThreadFile", {+ environmentId: String(environmentId),+ threadId: String(threadId),+ path: segments,+ });+ };+ const renderInspector = (headerInset: number) =>+ fileInspector.supported && environmentId !== null && cwd !== null ? (+ <ThreadFileNavigatorPane+ cwd={cwd}+ environmentId={environmentId}+ headerInset={headerInset}+ projectName={projectName}+ selectedPath={relativePath}+ onSelectFile={handleSelectFile}+ />+ ) : undefined;const safeAreaInsets = useSafeAreaInsets();const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;- const renderWorkspaceInspector = useCallback(- () => (- <ThreadInspectorContentStack- mode="files"- resetKeys={[threadId, cwd]}- renderFiles={() => renderInspector(inspectorHeaderInset)}- />- ),- [cwd, inspectorHeaderInset, renderInspector, threadId],+ const renderWorkspaceInspector = () => (+ <ThreadInspectorContentStack+ mode="files"+ resetKeys={[threadId, cwd]}+ renderFiles={() => renderInspector(inspectorHeaderInset)}+ />);useRegisterWorkspaceInspector(fileInspector.supported ? renderWorkspaceInspector : undefined);- const fileMenuActions = useMemo(() => {+ const fileMenuActions = (() => {if (relativePath === null) return [];const canToggleMode = canPreview && !isImageFile && !isVideoFile && !isAudioFile;return [@@ -856,26 +832,9 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {} as const): null,].filter((action) => action !== null);- }, [- appearance.codeWordBreak,- setCodeWordBreak,- assetPreviewUri,- assetPreview.refresh,- previewUri,- canPreview,- isAudioFile,- isBrowserFile,- isImageFile,- isVideoFile,- relativePath,- resolvedActiveMode,- mediaSource,- mediaActions.actions,- fileData?.contents,- fileData?.truncated,- ]);-- const handleReturnToThread = useCallback(() => {+ })();++ const handleReturnToThread = () => {if (environmentId !== null && threadId !== null) {navigation.dispatch(StackActions.replace("Thread", {@@ -884,14 +843,14 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {}),);}- }, [environmentId, navigation, threadId]);- const handleBack = useCallback(() => {+ };+ const handleBack = () => {if (navigation.canGoBack()) {navigation.goBack();return;}handleReturnToThread();- }, [handleReturnToThread, navigation]);+ };if (environmentId === null || (threadId !== null && selectedThread === null)) {return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;diff --git a/apps/mobile/src/features/files/useFileTreeEntries.ts b/apps/mobile/src/features/files/useFileTreeEntries.tsindex 855f0fddbae..3c728d48ad0 100644--- a/apps/mobile/src/features/files/useFileTreeEntries.ts+++ b/apps/mobile/src/features/files/useFileTreeEntries.ts@@ -1,7 +1,7 @@import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";import * as Cause from "effect/Cause";-import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from "react";+import { useEffect, useReducer, useRef, useState } from "react";import { appAtomRegistry } from "../../state/atom-registry";import { projectEnvironment } from "../../state/projects";@@ -33,17 +33,14 @@ export function useFileTreeEntries(input: {const [, render] = useReducer((value: number) => value + 1, 0);const [entriesRevision, entriesChanged] = useReducer((value: number) => value + 1, 0);const refreshVersion = useRef(0);- const directories = useMemo(- () => ({- cwd,- environmentId,- entries: new Map<string, ReadonlyArray<ProjectEntry>>(),- requested: new Set<string>(),- pending: new Map<string, AbortController>(),- errors: new Map<string, string>(),- }),- [cwd, environmentId],- );+ const directories = {+ cwd,+ environmentId,+ entries: new Map<string, ReadonlyArray<ProjectEntry>>(),+ requested: new Set<string>(),+ pending: new Map<string, AbortController>(),+ errors: new Map<string, string>(),+ };const [refreshingDirectories, setRefreshingDirectories] = useState<typeof directories | null>(null,);@@ -55,54 +52,51 @@ export function useFileTreeEntries(input: {},[directories],);- const loadDirectory = useCallback(- (directoryPath: string, refresh = false) => {- if (- cwd === null ||- environmentId === null ||- (!refresh && directories.entries.has(directoryPath)) ||- directories.pending.has(directoryPath)- ) {- return;+ const loadDirectory = (directoryPath: string, refresh = false) => {+ if (+ cwd === null ||+ environmentId === null ||+ (!refresh && directories.entries.has(directoryPath)) ||+ directories.pending.has(directoryPath)+ ) {+ return;+ }+ const controller = new AbortController();+ directories.requested.add(directoryPath);+ directories.pending.set(directoryPath, controller);+ directories.errors.delete(directoryPath);+ render();+ const atom = projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath } });+ appAtomRegistry.refresh(atom);+ return executeAtomQuery(appAtomRegistry, atom, {+ signal: controller.signal,+ reportFailure: false,+ reportDefect: false,+ }).then((result) => {+ if (controller.signal.aborted) return;+ directories.pending.delete(directoryPath);+ if (result._tag === "Success") {+ directories.entries.set(+ directoryPath,+ result.value.entries.filter(+ (entry) =>+ entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath,+ ),+ );+ entriesChanged();+ } else {+ const error = Cause.squash(result.cause);+ directories.errors.set(+ directoryPath,+ error instanceof Error ? error.message : "Files unavailable",+ );}- const controller = new AbortController();- directories.requested.add(directoryPath);- directories.pending.set(directoryPath, controller);- directories.errors.delete(directoryPath);render();- const atom = projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath } });- appAtomRegistry.refresh(atom);- return executeAtomQuery(appAtomRegistry, atom, {- signal: controller.signal,- reportFailure: false,- reportDefect: false,- }).then((result) => {- if (controller.signal.aborted) return;- directories.pending.delete(directoryPath);- if (result._tag === "Success") {- directories.entries.set(- directoryPath,- result.value.entries.filter(- (entry) =>- entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath,- ),- );- entriesChanged();- } else {- const error = Cause.squash(result.cause);- directories.errors.set(- directoryPath,- error instanceof Error ? error.message : "Files unavailable",- );- }- render();- });- },- [cwd, directories, environmentId],- );+ });+ };const { refresh: refreshRoot, data: rootData } = root;const { refresh: refreshSearch, data: searchData } = search;- const snapshot = useMemo(() => {+ const snapshot = (() => {const merged = new Map<string, ProjectEntry>();if (searching) {for (const entry of searchData?.entries ?? []) merged.set(entry.path, entry);@@ -126,9 +120,9 @@ export function useFileTreeEntries(input: {? new Set((searchData?.entries ?? []).map((entry) => entry.path)): null,};- }, [directories, entriesRevision, rootData, searchData, searching]);+ })();- const refresh = useCallback(() => {+ const refresh = () => {refreshRoot();if (searching) refreshSearch();const paths = new Set(@@ -171,17 +165,7 @@ export function useFileTreeEntries(input: {return Promise.all(work).finally(() => {if (version === refreshVersion.current) setRefreshingDirectories(null);});- }, [- cwd,- debouncedQuery,- environmentId,- directories,- loadDirectory,- refreshRoot,- refreshSearch,- searching,- snapshot.reachableDirectories,- ]);+ };return {entries: snapshot.entries,diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsxindex 96d6455d399..5660301371d 100644--- a/apps/mobile/src/features/review/ReviewSheet.tsx+++ b/apps/mobile/src/features/review/ReviewSheet.tsx@@ -1,3 +1,5 @@+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";+import { AsyncResult } from "effect/reactivity";import type { EnvironmentId, ThreadId } from "@t3tools/contracts";import { formatDiffCount } from "@t3tools/client-runtime/diff-count";import { useNavigation, type StaticScreenProps } from "@react-navigation/native";@@ -9,13 +11,10 @@ import type { ReviewSectionItem } from "./reviewModel";import { useReviewHeaderPresentation } from "./useReviewHeaderPresentation";import { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-screens";import {- memo,type Ref,type ReactElement,- useCallback,useEffect,useImperativeHandle,- useMemo,useRef,useState,} from "react";@@ -157,7 +156,7 @@ function ReviewHeader(const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";-const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) {+const ReviewNotice = function ReviewNotice(props: { readonly notice: string }) {return (<ViewclassName={cn(@@ -169,7 +168,7 @@ const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string<Text className="text-xs leading-normal text-warning-foreground">{props.notice}</Text></View>);-});+};function ReviewSelectionActionBar(props: {readonly bottomInset: number;@@ -241,15 +240,15 @@ interface ReviewNavigatorFile {readonly deletions: number;}-const ReviewFileNavigatorRow = memo(function ReviewFileNavigatorRow(props: {+const ReviewFileNavigatorRow = function ReviewFileNavigatorRow(props: {readonly file: ReviewNavigatorFile;readonly selected: boolean;readonly onSelectFile: (fileId: string | null) => void;}) {const { file, selected, onSelectFile } = props;- const handlePress = useCallback(() => {+ const handlePress = () => {onSelectFile(selected ? null : file.id);- }, [file.id, onSelectFile, selected]);+ };return (<Pressable@@ -287,7 +286,7 @@ const ReviewFileNavigatorRow = memo(function ReviewFileNavigatorRow(props: {</View></Pressable>);-});+};interface ReviewFileNavigatorHandle {readonly setVisibleFile: (fileId: string | null) => void;@@ -317,7 +316,7 @@ function ReviewFileNavigator({readonly sectionId: string | null;readonly fileId: string | null;}>({ sectionId: null, fileId: null });- const availableFileIds = useMemo(() => files.map((file) => file.id), [files]);+ const availableFileIds = files.map((file) => file.id);const selectedFileId = resolveSelectedReviewFileId({selection: fileSelection,sectionId,@@ -342,23 +341,17 @@ function ReviewFileNavigator({[availableFileIds, sectionId],);- const handleSelectFile = useCallback(- (fileId: string | null) => {- setFileSelection({ sectionId, fileId });- onSelectFile(fileId);- },- [onSelectFile, sectionId],- );+ const handleSelectFile = (fileId: string | null) => {+ setFileSelection({ sectionId, fileId });+ onSelectFile(fileId);+ };- const renderFile = useCallback(- ({ item }: { readonly item: ReviewNavigatorFile }) => (- <ReviewFileNavigatorRow- file={item}- selected={selectedFileId === item.id}- onSelectFile={handleSelectFile}- />- ),- [handleSelectFile, selectedFileId],+ const renderFile = ({ item }: { readonly item: ReviewNavigatorFile }) => (+ <ReviewFileNavigatorRow+ file={item}+ selected={selectedFileId === item.id}+ onSelectFile={handleSelectFile}+ />);const fileList = (@@ -509,14 +502,11 @@ export function ReviewSheet(props: ReviewSheetProps) {const nativeReviewDiffViewRef = useRef<NativeReviewDiffViewHandle>(null);const showcasedReviewDrawRef = useRef<string | null>(null);const [isPullRefreshing, setIsPullRefreshing] = useState(false);- const handlePullToRefresh = useCallback(async () => {+ const handlePullToRefresh = async () => {setIsPullRefreshing(true);- try {- await refreshSelectedSection();- } finally {- setIsPullRefreshing(false);- }- }, [refreshSelectedSection]);+ await refreshSelectedSection();+ setIsPullRefreshing(false);+ };const reviewFileNavigatorRef = useRef<ReviewFileNavigatorHandle>(null);const reviewFiles = parsedDiff.kind === "files" ? parsedDiff.files : [];const fileVisibility = useReviewFileVisibility({@@ -551,95 +541,82 @@ export function ReviewSheet(props: ReviewSheetProps) {SHOWCASE_ENABLED && parsedDiff.kind === "files" && selectedSection? `${reviewCache.threadKey}:${selectedSection.id}:${nativeBridge.tokensResetKey}:${nativeBridge.themeId}`: null;- const handleNativeDebug = useCallback(- (event: NativeSyntheticEvent<Record<string, unknown>>) => {- nativeBridge.onDebug(event);- if (- showcaseReviewKey === null ||- showcasedReviewDrawRef.current === showcaseReviewKey ||- !isNativeReviewDiffDrawEvent(event.nativeEvent)- ) {- return;- }- showcasedReviewDrawRef.current = showcaseReviewKey;- reportShowcaseSceneRendered({ scene: "review", themeId: nativeBridge.themeId });- },- [nativeBridge.onDebug, nativeBridge.themeId, showcaseReviewKey],+ const handleNativeDebug = (event: NativeSyntheticEvent<Record<string, unknown>>) => {+ nativeBridge.onDebug(event);+ if (+ showcaseReviewKey === null ||+ showcasedReviewDrawRef.current === showcaseReviewKey ||+ !isNativeReviewDiffDrawEvent(event.nativeEvent)+ ) {+ return;+ }+ showcasedReviewDrawRef.current = showcaseReviewKey;+ reportShowcaseSceneRendered({ scene: "review", themeId: nativeBridge.themeId });+ };++ const handleSelectFile = async (fileId: string | null) => {+ loadVisibleFile(fileId, true);+ commentSelection.clearSelection();+ if (fileId !== null && collapsedFileIds.includes(fileId)) {+ toggleExpandedFile(fileId);+ }+ const nativeView = nativeReviewDiffViewRef.current;+ if (!nativeView) return;+ const result = await settlePromise(() =>+ fileId === null ? nativeView.scrollToTop(true) : nativeView.scrollToFile(fileId, true),+ );+ if (AsyncResult.isFailure(result)) {+ console.error("[review] Failed to navigate to diff file", squashAtomCommandFailure(result));+ }+ };+ const handleVisibleFileChange = (+ event: NativeSyntheticEvent<{ readonly fileId?: string | null }>,+ ) => {+ loadVisibleFile(event.nativeEvent.fileId ?? null);+ reviewFileNavigatorRef.current?.setVisibleFile(event.nativeEvent.fileId ?? null);+ };+ const renderInspector = () => (+ <ReviewFileNavigator+ ref={reviewFileNavigatorRef}+ files={nativeReviewDiffData.files}+ headerInset={insets.top}+ sectionId={selectedSection?.id ?? null}+ onSelectFile={(fileId) => void handleSelectFile(fileId)}+ />);- const handleSelectFile = useCallback(- (fileId: string | null) => {+ const handleNativeToggleFile = (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {+ const { fileId } = event.nativeEvent;+ if (fileId) {loadVisibleFile(fileId, true);- commentSelection.clearSelection();- if (fileId !== null && collapsedFileIds.includes(fileId)) {- toggleExpandedFile(fileId);- }- const navigation =- fileId === null- ? nativeReviewDiffViewRef.current?.scrollToTop(true)- : nativeReviewDiffViewRef.current?.scrollToFile(fileId, true);- void navigation?.catch((error: unknown) => {- console.error("[review] Failed to navigate to diff file", error);- });- },- [collapsedFileIds, commentSelection, toggleExpandedFile, loadVisibleFile],- );- const handleVisibleFileChange = useCallback(- (event: NativeSyntheticEvent<{ readonly fileId?: string | null }>) => {- loadVisibleFile(event.nativeEvent.fileId ?? null);- reviewFileNavigatorRef.current?.setVisibleFile(event.nativeEvent.fileId ?? null);- },- [loadVisibleFile],- );- const renderInspector = useCallback(- () => (- <ReviewFileNavigator- ref={reviewFileNavigatorRef}- files={nativeReviewDiffData.files}- headerInset={insets.top}- sectionId={selectedSection?.id ?? null}- onSelectFile={handleSelectFile}- />- ),- [handleSelectFile, insets.top, nativeReviewDiffData.files, selectedSection?.id],- );-- const handleNativeToggleFile = useCallback(- (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {- const { fileId } = event.nativeEvent;- if (fileId) {- loadVisibleFile(fileId, true);- toggleExpandedFile(fileId);- }- },- [toggleExpandedFile, loadVisibleFile],- );-- const handleNativeToggleViewedFile = useCallback(- (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {- const { fileId } = event.nativeEvent;- if (fileId) {- toggleViewedFile(fileId);- }- },- [toggleViewedFile],- );+ toggleExpandedFile(fileId);+ }+ };++ const handleNativeToggleViewedFile = (+ event: NativeSyntheticEvent<{ readonly fileId?: string }>,+ ) => {+ const { fileId } = event.nativeEvent;+ if (fileId) {+ toggleViewedFile(fileId);+ }+ };const parsedDiffNotice =parsedDiff.kind === "files" || parsedDiff.kind === "raw" ? parsedDiff.notice : null;const hasCachedSelectedDiff = selectedSection?.diff != null;const hasAnyCachedDiff = reviewSections.some((section) => section.diff != null);- const sectionMenu = useMemo(() => buildReviewSectionMenu(reviewSections), [reviewSections]);+ const sectionMenu = buildReviewSectionMenu(reviewSections);const { showConnectionNotice, showSectionToolbar } = resolveReviewAvailability({hasEnvironmentPresentation: environment.isReady,isEnvironmentConnected: isEnvironmentReady,hasCachedSelectedDiff,hasAnyCachedDiff,});- const handleRetryEnvironment = useCallback(() => {+ const handleRetryEnvironment = () => {void retryEnvironment(environmentId);- }, [environmentId, retryEnvironment]);- const handleReturnToThread = useCallback(() => {+ };+ const handleReturnToThread = () => {if (navigation.canGoBack()) {navigation.goBack();return;@@ -648,7 +625,7 @@ export function ReviewSheet(props: ReviewSheetProps) {environmentId: String(environmentId),threadId: String(threadId),});- }, [environmentId, navigation, threadId]);+ };const androidHeaderSubtitle = [selectedSection?.title,headerDiffSummary.additions,@@ -665,7 +642,7 @@ export function ReviewSheet(props: ReviewSheetProps) {useRegisterWorkspaceInspector(showChangedFilesPane ? renderInspector : undefined);const showChangedFilesToggle = panes.supportsAuxiliaryPane && showChangedFilesPane;- const listHeader = useMemo(() => {+ const listHeader = (() => {const children: ReactElement[] = [];if (error) {@@ -692,7 +669,7 @@ export function ReviewSheet(props: ReviewSheetProps) {}return <>{children}</>;- }, [error, parsedDiffNotice]);+ })();const headerSubtitle = [headerDiffSummary.additions,headerDiffSummary.deletions,diff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsxindex 818f5ab8af4..4b2c66a2af9 100644--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx+++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx@@ -103,11 +103,10 @@ export function DiffTokenText(props: {}}>{(() => {- let offset = 0;+ const starts = tokenStartOffsets(props.tokens);- return props.tokens.map((token) => {- const start = offset;- offset += token.content.length;+ return props.tokens.map((token, index) => {+ const start = starts[index]!;const fontWeight =token.fontStyle !== null && (token.fontStyle & 2) === 2@@ -142,3 +141,13 @@ export function DiffTokenText(props: {</NativeText>);}++function tokenStartOffsets(tokens: ReadonlyArray<{ readonly content: string }>): number[] {+ const starts: number[] = [];+ let offset = 0;+ for (const token of tokens) {+ starts.push(offset);+ offset += token.content.length;+ }+ return starts;+}diff --git a/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts b/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.tsindex 61a205f9d91..129fb585842 100644--- a/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts+++ b/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts@@ -1,3 +1,5 @@+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";+import { AsyncResult } from "effect/reactivity";import { useEffect, useRef, useState } from "react";import {@@ -70,8 +72,8 @@ export function useNativeReviewDiffHighlighting(input: {const engine: NativeReviewDiffHighlightEngine = "native";void (async () => {- try {- const result = await highlightNativeReviewDiffVisibleRows({+ const settled = await settlePromise(() =>+ highlightNativeReviewDiffVisibleRows({files,rows,scheme,@@ -80,41 +82,40 @@ export function useNativeReviewDiffHighlighting(input: {lastRowIndex: requestRange.lastRowIndex,alreadyHighlightedRowIds: highlightedRowIdsRef.current,signal: abortController.signal,+ }),+ );+ if (abortController.signal.aborted) return;+ if (AsyncResult.isFailure(settled)) {+ logReviewDiffDiagnostic("native visible highlight failed", {+ error: squashAtomCommandFailure(settled),+ resetKey,+ scheme,+ firstRowIndex: requestRange.firstRowIndex,+ lastRowIndex: requestRange.lastRowIndex,});+ return;+ }+ const result = settled.value;+ if (result.rowCount === 0) return;- if (abortController.signal.aborted || result.rowCount === 0) {- return;- }-- for (const rowId of Object.keys(result.tokensByRowId)) {- highlightedRowIdsRef.current.add(rowId);- }-- const chunkIndex = visibleChunkIndexRef.current;- visibleChunkIndexRef.current += 1;- setTokensPatchJson(- JSON.stringify({- resetKey,- chunkIndex,- fileId: "visible",- filePath: "visible rows",- language: "diff",- lineCount: result.rowCount,- durationMs: result.durationMs,- tokensByRowId: result.tokensByRowId,- }),- );- } catch (error) {- if (!abortController.signal.aborted) {- logReviewDiffDiagnostic("native visible highlight failed", {- error,- resetKey,- scheme,- firstRowIndex: requestRange.firstRowIndex,- lastRowIndex: requestRange.lastRowIndex,- });- }+ for (const rowId of Object.keys(result.tokensByRowId)) {+ highlightedRowIdsRef.current.add(rowId);}++ const chunkIndex = visibleChunkIndexRef.current;+ visibleChunkIndexRef.current += 1;+ setTokensPatchJson(+ JSON.stringify({+ resetKey,+ chunkIndex,+ fileId: "visible",+ filePath: "visible rows",+ language: "diff",+ lineCount: result.rowCount,+ durationMs: result.durationMs,+ tokensByRowId: result.tokensByRowId,+ }),+ );})();return () => abortController.abort();diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsxindex 7017d8d30fe..99fbc09f08e 100644--- a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx@@ -5,7 +5,7 @@ import {UserProfileView,} from "@clerk/expo/native-components";import { StackActions, useNavigation } from "@react-navigation/native";-import { useCallback, useEffect, useLayoutEffect, useRef } from "react";+import { useEffect, useLayoutEffect, useState } from "react";import { View } from "react-native";import { hasCloudPublicConfig } from "../cloud/publicConfig";@@ -35,25 +35,22 @@ export function SettingsAuthRouteScreen() {function ConfiguredSettingsAuthRouteScreen() {const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });const navigation = useNavigation();- const handleHostBack = useCallback(- () => navigation.dispatch(StackActions.popTo("SettingsContent")),- [navigation],- );- const hasBeenSignedIn = useRef(isSignedIn);- if (isSignedIn) {- hasBeenSignedIn.current = true;- }+ const handleHostBack = () => navigation.dispatch(StackActions.popTo("SettingsContent"));+ // Once signed in, stay on the profile view so signing out pops back instead of+ // flashing the sign-in form.+ const [hasBeenSignedIn, setHasBeenSignedIn] = useState(isSignedIn === true);+ if (isSignedIn && !hasBeenSignedIn) setHasBeenSignedIn(true);useEffect(() => {- if (hasBeenSignedIn.current && isLoaded && isSignedIn === false) {+ if (hasBeenSignedIn && isLoaded && isSignedIn === false) {navigation.dispatch(StackActions.popTo("SettingsContent"));}- }, [isLoaded, isSignedIn, navigation]);+ }, [hasBeenSignedIn, isLoaded, isSignedIn, navigation]);return (<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">{isLoaded ? (- hasBeenSignedIn.current ? (+ hasBeenSignedIn ? (<UserProfileViewcustomPages={USER_PROFILE_CUSTOM_PAGES}isDismissible={false}diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsxindex 666e1c25313..f79b26e86bf 100644--- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx@@ -26,15 +26,7 @@ import {DEFAULT_WEBHOOK_PROMPT,parseMaxDeliveryAge,} from "@t3tools/client-runtime/scheduled-task-webhook";-import {- useCallback,- useEffect,- useLayoutEffect,- useMemo,- useRef,- useState,- type ReactNode,-} from "react";+import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";import { useFocusEffect, useNavigation, usePreventRemove } from "@react-navigation/native";import type { NativeStackNavigationProp } from "@react-navigation/native-stack";import { AppState, Platform, Pressable, TextInput as RNTextInput, View } from "react-native";@@ -266,20 +258,18 @@ function PickerRow(props: {export function SettingsScheduledTasksRouteScreen() {const [now, setNow] = useState(Date.now);- useFocusEffect(- useCallback(() => {- const updateNow = () => setNow(Date.now());- updateNow();- const timer = setInterval(updateNow, 60_000);- const subscription = AppState.addEventListener("change", (state) => {- if (state === "active") updateNow();- });- return () => {- clearInterval(timer);- subscription.remove();- };- }, []),- );+ useFocusEffect(() => {+ const updateNow = () => setNow(Date.now());+ updateNow();+ const timer = setInterval(updateNow, 60_000);+ const subscription = AppState.addEventListener("change", (state) => {+ if (state === "active") updateNow();+ });+ return () => {+ clearInterval(timer);+ subscription.remove();+ };+ });const { availableTargets, selectedTargets, selectedProjectKey, projectGroups } =useSettingsEnvironmentFilter();const selectedGroup = projectGroups.find((group) => group.key === selectedProjectKey);@@ -435,9 +425,8 @@ function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string }selection,readDraftMessage: () => {const current = readEditor();- return current?.environmentId === editor?.environmentId- ? (current?.draft.prompt ?? null)- : null;+ if (current?.environmentId !== editor?.environmentId) return null;+ return current?.draft.prompt ?? null;},onChangeSelection: setSelection,onChangeDraftMessage: (text) => {@@ -586,10 +575,7 @@ function TaskForm({);const projects = useProjects().filter((project) => project.environmentId === environmentId);const config = useEnvironmentServerConfig(environmentId);- const modelOptions = useMemo(- () => buildModelOptions(config, null, undefined, draft.projectId),- [config, draft.projectId],- );+ const modelOptions = buildModelOptions(config, null, undefined, draft.projectId);const canOperate = useAtomValue(serverEnvironment.upsertScheduledTask.permissionAtom(environmentId),);diff --git a/apps/mobile/src/features/settings/components/SettingsDragHandle.tsx b/apps/mobile/src/features/settings/components/SettingsDragHandle.tsxindex 3ac380eae6b..7bd48b7f6fc 100644--- a/apps/mobile/src/features/settings/components/SettingsDragHandle.tsx+++ b/apps/mobile/src/features/settings/components/SettingsDragHandle.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useRef } from "react";+import { useEffectEvent, useState } from "react";import { View } from "react-native";import { Gesture, GestureDetector } from "react-native-gesture-handler";@@ -13,28 +13,29 @@ export function SettingsDragHandle(props: {readonly onEnd: (translation: number, cancelled: boolean) => void;readonly onStep: (direction: "up" | "down") => void;}) {- const latest = useRef(props);- useEffect(() => {- latest.current = props;- });- const translation = useRef(0);- const gesture = useMemo(- () =>- Gesture.Pan()- .minDistance(0)- .shouldCancelWhenOutside(false)- .runOnJS(true)- .onStart(() => {- translation.current = 0;- latest.current.onStart();- })- .onUpdate((event) => {- translation.current = event.translationY;- latest.current.onMove(event.translationY);- })- .onFinalize((_, success) => latest.current.onEnd(translation.current, !success)),- [],+ // Gesture callbacks fire outside render, so effect events give them the+ // latest props while the gesture object itself stays stable.+ const onStart = useEffectEvent(() => props.onStart());+ const onMove = useEffectEvent((translation: number) => props.onMove(translation));+ const onEnd = useEffectEvent((translation: number, cancelled: boolean) =>+ props.onEnd(translation, cancelled),);+ const [gesture] = useState(() => {+ let translation = 0;+ return Gesture.Pan()+ .minDistance(0)+ .shouldCancelWhenOutside(false)+ .runOnJS(true)+ .onStart(() => {+ translation = 0;+ onStart();+ })+ .onUpdate((event) => {+ translation = event.translationY;+ onMove(event.translationY);+ })+ .onFinalize((_, success) => onEnd(translation, !success));+ });return (<GestureDetector gesture={gesture}><Viewdiff --git a/apps/mobile/src/reactCompilerCoverage.test.ts b/apps/mobile/src/reactCompilerCoverage.test.tsindex 98515329f4f..2179ab4d440 100644--- a/apps/mobile/src/reactCompilerCoverage.test.ts+++ b/apps/mobile/src/reactCompilerCoverage.test.ts@@ -27,12 +27,6 @@ const KNOWN_BAILOUTS: Record<string, string> = {"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/files/AttachmentFileScreen.tsx": "manual memo not preserved",- "src/features/files/FileMarkdownPreview.tsx": "try without catch",- "src/features/files/FileTreeBrowser.tsx": "ref read during render",- "src/features/files/SourceFileSurface.tsx": "try without catch",- "src/features/files/ThreadFilesRouteScreen.tsx": "manual memo not preserved",- "src/features/files/useFileTreeEntries.ts": "manual memo not preserved","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",@@ -55,12 +49,6 @@ const KNOWN_BAILOUTS: Record<string, string> = {"src/features/pull-requests/usePullRequestListActions.ts": "throw inside try, try/finally","src/features/pull-requests/usePullRequestListControls.ts": "unsupported syntax","src/features/pull-requests/usePullRequestThreads.ts": "throw inside try, try/finally",- "src/features/review/ReviewSheet.tsx": "try without catch",- "src/features/review/reviewDiffRendering.tsx": "mutates a frozen value",- "src/features/review/useNativeReviewDiffHighlighting.ts": "conditional inside try",- "src/features/settings/SettingsAuthRouteScreen.tsx": "ref read during render",- "src/features/settings/SettingsScheduledTasksRouteScreen.tsx": "unsupported syntax",- "src/features/settings/components/SettingsDragHandle.tsx": "ref read during render","src/features/terminal/ThreadTerminalRouteScreen.tsx": "ref read during render","src/features/threads/NewTaskContextPickerScreens.tsx":"manual memo not preserved, try without catch",diff --git a/apps/mobile/uniwind-types.d.ts b/apps/mobile/uniwind-types.d.tsindex a622367845d..22856ab57ff 100644--- a/apps/mobile/uniwind-types.d.ts+++ b/apps/mobile/uniwind-types.d.ts@@ -1,3 +1,4 @@+// NOTE: This file is generated by uniwind and it should not be edited manually./// <reference types="uniwind/types" />declare module 'uniwind' {