The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 03:00 UTC
perf(mobile): ThreadFeed compiles with the React Compiler (#21268)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 18, 2026 at 14:33 UTC
d8e9fd267e26b7680f035edc0b40db09d2685dbb
3 files changed
+524
-674
apps/mobile/src/features/threads/ThreadFeed.tsx
+461
-610
@@ -50,7 +50,7 @@ import {
50
import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
51
import { isMarkdownFileLinkLabel } from "@t3tools/shared/markdownLinks";
52
import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
53
-import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
53
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
54
import {
55
classifyMarkdownImageSource,
56
markdownImageSourceFragment,
@@ -568,46 +568,47 @@ function MessageAttachmentFile(props: {
568
const controller = new AbortController();
569
openingRef.current = controller;
570
setOpening(true);
571
+ const finish = (message: string | null) => {
572
+ if (message !== null && !controller.signal.aborted) {
573
+ Dialog.alert("Could not open attachment", message);
574
+ }
575
+ if (openingRef.current === controller) {
576
+ openingRef.current = null;
577
+ setOpening(false);
578
+ }
579
+ };
580
void (async () => {
572
- try {
573
- const result = await createAssetUrl({
574
- environmentId: props.environmentId,
575
- input: {
576
- resource: {
577
- _tag: "attachment",
578
- attachmentId: attachment.id,
579
- fileName: attachment.name,
580
- mimeType: attachment.mimeType,
581
- },
581
+ const result = await createAssetUrl({
582
+ environmentId: props.environmentId,
583
+ input: {
584
+ resource: {
585
+ _tag: "attachment",
586
+ attachmentId: attachment.id,
587
+ fileName: attachment.name,
588
+ mimeType: attachment.mimeType,
589
},
583
- });
584
- if (controller.signal.aborted) return;
585
- if (result._tag === "Failure") {
586
- throw squashAtomCommandFailure(result);
587
- }
588
- const url = resolveAssetUrl(httpBaseUrl, result.value.relativeUrl);
589
- if (url === null) {
590
- throw new Error("The attachment could not be opened.");
591
- }
592
- await downloadAndShareAttachment({
590
+ },
591
+ });
592
+ if (controller.signal.aborted) return finish(null);
593
+ if (result._tag === "Failure") {
594
+ const error = squashAtomCommandFailure(result);
595
+ return finish(error instanceof Error ? error.message : "The attachment is unavailable.");
596
+ }
597
+ const url = resolveAssetUrl(httpBaseUrl, result.value.relativeUrl);
598
+ if (url === null) return finish("The attachment could not be opened.");
599
+ const shared = await settlePromise(() =>
600
+ downloadAndShareAttachment({
601
url,
602
attachment,
603
signal: controller.signal,
604
sourceIdentifier,
597
- });
598
- } catch (error) {
599
- if (!controller.signal.aborted) {
600
- Dialog.alert(
601
- "Could not open attachment",
602
- error instanceof Error ? error.message : "The attachment is unavailable.",
603
- );
604
- }
605
- } finally {
606
- if (openingRef.current === controller) {
607
- openingRef.current = null;
608
- setOpening(false);
609
- }
605
+ }),
606
+ );
607
+ if (shared._tag === "Failure") {
608
+ const error = squashAtomCommandFailure(shared);
609
+ return finish(error instanceof Error ? error.message : "The attachment is unavailable.");
610
}
611
+ finish(null);
612
})();
613
};
614
@@ -1673,6 +1674,7 @@ function ThreadFeedPlaceholder(props: {
1674
}
1675
1676
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
1677
+ const { listRef, onEndFollowEnabledChange, onHeaderMaterialVisibilityChange } = props;
1678
const workflowOpening = useWorkflowOpening(props.environmentId, props.threadId);
1679
const deviceType = useDeviceType();
1680
const duoColumns = useNativeWorkspaceColumnsSupported() && isDuoDevice(deviceType);
@@ -1688,18 +1690,18 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
1690
const headerMaterialVisibleRef = useRef(false);
1691
const { width: windowWidth, fontScale } = useWindowDimensions();
1692
const { appearance } = useAppearancePreferences();
1691
- const workRowSizing = useMemo(
1692
- () => deriveThreadWorkLogSizing({ baseFontSize: appearance.baseFontSize, fontScale }),
1693
- [appearance.baseFontSize, fontScale],
1694
- );
1693
+ const workRowSizing = deriveThreadWorkLogSizing({
1694
+ baseFontSize: appearance.baseFontSize,
1695
+ fontScale,
1696
+ });
1697
const previousTextSize = useRef(workRowSizing.textSizeKey);
1698
useLayoutEffect(() => {
1699
if (previousTextSize.current === workRowSizing.textSizeKey) {
1700
return;
1701
}
1702
previousTextSize.current = workRowSizing.textSizeKey;
1701
- props.listRef.current?.clearCaches({ mode: "sizes" });
1702
- }, [workRowSizing.textSizeKey, props.listRef]);
1703
+ listRef.current?.clearCaches({ mode: "sizes" });
1704
+ }, [workRowSizing.textSizeKey, listRef]);
1705
const [viewportWidth, setViewportWidth] = useState(() =>
1706
props.layoutVariant === "split" ? 0 : windowWidth,
1707
);
@@ -1714,23 +1716,17 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
1716
// momentum; scroll events only break follow inside that session, so MVCP
1717
// compensations and programmatic scrolls never strand a follower.
1718
const userScrollSessionRef = useRef(false);
1717
- const setEndFollow = useCallback(
1718
- (enabled: boolean) => {
1719
- if (endFollowEnabledRef.current === enabled) {
1720
- return;
1721
- }
1722
- endFollowEnabledRef.current = enabled;
1723
- setEndFollowEnabled(enabled);
1724
- props.onEndFollowEnabledChange?.(enabled);
1725
- },
1726
- [props.onEndFollowEnabledChange],
1727
- );
1728
- const transitionEndFollow = useCallback(
1729
- (event: ThreadFeedLiveFollowEvent) => {
1730
- setEndFollow(resolveThreadFeedLiveFollow(endFollowEnabledRef.current, event));
1731
- },
1732
- [setEndFollow],
1733
- );
1719
+ const setEndFollow = (enabled: boolean) => {
1720
+ if (endFollowEnabledRef.current === enabled) {
1721
+ return;
1722
+ }
1723
+ endFollowEnabledRef.current = enabled;
1724
+ setEndFollowEnabled(enabled);
1725
+ onEndFollowEnabledChange?.(enabled);
1726
+ };
1727
+ const transitionEndFollow = (event: ThreadFeedLiveFollowEvent) => {
1728
+ setEndFollow(resolveThreadFeedLiveFollow(endFollowEnabledRef.current, event));
1729
+ };
1730
const [interactionState, setInteractionState] = useState<{
1731
readonly copiedRowId: string | null;
1732
readonly expandedWorkGroups: Record<string, boolean>;
@@ -1793,337 +1789,282 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
1789
const iconSubtleColor = theme["--color-icon-subtle"];
1790
const screenColor = theme["--color-screen"];
1791
const userBubbleColor = theme["--color-user-bubble"];
1796
- const onMarkdownLinkPress = useCallback(
1797
- (href: string, imageEmbed = false) => {
1798
- const linkedThreadId = parseThreadLinkHref(href);
1799
- if (linkedThreadId) {
1800
- navigation.navigate("Thread", {
1801
- environmentId: String(props.environmentId),
1802
- threadId: String(linkedThreadId),
1803
- });
1804
- return;
1805
- }
1806
- const media = resolveMarkdownMediaPreview(href, {
1807
- environmentId: props.environmentId,
1808
- threadId: props.threadId,
1809
- workspaceRoot: props.workspaceRoot,
1810
- imageEmbed,
1792
+ const onMarkdownLinkPress = (href: string, imageEmbed = false) => {
1793
+ const linkedThreadId = parseThreadLinkHref(href);
1794
+ if (linkedThreadId) {
1795
+ navigation.navigate("Thread", {
1796
+ environmentId: String(props.environmentId),
1797
+ threadId: String(linkedThreadId),
1798
});
1812
- if (media) {
1813
- void Haptics.selectionAsync();
1814
- if (media.kind === "video") {
1815
- setExpandedVideo((current) => current ?? media.source);
1816
- } else {
1817
- setExpandedFile((current) => current ?? media.source);
1818
- }
1819
- return;
1820
- }
1821
-
1822
- const presentation = resolveMarkdownLinkPresentation(href);
1823
- if (presentation.kind === "file") {
1824
- const relativePath = resolveWorkspaceRelativeFilePath(
1825
- props.workspaceRoot,
1826
- presentation.path,
1827
- );
1828
- if (relativePath) {
1829
- void Haptics.selectionAsync();
1830
- navigation.navigate("ThreadFile", {
1831
- environmentId: String(props.environmentId),
1832
- threadId: String(props.threadId),
1833
- path: fileRoutePathSegments(relativePath),
1834
- ...(presentation.line ? { line: String(presentation.line) } : {}),
1835
- });
1836
- return;
1837
- }
1799
+ return;
1800
+ }
1801
+ const media = resolveMarkdownMediaPreview(href, {
1802
+ environmentId: props.environmentId,
1803
+ threadId: props.threadId,
1804
+ workspaceRoot: props.workspaceRoot,
1805
+ imageEmbed,
1806
+ });
1807
+ if (media) {
1808
+ void Haptics.selectionAsync();
1809
+ if (media.kind === "video") {
1810
+ setExpandedVideo((current) => current ?? media.source);
1811
+ } else {
1812
+ setExpandedFile((current) => current ?? media.source);
1813
}
1814
+ return;
1815
+ }
1816
1840
- if (presentation.kind === "file" && isAbsolutePath(presentation.path)) {
1817
+ const presentation = resolveMarkdownLinkPresentation(href);
1818
+ if (presentation.kind === "file") {
1819
+ const relativePath = resolveWorkspaceRelativeFilePath(props.workspaceRoot, presentation.path);
1820
+ if (relativePath) {
1821
void Haptics.selectionAsync();
1822
navigation.navigate("ThreadFile", {
1823
environmentId: String(props.environmentId),
1824
threadId: String(props.threadId),
1845
- path: fileRoutePathSegments(presentation.path),
1825
+ path: fileRoutePathSegments(relativePath),
1826
...(presentation.line ? { line: String(presentation.line) } : {}),
1827
});
1828
return;
1829
}
1830
+ }
1831
1851
- if (presentation.kind !== "file" && presentation.href) {
1852
- if (/^https?:\/\//i.test(presentation.href) && isPdfFile({ name: presentation.href })) {
1853
- setExpandedFile(
1854
- (current) => current ?? { kind: "pdf", uri: presentation.href!, name: "Document.pdf" },
1855
- );
1856
- return;
1857
- }
1858
- void openPullRequest(presentation.href);
1832
+ if (presentation.kind === "file" && isAbsolutePath(presentation.path)) {
1833
+ void Haptics.selectionAsync();
1834
+ navigation.navigate("ThreadFile", {
1835
+ environmentId: String(props.environmentId),
1836
+ threadId: String(props.threadId),
1837
+ path: fileRoutePathSegments(presentation.path),
1838
+ ...(presentation.line ? { line: String(presentation.line) } : {}),
1839
+ });
1840
+ return;
1841
+ }
1842
+
1843
+ if (presentation.kind !== "file" && presentation.href) {
1844
+ if (/^https?:\/\//i.test(presentation.href) && isPdfFile({ name: presentation.href })) {
1845
+ setExpandedFile(
1846
+ (current) => current ?? { kind: "pdf", uri: presentation.href!, name: "Document.pdf" },
1847
+ );
1848
+ return;
1849
}
1860
- },
1861
- [props.environmentId, props.threadId, props.workspaceRoot, navigation, openPullRequest],
1862
- );
1850
+ void openPullRequest(presentation.href);
1851
+ }
1852
+ };
1853
const resolveImageSource = useMarkdownImageSource({
1854
environmentId: props.environmentId,
1855
threadId: props.threadId,
1856
workspaceRoot: props.workspaceRoot ?? null,
1857
});
1868
- const markdownLinkHandlers = useMemo<MarkdownLinkHandlers>(
1869
- () => ({
1870
- onLinkPress: onMarkdownLinkPress,
1871
- onImagePress: (href) => onMarkdownLinkPress(href, true),
1872
- resolveImageSource,
1873
- fileContextMenu: (href) => {
1874
- const target = resolveFileChipTarget(href, props.workspaceRoot);
1875
- return target ? fileChipMenu(target) : undefined;
1876
- },
1877
- onFileContextMenuAction: (href, actionId) => {
1878
- const target = resolveFileChipTarget(href, props.workspaceRoot);
1879
- if (!target) return;
1880
- switch (actionId as FileChipAction) {
1881
- case "copy-full-path":
1882
- if (target.fullPath) copyTextWithHaptic(target.fullPath);
1883
- return;
1884
- case "copy-relative-path":
1885
- if (target.relativePath) copyTextWithHaptic(target.relativePath);
1886
- return;
1887
- case "open-file":
1888
- onMarkdownLinkPress(href);
1889
- return;
1890
- case "save":
1891
- shareFileChip(target);
1892
- return;
1893
- }
1894
- },
1895
- }),
1896
- [onMarkdownLinkPress, props.workspaceRoot, shareFileChip, resolveImageSource],
1897
- );
1898
- const renderMarkdownImage = useCallback<MarkdownImageRenderer>(
1899
- (image) => {
1900
- const media = resolveMarkdownMediaPreview(image.href, {
1901
- environmentId: props.environmentId,
1902
- threadId: props.threadId,
1903
- workspaceRoot: props.workspaceRoot,
1904
- imageEmbed: true,
1905
- });
1906
- if (media?.kind === "video") {
1907
- return (
1908
- <ThreadMarkdownVideo
1909
- key={image.href}
1910
- source={{ ...media.source, name: image.alt ?? media.source.name }}
1911
- />
1912
- );
1913
- }
1914
- const imageSource = classifyMarkdownImageSource(image.href, props.workspaceRoot ?? null);
1915
- if (imageSource._tag === "Direct") {
1916
- return (
1917
- <ThreadMarkdownImageView
1918
- uri={normalizeNativeMarkdownUrl(imageSource.uri)}
1919
- sourceKey={imageSource.uri}
1920
- format={
1921
- /\.svg(?:[?#]|$)/i.test(imageSource.uri) ||
1922
- imageSource.uri.startsWith("data:image/svg+xml")
1923
- ? "svg"
1924
- : undefined
1925
- }
1926
- unavailable={false}
1927
- alt={image.alt}
1928
- actionsSource={media?.source.actionsSource}
1929
- onPressPreview={(source) => setExpandedFile((current) => current ?? source)}
1930
- />
1931
- );
1932
- }
1933
- if (imageSource._tag === "Blocked") {
1934
- return <ThreadMarkdownImageUnavailable alt={image.alt} />;
1858
+ const markdownLinkHandlers: MarkdownLinkHandlers = {
1859
+ onLinkPress: onMarkdownLinkPress,
1860
+ onImagePress: (href) => onMarkdownLinkPress(href, true),
1861
+ resolveImageSource,
1862
+ fileContextMenu: (href) => {
1863
+ const target = resolveFileChipTarget(href, props.workspaceRoot);
1864
+ return target ? fileChipMenu(target) : undefined;
1865
+ },
1866
+ onFileContextMenuAction: (href, actionId) => {
1867
+ const target = resolveFileChipTarget(href, props.workspaceRoot);
1868
+ if (!target) return;
1869
+ switch (actionId as FileChipAction) {
1870
+ case "copy-full-path":
1871
+ if (target.fullPath) copyTextWithHaptic(target.fullPath);
1872
+ return;
1873
+ case "copy-relative-path":
1874
+ if (target.relativePath) copyTextWithHaptic(target.relativePath);
1875
+ return;
1876
+ case "open-file":
1877
+ onMarkdownLinkPress(href);
1878
+ return;
1879
+ case "save":
1880
+ shareFileChip(target);
1881
+ return;
1882
}
1883
+ },
1884
+ };
1885
+ const renderMarkdownImage: MarkdownImageRenderer = (image) => {
1886
+ const media = resolveMarkdownMediaPreview(image.href, {
1887
+ environmentId: props.environmentId,
1888
+ threadId: props.threadId,
1889
+ workspaceRoot: props.workspaceRoot,
1890
+ imageEmbed: true,
1891
+ });
1892
+ if (media?.kind === "video") {
1893
return (
1937
- <ThreadMarkdownImage
1938
- environmentId={props.environmentId}
1939
- resource={{
1940
- _tag: "media-file",
1941
- threadId: props.threadId,
1942
- path: imageSource.path,
1943
- }}
1944
- alt={image.alt}
1945
- srcFragment={markdownImageSourceFragment(image.href)}
1946
- actionsSource={media?.source.actionsSource}
1947
- onPressPreview={(source) => setExpandedFile((current) => current ?? source)}
1894
+ <ThreadMarkdownVideo
1895
+ key={image.href}
1896
+ source={{ ...media.source, name: image.alt ?? media.source.name }}
1897
/>
1898
);
1950
- },
1951
- [props.environmentId, props.threadId, props.workspaceRoot],
1952
- );
1953
- const renderViewedImage = useCallback<MarkdownImageRenderer>(
1954
- (image) => {
1955
- const viewedImage = resolveViewedImageAsset(image.href, {
1956
- threadId: props.threadId,
1957
- workspaceRoot: props.workspaceRoot,
1958
- });
1959
- const media = viewedImage
1960
- ? resolveMarkdownMediaPreview(image.href, {
1961
- environmentId: props.environmentId,
1962
- threadId: props.threadId,
1963
- workspaceRoot: props.workspaceRoot,
1964
- imageEmbed: true,
1965
- })
1966
- : null;
1967
- const actionsSource = media?.source.actionsSource;
1968
- return viewedImage ? (
1969
- <ThreadMarkdownImage
1970
- environmentId={props.environmentId}
1971
- resource={viewedImage.resource}
1972
- alt={viewedImage.alt}
1973
- srcFragment={viewedImage.srcFragment}
1974
- actionsSource={
1975
- actionsSource && "resource" in actionsSource
1976
- ? { ...actionsSource, resource: viewedImage.resource }
1899
+ }
1900
+ const imageSource = classifyMarkdownImageSource(image.href, props.workspaceRoot ?? null);
1901
+ if (imageSource._tag === "Direct") {
1902
+ return (
1903
+ <ThreadMarkdownImageView
1904
+ uri={normalizeNativeMarkdownUrl(imageSource.uri)}
1905
+ sourceKey={imageSource.uri}
1906
+ format={
1907
+ /\.svg(?:[?#]|$)/i.test(imageSource.uri) ||
1908
+ imageSource.uri.startsWith("data:image/svg+xml")
1909
+ ? "svg"
1910
: undefined
1911
}
1912
+ unavailable={false}
1913
+ alt={image.alt}
1914
+ actionsSource={media?.source.actionsSource}
1915
onPressPreview={(source) => setExpandedFile((current) => current ?? source)}
1916
/>
1981
- ) : null;
1982
- },
1983
- [props.environmentId, props.threadId, props.workspaceRoot],
1984
- );
1985
- const markdownStyles = useMarkdownStyles();
1986
- const renderReasoning = useCallback(
1987
- (text: string) => (
1988
- <AssistantMarkdownContent
1989
- markdown={text}
1917
+ );
1918
+ }
1919
+ if (imageSource._tag === "Blocked") {
1920
+ return <ThreadMarkdownImageUnavailable alt={image.alt} />;
1921
+ }
1922
+ return (
1923
+ <ThreadMarkdownImage
1924
environmentId={props.environmentId}
1991
- markdownStyles={markdownStyles.assistant}
1992
- linkHandlers={markdownLinkHandlers}
1993
- renderImage={renderMarkdownImage}
1994
- skills={props.skills}
1925
+ resource={{
1926
+ _tag: "media-file",
1927
+ threadId: props.threadId,
1928
+ path: imageSource.path,
1929
+ }}
1930
+ alt={image.alt}
1931
+ srcFragment={markdownImageSourceFragment(image.href)}
1932
+ actionsSource={media?.source.actionsSource}
1933
+ onPressPreview={(source) => setExpandedFile((current) => current ?? source)}
1934
/>
1996
- ),
1997
- [
1998
- markdownStyles.assistant,
1999
- markdownLinkHandlers,
2000
- renderMarkdownImage,
2001
- props.skills,
2002
- props.environmentId,
2003
- ],
1935
+ );
1936
+ };
1937
+ const renderViewedImage: MarkdownImageRenderer = (image) => {
1938
+ const viewedImage = resolveViewedImageAsset(image.href, {
1939
+ threadId: props.threadId,
1940
+ workspaceRoot: props.workspaceRoot,
1941
+ });
1942
+ const media = viewedImage
1943
+ ? resolveMarkdownMediaPreview(image.href, {
1944
+ environmentId: props.environmentId,
1945
+ threadId: props.threadId,
1946
+ workspaceRoot: props.workspaceRoot,
1947
+ imageEmbed: true,
1948
+ })
1949
+ : null;
1950
+ const actionsSource = media?.source.actionsSource;
1951
+ return viewedImage ? (
1952
+ <ThreadMarkdownImage
1953
+ environmentId={props.environmentId}
1954
+ resource={viewedImage.resource}
1955
+ alt={viewedImage.alt}
1956
+ srcFragment={viewedImage.srcFragment}
1957
+ actionsSource={
1958
+ actionsSource && "resource" in actionsSource
1959
+ ? { ...actionsSource, resource: viewedImage.resource }
1960
+ : undefined
1961
+ }
1962
+ onPressPreview={(source) => setExpandedFile((current) => current ?? source)}
1963
+ />
1964
+ ) : null;
1965
+ };
1966
+ const markdownStyles = useMarkdownStyles();
1967
+ const renderReasoning = (text: string) => (
1968
+ <AssistantMarkdownContent
1969
+ markdown={text}
1970
+ environmentId={props.environmentId}
1971
+ markdownStyles={markdownStyles.assistant}
1972
+ linkHandlers={markdownLinkHandlers}
1973
+ renderImage={renderMarkdownImage}
1974
+ skills={props.skills}
1975
+ />
1976
);
1977
const reviewCommentColors = useReviewCommentColors();
1978
const unsettledTurnId = threadFeedRunIsUnsettled(props.latestRun) ? props.latestRun.runId : null;
1979
// LegendList does not invalidate visible rows when only the renderItem closure changes.
1980
// Include turn completion so unchanged message rows reveal their footer and spacing
1981
// even when the final message update arrives before the turn settles.
2010
- const listAppearanceData = useMemo(
2011
- () => ({
2012
- worktreeSetup: props.worktreeSetup,
2013
- setupWorkingStartedAt: props.setupWorkingStartedAt,
2014
- dispatchingMessageId: props.dispatchingMessageId,
2015
- unsettledTurnId,
2016
- copiedRowId,
2017
- expandedWorkGroups,
2018
- expandedWorkRows,
2019
- workRowSizing,
2020
- iconSubtleColor,
2021
- markdownStyles,
2022
- reviewCommentColors,
2023
- themeAppearance,
2024
- userBubbleColor,
2025
- viewportWidth,
2026
- workflowOpening,
2027
- }),
2028
- [
2029
- props.worktreeSetup,
2030
- props.setupWorkingStartedAt,
2031
- props.dispatchingMessageId,
2032
- unsettledTurnId,
2033
- copiedRowId,
2034
- expandedWorkGroups,
2035
- expandedWorkRows,
2036
- workRowSizing,
2037
- iconSubtleColor,
2038
- markdownStyles,
2039
- reviewCommentColors,
2040
- themeAppearance,
2041
- userBubbleColor,
2042
- viewportWidth,
2043
- workflowOpening,
2044
- ],
2045
- );
2046
- const reportHeaderMaterialVisibility = useCallback(
2047
- (visible: boolean) => {
2048
- if (headerMaterialVisibleRef.current === visible) {
2049
- return;
2050
- }
2051
- headerMaterialVisibleRef.current = visible;
2052
- props.onHeaderMaterialVisibilityChange?.(visible);
2053
- },
2054
- [props.onHeaderMaterialVisibilityChange],
2055
- );
2056
- const handleScroll = useCallback(
2057
- (event: NativeSyntheticEvent<NativeScrollEvent>) => {
2058
- reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6);
2059
- // Only the actual end re-arms follow: its broader maintain-scroll
2060
- // threshold is large enough for a streaming chunk to pull a user back
2061
- // before their upward drag escapes.
2062
- const listState = props.listRef.current?.getState();
2063
- if (listState) {
2064
- transitionEndFollow({
2065
- type: "scroll",
2066
- isAtEnd: listState.isAtEnd,
2067
- userScrollSessionActive: userScrollSessionRef.current,
2068
- });
2069
- }
2070
- },
2071
- [reportHeaderMaterialVisibility, anchorTopInset, props.listRef, transitionEndFollow],
2072
- );
2073
- const clearUserScrollSettle = useCallback(() => {
1982
+ const listAppearanceData = {
1983
+ worktreeSetup: props.worktreeSetup,
1984
+ setupWorkingStartedAt: props.setupWorkingStartedAt,
1985
+ dispatchingMessageId: props.dispatchingMessageId,
1986
+ unsettledTurnId,
1987
+ copiedRowId,
1988
+ expandedWorkGroups,
1989
+ expandedWorkRows,
1990
+ workRowSizing,
1991
+ iconSubtleColor,
1992
+ markdownStyles,
1993
+ reviewCommentColors,
1994
+ themeAppearance,
1995
+ userBubbleColor,
1996
+ viewportWidth,
1997
+ workflowOpening,
1998
+ };
1999
+ const reportHeaderMaterialVisibility = (visible: boolean) => {
2000
+ if (headerMaterialVisibleRef.current === visible) {
2001
+ return;
2002
+ }
2003
+ headerMaterialVisibleRef.current = visible;
2004
+ onHeaderMaterialVisibilityChange?.(visible);
2005
+ };
2006
+ const handleScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
2007
+ reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6);
2008
+ // Only the actual end re-arms follow: its broader maintain-scroll
2009
+ // threshold is large enough for a streaming chunk to pull a user back
2010
+ // before their upward drag escapes.
2011
+ const listState = listRef.current?.getState();
2012
+ if (listState) {
2013
+ transitionEndFollow({
2014
+ type: "scroll",
2015
+ isAtEnd: listState.isAtEnd,
2016
+ userScrollSessionActive: userScrollSessionRef.current,
2017
+ });
2018
+ }
2019
+ };
2020
+ const clearUserScrollSettle = () => {
2021
if (userScrollSettleTimerRef.current !== null) {
2022
clearTimeout(userScrollSettleTimerRef.current);
2023
userScrollSettleTimerRef.current = null;
2024
}
2078
- }, []);
2079
- const handleScrollBeginDrag = useCallback(() => {
2025
+ };
2026
+ const handleScrollBeginDrag = () => {
2027
clearUserScrollSettle();
2028
userScrollSessionRef.current = true;
2029
// Pause before the first scroll event. Otherwise a stream update can run
2030
// maintainScrollAtEnd between touch-down and the drag leaving its threshold.
2031
transitionEndFollow({ type: "user-scroll-begin" });
2085
- }, [clearUserScrollSettle, transitionEndFollow]);
2086
- const finishUserScroll = useCallback(
2087
- (releaseIsAtEnd?: boolean) => {
2088
- clearUserScrollSettle();
2089
- const userScrollSessionActive = userScrollSessionRef.current;
2090
- userScrollSessionRef.current = false;
2091
- transitionEndFollow({
2092
- type: "user-scroll-end",
2093
- // With no momentum, preserve the finger-release position. Streaming
2094
- // growth during the native momentum-detection window must not turn a
2095
- // release at the live edge into an opt-out from follow.
2096
- isAtEnd: releaseIsAtEnd ?? props.listRef.current?.getState().isAtEnd ?? false,
2097
- userScrollSessionActive,
2098
- });
2099
- },
2100
- [clearUserScrollSettle, props.listRef, transitionEndFollow],
2101
- );
2032
+ };
2033
+ const finishUserScroll = (releaseIsAtEnd?: boolean) => {
2034
+ clearUserScrollSettle();
2035
+ const userScrollSessionActive = userScrollSessionRef.current;
2036
+ userScrollSessionRef.current = false;
2037
+ transitionEndFollow({
2038
+ type: "user-scroll-end",
2039
+ // With no momentum, preserve the finger-release position. Streaming
2040
+ // growth during the native momentum-detection window must not turn a
2041
+ // release at the live edge into an opt-out from follow.
2042
+ isAtEnd: releaseIsAtEnd ?? listRef.current?.getState().isAtEnd ?? false,
2043
+ userScrollSessionActive,
2044
+ });
2045
+ };
2046
// Finger-lift velocity is not a reliable momentum signal: a gentle fling can
2047
// report zero and still decelerate. Give native momentum a short window to
2048
// announce itself; if it does, onMomentumScrollBegin cancels this fallback
2049
// and the session survives until the settled momentum-end position.
2106
- const handleScrollEndDrag = useCallback(() => {
2050
+ const handleScrollEndDrag = () => {
2051
clearUserScrollSettle();
2108
- const releaseIsAtEnd = props.listRef.current?.getState().isAtEnd ?? false;
2052
+ const releaseIsAtEnd = listRef.current?.getState().isAtEnd ?? false;
2053
userScrollSettleTimerRef.current = setTimeout(() => finishUserScroll(releaseIsAtEnd), 160);
2110
- }, [clearUserScrollSettle, finishUserScroll, props.listRef]);
2111
- const handleMomentumScrollBegin = useCallback(() => {
2054
+ };
2055
+ const handleMomentumScrollBegin = () => {
2056
if (userScrollSessionRef.current) {
2057
clearUserScrollSettle();
2058
}
2115
- }, [clearUserScrollSettle]);
2116
- const handleMomentumScrollEnd = useCallback(() => {
2059
+ };
2060
+ const handleMomentumScrollEnd = () => {
2061
finishUserScroll();
2118
- }, [finishUserScroll]);
2062
+ };
2063
2064
useEffect(() => clearUserScrollSettle, [clearUserScrollSettle]);
2065
2066
const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId);
2123
- const workGroupScrollPositions = useMemo(
2124
- () => new Map<string, ThreadWorkGroupScrollPosition>(),
2125
- [feedThreadKey],
2126
- );
2067
+ const workGroupScrollPositions = new Map<string, ThreadWorkGroupScrollPosition>();
2068
useEffect(() => {
2069
clearUserScrollSettle();
2070
userScrollSessionRef.current = false;
@@ -2137,44 +2078,32 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2078
}
2079
}, [clearUserScrollSettle, props.submittedMessageId, transitionEndFollow]);
2080
2140
- const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
2081
+ const handleViewportLayout = (event: LayoutChangeEvent) => {
2082
const nextWidth = Math.round(event.nativeEvent.layout.width);
2083
const nextHeight = Math.round(event.nativeEvent.layout.height);
2084
setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current));
2085
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
2145
- }, []);
2086
+ };
2087
2088
useEffect(() => {
2089
reportHeaderMaterialVisibility(false);
2090
}, [feedThreadKey, reportHeaderMaterialVisibility]);
2091
2151
- const presentedFeed = useMemo(
2152
- () =>
2153
- appendPendingThreadMessages(
2154
- deriveThreadFeedPresentation(
2155
- props.feed,
2156
- props.latestRun,
2157
- expandedTurnIds,
2158
- new Set(
2159
- Object.entries(expandedWorkGroups)
2160
- .filter(([, expanded]) => expanded)
2161
- .map(([groupId]) => groupId),
2162
- ),
2163
- props.activeWorkStartedAt,
2164
- props.runlessWorkActive ?? false,
2165
- ),
2166
- props.feed,
2167
- props.queuedMessages,
2168
- ),
2169
- [
2170
- props.queuedMessages,
2171
- expandedTurnIds,
2172
- expandedWorkGroups,
2173
- props.activeWorkStartedAt,
2174
- props.runlessWorkActive,
2092
+ const presentedFeed = appendPendingThreadMessages(
2093
+ deriveThreadFeedPresentation(
2094
props.feed,
2095
props.latestRun,
2177
- ],
2096
+ expandedTurnIds,
2097
+ new Set(
2098
+ Object.entries(expandedWorkGroups)
2099
+ .filter(([, expanded]) => expanded)
2100
+ .map(([groupId]) => groupId),
2101
+ ),
2102
+ props.activeWorkStartedAt,
2103
+ props.runlessWorkActive ?? false,
2104
+ ),
2105
+ props.feed,
2106
+ props.queuedMessages,
2107
);
2108
const setupAnchorIndex = presentedFeed.findIndex(
2109
(entry) => entry.type === "message" && entry.message.role === "user",
@@ -2187,25 +2116,18 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2116
useLayoutEffect(() => {
2117
const bottom = props.contentInsetEndAdjustment.value;
2118
if (bottom > 0) {
2190
- props.listRef.current?.reportContentInset({ bottom });
2119
+ listRef.current?.reportContentInset({ bottom });
2120
}
2192
- }, [listMountKey, props.contentInsetEndAdjustment, props.listRef]);
2193
-
2194
- const anchoredEndSpace = useMemo(
2195
- () =>
2196
- resolveChatListAnchoredEndSpace(
2197
- presentedFeed,
2198
- props.anchorMessageId,
2199
- (entry) => (entry.type === "message" ? entry.id : null),
2200
- { anchorOffset: anchorTopInset + CHAT_LIST_ANCHOR_OFFSET },
2201
- ),
2202
- [presentedFeed, props.anchorMessageId, anchorTopInset],
2203
- );
2204
- const failedRunIds = useMemo(
2205
- () => failedFeedRunIds(props.feed, props.latestRun),
2206
- [props.feed, props.latestRun],
2121
+ }, [listMountKey, props.contentInsetEndAdjustment, listRef]);
2122
+
2123
+ const anchoredEndSpace = resolveChatListAnchoredEndSpace(
2124
+ presentedFeed,
2125
+ props.anchorMessageId,
2126
+ (entry) => (entry.type === "message" ? entry.id : null),
2127
+ { anchorOffset: anchorTopInset + CHAT_LIST_ANCHOR_OFFSET },
2128
);
2208
- const terminalAssistantMessageIds = useMemo(() => {
2129
+ const failedRunIds = failedFeedRunIds(props.feed, props.latestRun);
2130
+ const terminalAssistantMessageIds = (() => {
2131
const terminalIdsByTurn = new Map<RunId, string>();
2132
for (const entry of props.feed) {
2133
if (entry.type === "message" && entry.message.role === "assistant" && entry.message.runId) {
@@ -2213,7 +2135,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2135
}
2136
}
2137
return new Set(terminalIdsByTurn.values());
2216
- }, [props.feed]);
2138
+ })();
2139
useEffect(() => {
2140
const previous = previousLatestTurnRef.current;
2141
previousLatestTurnRef.current = props.latestRun;
@@ -2254,7 +2176,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2176
};
2177
}, []);
2178
2257
- const settleDisclosureAfterLayout = useCallback(() => {
2179
+ const settleDisclosureAfterLayout = () => {
2180
if (disclosureSettleFrameRef.current !== null) {
2181
cancelAnimationFrame(disclosureSettleFrameRef.current);
2182
}
@@ -2263,7 +2185,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2185
}
2186
disclosureSettleFrameRef.current = requestAnimationFrame(() => {
2187
disclosureSettleSecondFrameRef.current = requestAnimationFrame(() => {
2266
- const listState = props.listRef.current?.getState();
2188
+ const listState = listRef.current?.getState();
2189
if (listState) {
2190
transitionEndFollow({
2191
type: "disclosure-settled",
@@ -2277,12 +2199,12 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2199
disclosureSettleSecondFrameRef.current = null;
2200
});
2201
});
2280
- }, [props.listRef, transitionEndFollow]);
2202
+ };
2203
2282
- const suspendEndScrollMaintenanceForDisclosure = useCallback((anchorKey: string | null) => {
2204
+ const suspendEndScrollMaintenanceForDisclosure = (anchorKey: string | null) => {
2205
disclosureAnchorKeyRef.current = anchorKey;
2206
setDisclosureToggleSettling(true);
2285
- }, []);
2207
+ };
2208
2209
// Start the quiet-frame countdown after React has committed the disclosure.
2210
// Every measured item-size change restarts it, so end maintenance cannot
@@ -2293,27 +2215,24 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2215
}
2216
}, [expandedTurnIds, expandedWorkGroups, expandedWorkRows, settleDisclosureAfterLayout]);
2217
2296
- const handleItemSizeChanged = useCallback(() => {
2218
+ const handleItemSizeChanged = () => {
2219
if (disclosureAnchorKeyRef.current !== null) {
2220
settleDisclosureAfterLayout();
2221
}
2300
- }, [settleDisclosureAfterLayout]);
2222
+ };
2223
2302
- const shouldRestoreVisibleContentPosition = useCallback((entry: ThreadFeedEntry) => {
2224
+ const shouldRestoreVisibleContentPosition = (entry: ThreadFeedEntry) => {
2225
const disclosureAnchorKey = disclosureAnchorKeyRef.current;
2226
return disclosureAnchorKey === null || entry.id === disclosureAnchorKey;
2305
- }, []);
2227
+ };
2228
2307
- const maintainVisibleContentPosition = useMemo(
2308
- () => ({
2309
- data: true,
2310
- size: true,
2311
- shouldRestorePosition: shouldRestoreVisibleContentPosition,
2312
- }),
2313
- [shouldRestoreVisibleContentPosition],
2314
- );
2229
+ const maintainVisibleContentPosition = {
2230
+ data: true,
2231
+ size: true,
2232
+ shouldRestorePosition: shouldRestoreVisibleContentPosition,
2233
+ };
2234
2316
- const onCopyWorkRow = useCallback((rowId: string, value: string) => {
2235
+ const onCopyWorkRow = (rowId: string, value: string) => {
2236
copyTextWithHaptic(value, {
2237
target: "thread-work-row",
2238
feedback: "selection",
@@ -2328,230 +2247,165 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2247
);
2248
copyFeedbackTimeoutRef.current = null;
2249
}, 1200);
2331
- }, []);
2250
+ };
2251
2333
- const onToggleWorkGroup = useCallback(
2334
- (groupId: string, anchorKey?: string) => {
2335
- suspendEndScrollMaintenanceForDisclosure(anchorKey ?? `work-toggle:${groupId}`);
2336
- setInteractionState((current) => ({
2337
- ...current,
2338
- expandedWorkGroups: {
2339
- ...current.expandedWorkGroups,
2340
- [groupId]: !(current.expandedWorkGroups[groupId] ?? false),
2341
- },
2342
- }));
2343
- },
2344
- [suspendEndScrollMaintenanceForDisclosure],
2345
- );
2252
+ const onToggleWorkGroup = (groupId: string, anchorKey?: string) => {
2253
+ suspendEndScrollMaintenanceForDisclosure(anchorKey ?? `work-toggle:${groupId}`);
2254
+ setInteractionState((current) => ({
2255
+ ...current,
2256
+ expandedWorkGroups: {
2257
+ ...current.expandedWorkGroups,
2258
+ [groupId]: !(current.expandedWorkGroups[groupId] ?? false),
2259
+ },
2260
+ }));
2261
+ };
2262
2263
// A lone call's row stands in for its group header, so both disclosures move
2264
// together. Details the reader opened stay open when a second call turns the
2265
// row into a group.
2350
- const onToggleWorkRow = useCallback(
2351
- (rowId: string, anchorKey?: string, groupId?: string) => {
2352
- suspendEndScrollMaintenanceForDisclosure(anchorKey ?? null);
2353
- setInteractionState((current) => {
2354
- const expanded = !(current.expandedWorkRows[rowId] ?? false);
2355
- return {
2356
- ...current,
2357
- expandedWorkRows: { ...current.expandedWorkRows, [rowId]: expanded },
2358
- ...(groupId === undefined
2359
- ? {}
2360
- : { expandedWorkGroups: { ...current.expandedWorkGroups, [groupId]: expanded } }),
2361
- };
2362
- });
2363
- },
2364
- [suspendEndScrollMaintenanceForDisclosure],
2365
- );
2266
+ const onToggleWorkRow = (rowId: string, anchorKey?: string, groupId?: string) => {
2267
+ suspendEndScrollMaintenanceForDisclosure(anchorKey ?? null);
2268
+ setInteractionState((current) => {
2269
+ const expanded = !(current.expandedWorkRows[rowId] ?? false);
2270
+ return {
2271
+ ...current,
2272
+ expandedWorkRows: { ...current.expandedWorkRows, [rowId]: expanded },
2273
+ ...(groupId === undefined
2274
+ ? {}
2275
+ : { expandedWorkGroups: { ...current.expandedWorkGroups, [groupId]: expanded } }),
2276
+ };
2277
+ });
2278
+ };
2279
2367
- const onToggleTurnFold = useCallback(
2368
- (runId: RunId) => {
2369
- suspendEndScrollMaintenanceForDisclosure(`run-fold:${runId}`);
2370
- setInteractionState((current) => {
2371
- const next = new Set(current.expandedTurnIds);
2372
- if (next.has(runId)) {
2373
- next.delete(runId);
2374
- } else {
2375
- next.add(runId);
2376
- }
2377
- return { ...current, expandedTurnIds: next };
2378
- });
2379
- },
2380
- [suspendEndScrollMaintenanceForDisclosure],
2381
- );
2280
+ const onToggleTurnFold = (runId: RunId) => {
2281
+ suspendEndScrollMaintenanceForDisclosure(`run-fold:${runId}`);
2282
+ setInteractionState((current) => {
2283
+ const next = new Set(current.expandedTurnIds);
2284
+ if (next.has(runId)) {
2285
+ next.delete(runId);
2286
+ } else {
2287
+ next.add(runId);
2288
+ }
2289
+ return { ...current, expandedTurnIds: next };
2290
+ });
2291
+ };
2292
2383
- const onPressPreview = useCallback((source: FilePreviewSource) => {
2293
+ const onPressPreview = (source: FilePreviewSource) => {
2294
setExpandedFile((current) => current ?? source);
2385
- }, []);
2386
- const onPressVideo = useCallback(
2387
- (attachment: ChatFileAttachment, sourceIdentifier: string) => {
2388
- setExpandedVideo(
2389
- (current) =>
2390
- current ??
2391
- attachmentVideoPreviewSource(props.environmentId, attachment, sourceIdentifier),
2392
- );
2393
- },
2394
- [props.environmentId],
2395
- );
2295
+ };
2296
+ const onPressVideo = (attachment: ChatFileAttachment, sourceIdentifier: string) => {
2297
+ setExpandedVideo(
2298
+ (current) =>
2299
+ current ?? attachmentVideoPreviewSource(props.environmentId, attachment, sourceIdentifier),
2300
+ );
2301
+ };
2302
2303
// Without this, every row above the viewport is assumed to be
2304
// estimatedItemSize tall, and scrolling up through unmeasured content
2305
// corrects each row's height as it mounts — the feed visibly jumps.
2400
- const getFixedItemSize = useCallback(
2401
- (entry: ThreadFeedEntry) => {
2402
- if (entry.type === "html-render") {
2403
- return htmlRenderRowHeight(htmlRenderFrameHeight(entry.render, contentWidth));
2404
- }
2405
- if (workRowSizing.fixedRowHeight === undefined) {
2406
- return undefined;
2407
- }
2408
- switch (entry.type) {
2409
- case "run-fold":
2410
- return resolveThreadFeedFixedItemSize(entry.type);
2411
- case "work-toggle":
2412
- return entry.thought ? undefined : WORK_GROUP_TOGGLE_HEIGHT;
2413
- case "thinking":
2414
- return WORK_GROUP_TOGGLE_HEIGHT;
2415
- case "activity-group":
2416
- if (entry.activities[0]?.projectedItem.item.type === "subagent") {
2417
- return undefined;
2418
- }
2419
- if (isContextCompactionActivityGroup(entry) || isContextHandoffActivityGroup(entry)) {
2420
- return undefined;
2421
- }
2422
- if (
2423
- entry.activities[0]?.groupedToolDetail &&
2424
- entry.activities.every((activity) => activity.workEntry.itemType === "reasoning")
2425
- ) {
2426
- return undefined;
2427
- }
2428
- return entry.activities.some(
2429
- (activity) => activity.prominent || expandedWorkRows[activity.id],
2430
- )
2431
- ? undefined
2432
- : collapsedWorkLogHeight(entry.activities, entry.continuesWorkLog);
2433
- default:
2306
+ const getFixedItemSize = (entry: ThreadFeedEntry) => {
2307
+ if (entry.type === "html-render") {
2308
+ return htmlRenderRowHeight(htmlRenderFrameHeight(entry.render, contentWidth));
2309
+ }
2310
+ if (workRowSizing.fixedRowHeight === undefined) {
2311
+ return undefined;
2312
+ }
2313
+ switch (entry.type) {
2314
+ case "run-fold":
2315
+ return resolveThreadFeedFixedItemSize(entry.type);
2316
+ case "work-toggle":
2317
+ return entry.thought ? undefined : WORK_GROUP_TOGGLE_HEIGHT;
2318
+ case "thinking":
2319
+ return WORK_GROUP_TOGGLE_HEIGHT;
2320
+ case "activity-group":
2321
+ if (entry.activities[0]?.projectedItem.item.type === "subagent") {
2322
return undefined;
2435
- }
2436
- },
2437
- [contentWidth, expandedWorkRows, workRowSizing.fixedRowHeight],
2438
- );
2439
- const hasHtmlRenders = useMemo(
2440
- () => presentedFeed.some((entry) => entry.type === "html-render"),
2441
- [presentedFeed],
2442
- );
2323
+ }
2324
+ if (isContextCompactionActivityGroup(entry) || isContextHandoffActivityGroup(entry)) {
2325
+ return undefined;
2326
+ }
2327
+ if (
2328
+ entry.activities[0]?.groupedToolDetail &&
2329
+ entry.activities.every((activity) => activity.workEntry.itemType === "reasoning")
2330
+ ) {
2331
+ return undefined;
2332
+ }
2333
+ return entry.activities.some(
2334
+ (activity) => activity.prominent || expandedWorkRows[activity.id],
2335
+ )
2336
+ ? undefined
2337
+ : collapsedWorkLogHeight(entry.activities, entry.continuesWorkLog);
2338
+ default:
2339
+ return undefined;
2340
+ }
2341
+ };
2342
+ const hasHtmlRenders = presentedFeed.some((entry) => entry.type === "html-render");
2343
const previousContentWidth = useRef(contentWidth);
2344
useLayoutEffect(() => {
2345
if (previousContentWidth.current === contentWidth) return;
2346
previousContentWidth.current = contentWidth;
2447
- if (hasHtmlRenders) props.listRef.current?.clearCaches({ mode: "sizes" });
2448
- }, [contentWidth, hasHtmlRenders, props.listRef]);
2347
+ if (hasHtmlRenders) listRef.current?.clearCaches({ mode: "sizes" });
2348
+ }, [contentWidth, hasHtmlRenders, listRef]);
2349
2450
- const renderItem = useCallback(
2451
- (info: { item: PendingThreadFeedEntry; index: number }) => (
2452
- <Animated.View
2453
- key={info.item.id}
2454
- entering={disclosureToggleSettling ? THREAD_FEED_DISCLOSURE_ENTER_TRANSITION : undefined}
2350
+ const renderItem = (info: { item: PendingThreadFeedEntry; index: number }) => (
2351
+ <Animated.View
2352
+ key={info.item.id}
2353
+ entering={disclosureToggleSettling ? THREAD_FEED_DISCLOSURE_ENTER_TRANSITION : undefined}
2354
+ >
2355
+ <MessageImageGalleryScope
2356
+ entry={info.item}
2357
+ environmentId={props.environmentId}
2358
+ threadId={props.threadId}
2359
+ workspaceRoot={props.workspaceRoot}
2360
>
2456
- <MessageImageGalleryScope
2457
- entry={info.item}
2458
- environmentId={props.environmentId}
2459
- threadId={props.threadId}
2460
- workspaceRoot={props.workspaceRoot}
2461
- >
2462
- <ThreadMediaVisibility>
2463
- {renderFeedEntry(info, {
2464
- environmentId: props.environmentId,
2465
- dispatchingMessageId: props.dispatchingMessageId,
2466
- onEditPendingMessage: props.onEditPendingMessage,
2467
- onUseArtifactTemplate: props.onUseArtifactTemplate,
2468
- threadId: props.threadId,
2469
- copiedRowId,
2470
- expandedWorkRows,
2471
- workRowSizing,
2472
- workGroupScrollPositions,
2473
- terminalAssistantMessageIds,
2474
- unsettledTurnId,
2475
- failedRunIds,
2476
- onCopyWorkRow,
2477
- onToggleWorkGroup,
2478
- onToggleWorkRow,
2479
- onToggleTurnFold,
2480
- onPressPreview,
2481
- onPressVideo,
2482
- markdownLinkHandlers,
2483
- renderMarkdownImage,
2484
- renderViewedImage,
2485
- renderReasoning,
2486
- iconSubtleColor,
2487
- screenColor,
2488
- userBubbleColor,
2489
- markdownStyles,
2490
- reviewCommentColors,
2491
- reviewCommentBubbleWidth,
2492
- themeAppearance,
2493
- duoColumns,
2494
- userBubbleMaxWidth,
2495
- markdownContentWidth,
2496
- contentWidth,
2497
- threadTitle: props.threadTitle,
2498
- skills: props.skills,
2499
- workspaceRoot: props.workspaceRoot,
2500
- workflowOpening,
2501
- })}
2502
- {props.worktreeSetup && info.index === setupAnchorIndex ? (
2503
- <WorktreeSetupCard key={props.threadId} {...props.worktreeSetup} />
2504
- ) : props.setupWorkingStartedAt && info.index === setupAnchorIndex ? (
2505
- <WorktreeWorkingHeader startedAt={props.setupWorkingStartedAt} />
2506
- ) : null}
2507
- </ThreadMediaVisibility>
2508
- </MessageImageGalleryScope>
2509
- </Animated.View>
2510
- ),
2511
- [
2512
- props.worktreeSetup,
2513
- props.setupWorkingStartedAt,
2514
- props.threadId,
2515
- setupAnchorIndex,
2516
- props.dispatchingMessageId,
2517
- props.onEditPendingMessage,
2518
- copiedRowId,
2519
- disclosureToggleSettling,
2520
- expandedWorkRows,
2521
- workRowSizing,
2522
- workGroupScrollPositions,
2523
- terminalAssistantMessageIds,
2524
- unsettledTurnId,
2525
- failedRunIds,
2526
- iconSubtleColor,
2527
- screenColor,
2528
- userBubbleColor,
2529
- markdownStyles,
2530
- reviewCommentColors,
2531
- reviewCommentBubbleWidth,
2532
- themeAppearance,
2533
- duoColumns,
2534
- userBubbleMaxWidth,
2535
- markdownContentWidth,
2536
- contentWidth,
2537
- onCopyWorkRow,
2538
- markdownLinkHandlers,
2539
- onPressPreview,
2540
- onPressVideo,
2541
- onToggleTurnFold,
2542
- onToggleWorkGroup,
2543
- onToggleWorkRow,
2544
- props.environmentId,
2545
- props.onUseArtifactTemplate,
2546
- props.threadId,
2547
- props.threadTitle,
2548
- props.skills,
2549
- props.workspaceRoot,
2550
- workflowOpening,
2551
- renderMarkdownImage,
2552
- renderViewedImage,
2553
- renderReasoning,
2554
- ],
2361
+ <ThreadMediaVisibility>
2362
+ {renderFeedEntry(info, {
2363
+ environmentId: props.environmentId,
2364
+ dispatchingMessageId: props.dispatchingMessageId,
2365
+ onEditPendingMessage: props.onEditPendingMessage,
2366
+ onUseArtifactTemplate: props.onUseArtifactTemplate,
2367
+ threadId: props.threadId,
2368
+ copiedRowId,
2369
+ expandedWorkRows,
2370
+ workRowSizing,
2371
+ workGroupScrollPositions,
2372
+ terminalAssistantMessageIds,
2373
+ unsettledTurnId,
2374
+ failedRunIds,
2375
+ onCopyWorkRow,
2376
+ onToggleWorkGroup,
2377
+ onToggleWorkRow,
2378
+ onToggleTurnFold,
2379
+ onPressPreview,
2380
+ onPressVideo,
2381
+ markdownLinkHandlers,
2382
+ renderMarkdownImage,
2383
+ renderViewedImage,
2384
+ renderReasoning,
2385
+ iconSubtleColor,
2386
+ screenColor,
2387
+ userBubbleColor,
2388
+ markdownStyles,
2389
+ reviewCommentColors,
2390
+ reviewCommentBubbleWidth,
2391
+ themeAppearance,
2392
+ duoColumns,
2393
+ userBubbleMaxWidth,
2394
+ markdownContentWidth,
2395
+ contentWidth,
2396
+ threadTitle: props.threadTitle,
2397
+ skills: props.skills,
2398
+ workspaceRoot: props.workspaceRoot,
2399
+ workflowOpening,
2400
+ })}
2401
+ {props.worktreeSetup && info.index === setupAnchorIndex ? (
2402
+ <WorktreeSetupCard key={props.threadId} {...props.worktreeSetup} />
2403
+ ) : props.setupWorkingStartedAt && info.index === setupAnchorIndex ? (
2404
+ <WorktreeWorkingHeader startedAt={props.setupWorkingStartedAt} />
2405
+ ) : null}
2406
+ </ThreadMediaVisibility>
2407
+ </MessageImageGalleryScope>
2408
+ </Animated.View>
2409
);
2410
2411
if (props.contentPresentation.kind === "unavailable" && props.queuedMessages.length === 0) {
@@ -2571,7 +2425,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2425
<View className="flex-1" onLayout={handleViewportLayout}>
2426
<View className="flex-1">
2427
<KeyboardAwareLegendList
2574
- ref={props.listRef}
2428
+ ref={listRef}
2429
// LegendList's maintainScrollAtEnd calls scrollToEnd(), which is
2430
// blind to UIKit's adjustedContentInset — inserting into an
2431
// already-attached list under a transparent header can pin short
@@ -2775,15 +2629,12 @@ function MessageImageGalleryScope(props: {
2629
children: ReactNode;
2630
}) {
2631
const { entry, environmentId, threadId, workspaceRoot } = props;
2778
- const images = useMemo(
2779
- () =>
2780
- entry.type === "message"
2781
- ? [
2782
- ...messageImageGallery(entry.message, { environmentId, threadId, workspaceRoot }),
2783
- ...composerImageGallery(entry.pendingMessage?.attachments ?? []),
2784
- ]
2785
- : [],
2786
- [entry, environmentId, threadId, workspaceRoot],
2787
- );
2632
+ const images =
2633
+ entry.type === "message"
2634
+ ? [
2635
+ ...messageImageGallery(entry.message, { environmentId, threadId, workspaceRoot }),
2636
+ ...composerImageGallery(entry.pendingMessage?.attachments ?? []),
2637
+ ]
2638
+ : [];
2639
return <FilePreviewGallery value={images}>{props.children}</FilePreviewGallery>;
2640
}
apps/mobile/src/reactCompilerCoverage.test.ts
-2
@@ -24,13 +24,11 @@ const KNOWN_BAILOUTS: Record<string, string> = {
24
"src/features/terminal/ThreadTerminalRouteScreen.tsx": "ref read during render",
25
"src/features/threads/PendingUserInputCard.tsx": "mutates a frozen value",
26
"src/features/threads/ThreadArrangementSheet.tsx": "ref read during render",
27
- "src/features/threads/ThreadFeed.tsx": "ref read during render, throw inside try, try/finally",
27
"src/features/voice-input/VoiceInputProvider.tsx": "ref read during render",
28
"src/features/voice-input/useVoiceInputController.ts": "ref read during render",
29
"src/native/StackHeader.tsx": "ref read during render",
30
"src/native/T3ComposerEditor.ios.tsx": "ref read during render",
31
"src/native/T3ComposerEditor.native.tsx": "ref read during render",
33
- "src/state/use-thread-selection.ts": "ref read during render",
32
};
33
34
// Caller flags Metro passes for an iOS release bundle. supportsReactCompiler is
apps/mobile/src/state/use-thread-selection.ts
+63
-62
@@ -1,6 +1,6 @@
1
import { useAtomValue } from "@effect/atom-react";
2
import { useRoute, type RouteProp } from "@react-navigation/native";
3
-import { useMemo, useRef, useState } from "react";
3
+import { useState } from "react";
4
import {
5
EnvironmentId,
6
ThreadId,
@@ -113,23 +113,32 @@ function threadDetailToShell(
113
114
function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefined) {
115
const routeParams = params ?? {};
116
- const routeThreadRef = useMemo<ScopedThreadRef | null>(() => {
117
- const environmentId = firstRouteParam(routeParams.environmentId);
118
- const threadId = firstRouteParam(routeParams.threadId);
119
- if (!environmentId || !threadId) {
120
- return null;
121
- }
122
-
123
- return {
124
- environmentId: EnvironmentId.make(environmentId),
125
- threadId: ThreadId.make(threadId),
126
- };
127
- }, [routeParams.environmentId, routeParams.threadId]);
128
- const lastRouteThreadRef = useRef<ScopedThreadRef | null>(null);
129
- if (routeThreadRef !== null) {
130
- lastRouteThreadRef.current = routeThreadRef;
116
+ const routeEnvironmentId = firstRouteParam(routeParams.environmentId);
117
+ const routeThreadId = firstRouteParam(routeParams.threadId);
118
+ // A route that drops its params (a closing sheet, for example) keeps showing
119
+ // the last thread, so the last complete pair is kept as state.
120
+ const [lastRouteThreadRef, setLastRouteThreadRef] = useState<ScopedThreadRef | null>(null);
121
+ if (
122
+ routeEnvironmentId !== null &&
123
+ routeThreadId !== null &&
124
+ (lastRouteThreadRef?.environmentId !== routeEnvironmentId ||
125
+ lastRouteThreadRef.threadId !== routeThreadId)
126
+ ) {
127
+ setLastRouteThreadRef({
128
+ environmentId: EnvironmentId.make(routeEnvironmentId),
129
+ threadId: ThreadId.make(routeThreadId),
130
+ });
131
}
132
- const selectedThreadRef = routeThreadRef ?? lastRouteThreadRef.current;
132
+ const selectedThreadRef =
133
+ routeEnvironmentId !== null && routeThreadId !== null
134
+ ? lastRouteThreadRef?.environmentId === routeEnvironmentId &&
135
+ lastRouteThreadRef.threadId === routeThreadId
136
+ ? lastRouteThreadRef
137
+ : {
138
+ environmentId: EnvironmentId.make(routeEnvironmentId),
139
+ threadId: ThreadId.make(routeThreadId),
140
+ }
141
+ : lastRouteThreadRef;
142
const selectedThreadShell = useThreadShell(selectedThreadRef);
143
const selectedThreadKey =
144
selectedThreadRef === null
@@ -137,7 +146,7 @@ function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefin
146
: scopedThreadKey(selectedThreadRef.environmentId, selectedThreadRef.threadId);
147
const queuedMessagesByThreadKey = useThreadOutboxMessages();
148
const creationOutcome = useAtomValue(pendingThreadCreationOutcomesAtom);
140
- const pendingCreation = useMemo<PendingThreadCreation | null>(() => {
149
+ const pendingCreation = ((): PendingThreadCreation | null => {
150
if (selectedThreadKey === null) {
151
return null;
152
}
@@ -147,7 +156,7 @@ function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefin
156
const outcome = creationOutcome[selectedThreadKey] ?? null;
157
const message = queued ?? outcome?.message ?? null;
158
return message === null ? null : { message, outcome };
150
- }, [creationOutcome, queuedMessagesByThreadKey, selectedThreadKey]);
159
+ })();
160
// Until the creation is delivered the server has no thread to subscribe
161
// to. Every detail reader must use this ref, not the route id: an earlier
162
// read gets a definitive not-found, which the thread state keeps as deleted.
@@ -165,60 +174,52 @@ function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefin
174
needsDetail ? (selectedThreadDetailRef?.threadId ?? null) : null,
175
);
176
const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
168
- const selectedThread = useMemo(
169
- () =>
170
- selectedThreadShell ??
171
- (selectedThreadRef !== null && selectedThreadDetail !== null
172
- ? threadDetailToShell(selectedThreadRef.environmentId, selectedThreadDetail)
173
- : pendingCreation !== null
174
- ? pendingThreadCreationShell(pendingCreation.message)
175
- : null),
176
- [pendingCreation, selectedThreadDetail, selectedThreadRef, selectedThreadShell],
177
- );
178
- const selectedThreadCreation = resolvePendingThreadCreation({
177
+ const selectedThread =
178
+ selectedThreadShell ??
179
+ (selectedThreadRef !== null && selectedThreadDetail !== null
180
+ ? threadDetailToShell(selectedThreadRef.environmentId, selectedThreadDetail)
181
+ : pendingCreation !== null
182
+ ? pendingThreadCreationShell(pendingCreation.message)
183
+ : null);
184
+ const resolvedCreation = resolvePendingThreadCreation({
185
threadKey: selectedThreadKey,
186
pending: pendingCreation,
187
previous: previousCreation,
188
detail: selectedThreadDetail,
189
});
184
- if (previousCreation !== selectedThreadCreation) {
185
- setPreviousCreation(selectedThreadCreation);
190
+ // `pendingCreation` is rebuilt each render, so compare contents: an identity
191
+ // check would set state on every render.
192
+ const creationUnchanged =
193
+ resolvedCreation === previousCreation ||
194
+ (resolvedCreation !== null &&
195
+ previousCreation !== null &&
196
+ resolvedCreation.message === previousCreation.message &&
197
+ resolvedCreation.outcome === previousCreation.outcome);
198
+ if (!creationUnchanged) {
199
+ setPreviousCreation(resolvedCreation);
200
}
187
- const selectedProjectRef = useMemo<ScopedProjectRef | null>(
188
- () =>
189
- selectedThread === null
190
- ? null
191
- : {
192
- environmentId: selectedThread.environmentId,
193
- projectId: selectedThread.projectId,
194
- },
195
- [selectedThread],
196
- );
201
+ const selectedThreadCreation = creationUnchanged ? previousCreation : resolvedCreation;
202
+ const selectedProjectRef: ScopedProjectRef | null =
203
+ selectedThread === null
204
+ ? null
205
+ : {
206
+ environmentId: selectedThread.environmentId,
207
+ projectId: selectedThread.projectId,
208
+ };
209
const selectedThreadProject = useProject(selectedProjectRef);
210
const selectedEnvironmentId = selectedThread?.environmentId ?? null;
211
const selectedEnvironmentConnection = useSavedRemoteConnection(selectedEnvironmentId);
212
const selectedEnvironmentRuntime = useRemoteEnvironmentRuntime(selectedEnvironmentId);
213
202
- return useMemo(
203
- () => ({
204
- selectedThreadRef,
205
- selectedThread,
206
- selectedThreadCreation,
207
- selectedThreadDetailRef,
208
- selectedThreadProject,
209
- selectedEnvironmentConnection,
210
- selectedEnvironmentRuntime,
211
- }),
212
- [
213
- selectedEnvironmentConnection,
214
- selectedEnvironmentRuntime,
215
- selectedThread,
216
- selectedThreadCreation,
217
- selectedThreadDetailRef,
218
- selectedThreadProject,
219
- selectedThreadRef,
220
- ],
221
- );
214
+ return {
215
+ selectedThreadRef,
216
+ selectedThread,
217
+ selectedThreadCreation,
218
+ selectedThreadDetailRef,
219
+ selectedThreadProject,
220
+ selectedEnvironmentConnection,
221
+ selectedEnvironmentRuntime,
222
+ };
223
}
224
225
type ThreadSelectionState = ReturnType<typeof useResolvedThreadSelection>;