From 89d6551454953617b30390697e545b8de7b58894 Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Sat, 28 Nov 2026 17:06:57 +0530 Subject: [PATCH 01/15] perf(mobile): Android taps no longer stall on translated text Every translated string reparsed its ICU message and re-resolved its locale on each render. On Android, Intl.supportedLocalesOf crosses JNI and the Intl.Locale/PluralRules polyfills are slow, so with several environments connected a tap could block the JS thread for seconds. Patch @generaltranslation/icu to cache the resolved locale, parsed messages and Intl formatters per locale. --- patches/@generaltranslation__icu@0.1.2.patch | 94 ++++++++++++++++++++ pnpm-lock.yaml | 9 +- pnpm-workspace.yaml | 3 + 3 files changed, 102 insertions(+), 4 deletions(-) create mode 100644 patches/@generaltranslation__icu@0.1.2.patch diff --git a/patches/@generaltranslation__icu@0.1.2.patch b/patches/@generaltranslation__icu@0.1.2.patch new file mode 100644 index 0000000000000..8090190224215 --- /dev/null +++ b/patches/@generaltranslation__icu@0.1.2.patch @@ -0,0 +1,94 @@ +diff --git a/dist/index.cjs b/dist/index.cjs +index 1d257228877aeab6a04ee143c0aad5a209d3e6a5..7e68214329cb18e59fab0580df35d04da0522b7d 100644 +--- a/dist/index.cjs ++++ b/dist/index.cjs +@@ -750,11 +750,40 @@ const TIME_STYLES = { + long: LONG_TIME_STYLE, + full: LONG_TIME_STYLE + }; ++// T3 patch: GT formats every translated string on every render. Parsing the message, resolving ++// its locale (Intl.supportedLocalesOf crosses JNI on Android) and building Intl formatters were ++// redone per call; they depend only on the locale and message, so keep them per locale. ++const MAX_CACHED_MESSAGES = 2e3; ++const localeCaches = /* @__PURE__ */ new Map(); ++function localeCacheFor(locales) { ++ const key = typeof locales === "string" ? locales : locales.join("\0"); ++ let cache = localeCaches.get(key); ++ if (!cache) localeCaches.set(key, cache = { ++ locale: resolveLocale(locales), ++ messages: /* @__PURE__ */ new Map(), ++ numberFormats: /* @__PURE__ */ new Map(), ++ dateTimeFormats: /* @__PURE__ */ new Map(), ++ pluralRules: /* @__PURE__ */ new Map() ++ }); ++ return cache; ++} ++function parseCached(cache, message) { ++ let elements = cache.messages.get(message); ++ if (elements) return elements; ++ elements = parse(message, { locale: cache.locale }); ++ if (cache.messages.size >= MAX_CACHED_MESSAGES) cache.messages.clear(); ++ cache.messages.set(message, elements); ++ return elements; ++} + function formatMessage(message, locales = "en", variables = {}) { +- const parts = formatElements(parse(message, { locale: resolveLocale(locales) }), { ++ const cache = localeCacheFor(locales); ++ const parts = formatElements(parseCached(cache, message), { + message, + locales, +- variables ++ variables, ++ numberFormats: cache.numberFormats, ++ dateTimeFormats: cache.dateTimeFormats, ++ pluralRules: cache.pluralRules + }); + if (parts.length === 1) return parts[0]; + return parts.length ? parts : ""; +diff --git a/dist/index.mjs b/dist/index.mjs +index a54f2235227290efe761215b30da542562b2e77f..db5bcf2592340e7e9e96d26f89e3437018cfcd0f 100644 +--- a/dist/index.mjs ++++ b/dist/index.mjs +@@ -749,11 +749,40 @@ const TIME_STYLES = { + long: LONG_TIME_STYLE, + full: LONG_TIME_STYLE + }; ++// T3 patch: GT formats every translated string on every render. Parsing the message, resolving ++// its locale (Intl.supportedLocalesOf crosses JNI on Android) and building Intl formatters were ++// redone per call; they depend only on the locale and message, so keep them per locale. ++const MAX_CACHED_MESSAGES = 2e3; ++const localeCaches = /* @__PURE__ */ new Map(); ++function localeCacheFor(locales) { ++ const key = typeof locales === "string" ? locales : locales.join("\0"); ++ let cache = localeCaches.get(key); ++ if (!cache) localeCaches.set(key, cache = { ++ locale: resolveLocale(locales), ++ messages: /* @__PURE__ */ new Map(), ++ numberFormats: /* @__PURE__ */ new Map(), ++ dateTimeFormats: /* @__PURE__ */ new Map(), ++ pluralRules: /* @__PURE__ */ new Map() ++ }); ++ return cache; ++} ++function parseCached(cache, message) { ++ let elements = cache.messages.get(message); ++ if (elements) return elements; ++ elements = parse(message, { locale: cache.locale }); ++ if (cache.messages.size >= MAX_CACHED_MESSAGES) cache.messages.clear(); ++ cache.messages.set(message, elements); ++ return elements; ++} + function formatMessage(message, locales = "en", variables = {}) { +- const parts = formatElements(parse(message, { locale: resolveLocale(locales) }), { ++ const cache = localeCacheFor(locales); ++ const parts = formatElements(parseCached(cache, message), { + message, + locales, +- variables ++ variables, ++ numberFormats: cache.numberFormats, ++ dateTimeFormats: cache.dateTimeFormats, ++ pluralRules: cache.pluralRules + }); + if (parts.length === 1) return parts[0]; + return parts.length ? parts : ""; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b109b7207ec62..3a90e98ee1035 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -375,6 +375,7 @@ patchedDependencies: '@expo/ui@58.0.29': 2346ac02073363a401e85357e541055e9737bcbc1cdcb63e056cda9368fa79f6 '@ff-labs/fff-node@0.11.0': 93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252 '@generaltranslation/format@0.1.9': 5712dc73770a30134376f9ef883e1a2e1814f007f95532725ba5ecc7b7812db3 + '@generaltranslation/icu@0.1.2': 88fcf88d9660610fbafcbf89b4c7320009b836da05fc658955d50fec899d3d04 '@legendapp/list@3.9.0': c25646442029896901845e418ade4eaebb33cc101dc3bb4a38201f6923cf5e67 '@muse-code/sdk@1.4.6': 7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101 '@pierre/diffs@1.7.0-beta.4': 7edcdd484a99c7ec0b2667499c4cb21d113ec9bea1f8570c0b0a030d33bbf1cd @@ -15457,9 +15458,9 @@ snapshots: '@generaltranslation/format@0.1.9(patch_hash=5712dc73770a30134376f9ef883e1a2e1814f007f95532725ba5ecc7b7812db3)': dependencies: - '@generaltranslation/icu': 0.1.2 + '@generaltranslation/icu': 0.1.2(patch_hash=88fcf88d9660610fbafcbf89b4c7320009b836da05fc658955d50fec899d3d04) - '@generaltranslation/icu@0.1.2': {} + '@generaltranslation/icu@0.1.2(patch_hash=88fcf88d9660610fbafcbf89b4c7320009b836da05fc658955d50fec899d3d04)': {} '@generaltranslation/python-extractor@0.2.64': dependencies: @@ -20130,7 +20131,7 @@ snapshots: dependencies: '@generaltranslation/api': 0.5.6 '@generaltranslation/format': 0.1.9(patch_hash=5712dc73770a30134376f9ef883e1a2e1814f007f95532725ba5ecc7b7812db3) - '@generaltranslation/icu': 0.1.2 + '@generaltranslation/icu': 0.1.2(patch_hash=88fcf88d9660610fbafcbf89b4c7320009b836da05fc658955d50fec899d3d04) '@noble/hashes': 2.4.0 gensync@1.0.0-beta.2: {} @@ -20284,7 +20285,7 @@ snapshots: '@babel/types': 7.29.8 '@clack/prompts': 1.0.0-alpha.6 '@generaltranslation/format': 0.1.9(patch_hash=5712dc73770a30134376f9ef883e1a2e1814f007f95532725ba5ecc7b7812db3) - '@generaltranslation/icu': 0.1.2 + '@generaltranslation/icu': 0.1.2(patch_hash=88fcf88d9660610fbafcbf89b4c7320009b836da05fc658955d50fec899d3d04) '@generaltranslation/python-extractor': 0.2.64 '@generaltranslation/supported-locales': 2.1.45 '@generaltranslation/vue-extractor': 0.1.23(supports-color@8.1.1) diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index eca09cf47a865..6fd627792f5e7 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -295,6 +295,9 @@ patchedDependencies: effect@4.1.5: patches/effect@4.1.5.patch "@generaltranslation/format@0.1.9": patches/@generaltranslation__format@0.1.9.patch gt-i18n@1.0.40: patches/gt-i18n@1.0.40.patch + # Every translated string reparsed its message and re-resolved its locale on each render, which + # crosses JNI on Android and stalled taps for seconds; cache both per locale. + "@generaltranslation/icu@0.1.2": patches/@generaltranslation__icu@0.1.2.patch # Unmet peers fail resolution, so a pin outside a dependency's peer range is # caught when the lockfile changes instead of scrolling past as a warning. From e9e6a2504c1e293482f70ea4d2763e7090700db5 Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Sat, 28 Nov 2026 19:46:06 +0530 Subject: [PATCH 02/15] perf(mobile): Android tab switches no longer re-render hidden tabs Every tab switch changed the workspace tabs context value, so every mounted tab pane re-rendered, hidden ones included. The context now carries an atom and panes select only the state they read. Android localeCompare also shares one collator, since Hermes built a new one over JNI for every comparison. --- .../features/home/AndroidHomeFab.android.tsx | 7 +- .../src/features/home/HomeRouteScreen.tsx | 12 +- apps/mobile/src/features/home/HomeScreen.tsx | 12 +- .../src/features/home/ThreadUndoNotice.tsx | 10 +- .../src/features/issues/IssuesScreen.tsx | 9 +- .../layout/AdaptiveWorkspaceLayout.tsx | 16 +- .../AndroidWorkspaceSidebar.android.tsx | 16 +- .../workspace/ListSearchToolbar.android.tsx | 6 +- .../workspace/WorkspaceListHeader.android.tsx | 8 +- .../workspace/WorkspaceNativeTabs.ios.tsx | 2 + .../workspace/WorkspaceRootScreen.android.tsx | 183 ++++++++++-------- .../layout/workspace/WorkspaceRootScreen.tsx | 6 +- .../layout/workspace/WorkspaceTabPanes.tsx | 11 +- .../layout/workspace/WorkspaceTabsContext.tsx | 34 +++- .../layout/workspace/navigation-tabs.ts | 4 +- .../layout/workspace/useSelectWorkspaceTab.ts | 4 +- .../workspace/useSystemWorkspaceTabBar.ts | 7 +- .../layout/workspace/useWorkspaceCompose.ts | 8 +- .../workspace/workspace-tabs-state.test.ts | 3 + .../pull-requests/PullRequestsScreen.tsx | 9 +- .../features/settings/SettingsRouteScreen.tsx | 14 +- .../settings/components/SettingsScreen.tsx | 4 +- apps/mobile/src/i18n/intl-polyfills.ts | 18 ++ 23 files changed, 252 insertions(+), 151 deletions(-) diff --git a/apps/mobile/src/features/home/AndroidHomeFab.android.tsx b/apps/mobile/src/features/home/AndroidHomeFab.android.tsx index b5c86e3295c7b..e51d9aa263ca7 100644 --- a/apps/mobile/src/features/home/AndroidHomeFab.android.tsx +++ b/apps/mobile/src/features/home/AndroidHomeFab.android.tsx @@ -15,7 +15,10 @@ import { useWorkspaceState } from "../../state/workspace"; import { FabScrollContext } from "./FabScrollContext"; import { updateFabScroll } from "./fab-scroll"; import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing"; -import { WorkspaceTabsContext, useWorkspaceTabs } from "../layout/workspace/WorkspaceTabsContext"; +import { + WorkspaceTabsContext, + useWorkspaceTabControls, +} from "../layout/workspace/WorkspaceTabsContext"; import { FLOATING_TABS, floatingTabsMetrics } from "../layout/workspace/floating-workspace-tabs"; import { useEnabledNavigationTabs } from "../layout/workspace/navigation-tabs"; import { @@ -40,7 +43,7 @@ export function AndroidHomeFabLayout(props: ComponentProps state.tabs.threads); const [localSearchQuery, setLocalSearchQuery] = useState(""); const searchQuery = - Platform.OS === "android" - ? primarySidebarSearchQuery - : (workspace?.state.tabs.threads.query ?? localSearchQuery); + Platform.OS === "android" ? primarySidebarSearchQuery : (threadsTab?.query ?? localSearchQuery); const setSearchQuery = (query: string) => { if (Platform.OS === "android") setPrimarySidebarSearchQuery(query); else if (workspace) workspace.dispatch({ type: "query", query, tab: "threads" }); diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index e5b23a2627d9c..d57e96c90bb9a 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -101,7 +101,10 @@ import { createSwipeRowActivation } from "./swipe-row-activation"; import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions"; import { useFabScroll } from "./FabScrollContext"; import { holdLaunchSplashForHomeRows, settleLaunchSplashHomeRows } from "./home-launch-splash"; -import { useWorkspaceTabs } from "../layout/workspace/WorkspaceTabsContext"; +import { + useWorkspaceTabControls, + useWorkspaceTabsSelector, +} from "../layout/workspace/WorkspaceTabsContext"; import { ThreadListFilters } from "./ThreadListFilters"; import { deriveHomeEmptyState } from "./home-empty-state"; @@ -197,7 +200,8 @@ export function HomeScreen(props: HomeScreenProps) { const gt = useGT(); const m = useMessages(); const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported(); - const workspace = useWorkspaceTabs(); + const workspace = useWorkspaceTabControls(); + const threadsTab = useWorkspaceTabsSelector((state) => state.tabs.threads); const [initialScrollOffset] = useState(() => workspace?.getScrollOffset("threads") ?? 0); const primaryColumn = use(NativePrimaryColumnContext); const sidebarSurface = usePaneRole() === "sidebar" && primaryColumn !== null; @@ -275,8 +279,8 @@ export function HomeScreen(props: HomeScreenProps) { }; const onFabScroll = useFabScroll(); const listRef = useRef(null); - const searchMode = workspace?.state.tabs.threads.searchMode; - const restoredOffset = workspace?.state.tabs.threads.scrollOffset; + const searchMode = threadsTab?.searchMode; + const restoredOffset = threadsTab?.scrollOffset; useSearchScrollRestoration(searchMode, () => { if (restoredOffset === undefined) return; void listRef.current?.scrollToOffset({ diff --git a/apps/mobile/src/features/home/ThreadUndoNotice.tsx b/apps/mobile/src/features/home/ThreadUndoNotice.tsx index 633946c18bee5..21f99018c62fc 100644 --- a/apps/mobile/src/features/home/ThreadUndoNotice.tsx +++ b/apps/mobile/src/features/home/ThreadUndoNotice.tsx @@ -12,7 +12,10 @@ import { useNativeColumnLayoutMetrics, } from "../../native/native-layout-metrics"; import { workspaceSearchBottomClearance } from "../layout/workspace/workspace-tabs-state"; -import { useWorkspaceTabs } from "../layout/workspace/WorkspaceTabsContext"; +import { + useWorkspaceTabControls, + useWorkspaceTabsSelector, +} from "../layout/workspace/WorkspaceTabsContext"; import { dismissThreadUndoNotice, readThreadUndoNotice, @@ -26,7 +29,8 @@ export function ThreadUndoNotice(props: { readonly visible: boolean }) { const insets = useSafeAreaInsets(); const columnMetrics = useNativeColumnLayoutMetrics(); const rootMetrics = useNativeLayoutMetrics(); - const workspace = useWorkspaceTabs(); + const workspace = useWorkspaceTabControls(); + const threadsTab = useWorkspaceTabsSelector((state) => state.tabs.threads); const deviceType = useDeviceType(); const keyboardHeight = useKeyboardState((keyboard) => keyboard.height); const horizontalInsets = @@ -49,7 +53,7 @@ export function ThreadUndoNotice(props: { readonly visible: boolean }) { const foldedResting = rootMetrics?.hasHinge && rootMetrics.horizontalSizeClass === "compact" && - workspace?.state.tabs.threads.searchMode === "resting"; + threadsTab?.searchMode === "resting"; const bottom = Platform.OS === "ios" ? foldedResting diff --git a/apps/mobile/src/features/issues/IssuesScreen.tsx b/apps/mobile/src/features/issues/IssuesScreen.tsx index 4936603a0c2cc..da212e2119033 100644 --- a/apps/mobile/src/features/issues/IssuesScreen.tsx +++ b/apps/mobile/src/features/issues/IssuesScreen.tsx @@ -46,7 +46,10 @@ import { useWorkspaceState } from "../../state/workspace"; import { ListFilterMenu } from "../layout/workspace/ListFilterMenu"; import { useSearchScrollRestoration } from "../layout/workspace/useSearchScrollRestoration"; import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail"; -import { useWorkspaceTabs } from "../layout/workspace/WorkspaceTabsContext"; +import { + useWorkspaceTabControls, + useWorkspaceTabsSelector, +} from "../layout/workspace/WorkspaceTabsContext"; import { issueParamsKey } from "./issueParams"; import { IssueListRow } from "./IssueListRow"; import type { PullRequestFilterMenu } from "../pull-requests/PullRequestListFilters"; @@ -111,7 +114,8 @@ export function IssuesScreen( const gt = useGT(); const messages = useMessages(); const primaryColumn = use(NativePrimaryColumnContext); - const workspace = useWorkspaceTabs()!; + const workspace = useWorkspaceTabControls()!; + const tab = useWorkspaceTabsSelector((state) => state.tabs.issues)!; const { environments } = useWorkspaceState(); const configs = useAtomValue(environmentServerConfigsAtom); const projects = useProjects(); @@ -122,7 +126,6 @@ export function IssuesScreen( const bottomSafeArea = Platform.OS === "ios" ? (columnSafeBottom ?? insets.bottom) : insets.bottom; const listRef = useRef(null); - const tab = workspace.state.tabs.issues; const [initialScrollOffset] = useState(() => workspace.getScrollOffset("issues")); useSearchScrollRestoration(tab.searchMode, () => { void listRef.current?.scrollToOffset({ diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx index 015d4641011e9..5ca96c1e295c4 100644 --- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx +++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx @@ -91,7 +91,10 @@ import { type WorkspaceDetailSheet, } from "./workspace/workspace-detail-selection"; import { startOpeningDetail } from "./workspace/useSelectWorkspaceDetail"; -import { useWorkspaceTabs } from "./workspace/WorkspaceTabsContext"; +import { + useWorkspaceTabControls, + useWorkspaceTabsSelector, +} from "./workspace/WorkspaceTabsContext"; import { HomeListOptionsProvider } from "../home/home-list-options"; import { buildHomeProjectScopes, resolveHomeProjectFilterScope } from "../home/homeThreadList"; import { newTaskDestination, newTaskFilteredProject } from "../threads/new-task-project-selection"; @@ -282,16 +285,15 @@ function AdaptiveWorkspaceLayoutContent( const nativeMetrics = useNativeLayoutMetrics(); const { width: viewportWidth, height } = nativeMetrics ?? windowDimensions; const pathname = props.pathname; - const workspace = useWorkspaceTabs(); + const workspace = useWorkspaceTabControls(); + const selectedTabUsesColumns = useWorkspaceTabsSelector((state) => + workspaceUsesColumns(state.selectedTab), + ); // Settings and Usage occupy the workspace rather than a list/detail pair. const androidSettingsOpen = useAndroidWorkspaceRoot()?.settingsOpen ?? false; const safeAreaInsets = useSafeAreaInsets(); const workspacePage = - Platform.OS === "android" && - (androidSettingsOpen || - (workspace !== null && - workspace !== undefined && - !workspaceUsesColumns(workspace.state.selectedTab))); + Platform.OS === "android" && (androidSettingsOpen || selectedTabUsesColumns === false); const navigation = useNavigation(); const [primarySidebarPreferredVisible, setPrimarySidebarPreferredVisible] = useState(true); const [fileInspectorPreferredVisible, setFileInspectorPreferredVisible] = useState(true); diff --git a/apps/mobile/src/features/layout/workspace/AndroidWorkspaceSidebar.android.tsx b/apps/mobile/src/features/layout/workspace/AndroidWorkspaceSidebar.android.tsx index e90b697a7492f..344d1f86e6385 100644 --- a/apps/mobile/src/features/layout/workspace/AndroidWorkspaceSidebar.android.tsx +++ b/apps/mobile/src/features/layout/workspace/AndroidWorkspaceSidebar.android.tsx @@ -17,7 +17,11 @@ import { selectedPullRequestKey } from "../../pull-requests/pullRequestSelection import { AndroidHomeFabLayout } from "../../home/AndroidHomeFab"; import { useAdaptiveWorkspaceLayout } from "../adaptive-workspace-context"; import { useAndroidWorkspaceRoot } from "./AndroidWorkspaceTabsProvider"; -import { WorkspaceTabsContext, useWorkspaceTabs } from "./WorkspaceTabsContext"; +import { + WorkspaceTabsContext, + useWorkspaceTabControls, + useWorkspaceTabsSelector, +} from "./WorkspaceTabsContext"; import { WorkspaceTabPanes } from "./WorkspaceTabPanes"; import { WorkspaceThreadSidebar } from "./WorkspaceThreadSidebar"; import { WorkspaceAppBarScope } from "../../../components/ui/WorkspaceAppBar.android"; @@ -25,7 +29,8 @@ import { WorkspaceAppBarScope } from "../../../components/ui/WorkspaceAppBar.and /** The Home route in the sidebar column: the selected tab's list. */ export function AndroidWorkspaceSidebar() { const floatingTabsEnabled = useAndroidFloatingTabs(); - const workspace = useWorkspaceTabs()!; + const controls = useWorkspaceTabControls()!; + const selectedTab = useWorkspaceTabsSelector((state) => state.selectedTab)!; const enabled = useEnabledNavigationTabs(); const insets = useSafeAreaInsets(); const { fabSize } = useAndroidControlSizing(); @@ -34,18 +39,17 @@ export function AndroidWorkspaceSidebar() { const selectedIssue = useNavigationState(selectedIssueKey); // Settings and the one-page tabs cover the sidebar. const coveredByPage = - (useAndroidWorkspaceRoot()?.settingsOpen ?? false) || - !workspaceUsesColumns(workspace.state.selectedTab); + (useAndroidWorkspaceRoot()?.settingsOpen ?? false) || !workspaceUsesColumns(selectedTab); const bottomClearance = floatingTabsEnabled ? insets.bottom + FLOATING_TABS.bottom + FLOATING_TABS.edge + fabSize : 16; - const context = { ...workspace, bottomClearance }; + const context = { ...controls, bottomClearance }; if (enabled.length === 0) return ; return ( tab === "threads" ? ( diff --git a/apps/mobile/src/features/layout/workspace/ListSearchToolbar.android.tsx b/apps/mobile/src/features/layout/workspace/ListSearchToolbar.android.tsx index 6ddc23294c883..e3e490c2d9a0f 100644 --- a/apps/mobile/src/features/layout/workspace/ListSearchToolbar.android.tsx +++ b/apps/mobile/src/features/layout/workspace/ListSearchToolbar.android.tsx @@ -8,7 +8,7 @@ import { useHardwareKeyboardCommand } from "../../keyboard/hardwareKeyboardComma import { WorkspaceConnectionTitle } from "../../home/WorkspaceConnectionTitle"; import type { SharedSlotTab } from "./navigation-tab-order"; import { SharedSlotTitle } from "./SharedSlotTitle"; -import { useWorkspaceTabs } from "./WorkspaceTabsContext"; +import { useWorkspaceTabControls, useWorkspaceTabsSelector } from "./WorkspaceTabsContext"; import type { PullRequestFilterMenu } from "../../pull-requests/PullRequestListFilters"; import { openSettings } from "../../settings/settings-navigation"; @@ -21,10 +21,10 @@ export function ListSearchToolbar(props: { const gt = useGT(); const navigation = useNavigation(); const { filters, tab: section } = props; - const workspace = useWorkspaceTabs()!; + const workspace = useWorkspaceTabControls()!; const { dispatch, getScrollOffset, recordScrollOffset, isTabActive } = workspace; const { onRequestVisibility } = props; - const tab = workspace.state.tabs[section]; + const tab = useWorkspaceTabsSelector((state) => state.tabs[section])!; const searching = tab.searchMode !== "resting"; const openSearch = () => { onRequestVisibility?.(); diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceListHeader.android.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceListHeader.android.tsx index c205de8302d79..3b728c0153221 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceListHeader.android.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceListHeader.android.tsx @@ -7,7 +7,7 @@ import { AppBar } from "../../../components/ui/AppBar"; import { useWorkspaceConnectionState } from "../../../state/workspace"; import { useHardwareKeyboardCommand } from "../../keyboard/hardwareKeyboardCommands"; import { WorkspaceBrandTitle } from "./WorkspaceBrandTitle"; -import { useWorkspaceTabs } from "./WorkspaceTabsContext"; +import { useWorkspaceTabControls, useWorkspaceTabsSelector } from "./WorkspaceTabsContext"; import { workspaceListFilterIcon, type WorkspaceListHeaderProps, @@ -16,11 +16,11 @@ import { export function WorkspaceListHeader(props: WorkspaceListHeaderProps) { const gt = useGT(); const navigation = useNavigation(); - const workspace = useWorkspaceTabs(); + const workspace = useWorkspaceTabControls(); + const threadsSelected = useWorkspaceTabsSelector((state) => state.selectedTab === "threads"); const isTabActive = workspace?.isTabActive; const homeFocused = useNavigationState((state) => state.routes[state.index]?.name === "Home"); - const listFocused = - homeFocused && (workspace === null || workspace.state.selectedTab === "threads"); + const listFocused = homeFocused && (workspace === null || threadsSelected === true); const connectionState = useWorkspaceConnectionState(); const { search, sidebar } = props; const onSearchQueryChange = search.onChangeText; diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx index cc013343188bb..0e09ba631da31 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx @@ -1,3 +1,4 @@ +import { Atom } from "effect/reactivity"; import { useGT, useMessages } from "gt-react-native"; import { WORKSPACE_TAB_LABELS, @@ -74,6 +75,7 @@ function RetainedWorkspaceTab(props: { ...workspace, settingsOpen: props.slot === "settings", state: { ...workspace.state, selectedTab: props.tab }, + stateAtom: Atom.make((get) => ({ ...get(workspace.stateAtom), selectedTab: props.tab })), }, children: props.children, headerOnly: true, diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.android.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.android.tsx index 141b0bb79f1d3..0a60980b684ed 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.android.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.android.tsx @@ -4,7 +4,7 @@ import { WorkspaceNoTabs } from "./WorkspaceNoTabs"; import { useEnabledNavigationTabs } from "./navigation-tabs"; import { NAVIGATION_TAB_ORDER } from "./navigation-tab-order"; import { WorkspaceExtraTab } from "./WorkspaceExtraTab"; -import type { ReactNode } from "react"; +import { useMemo, type ReactNode } from "react"; import { View } from "react-native"; import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context"; import { NativeStackScreenOptions } from "../../../native/StackHeader"; @@ -20,7 +20,11 @@ import { useAdaptiveWorkspaceLayout } from "../AdaptiveWorkspaceLayout"; import { WorkspaceSettledContentWidthContext } from "../workspace-content-width"; import { AndroidWorkspaceNavigation, FloatingWorkspaceTabs } from "./AndroidWorkspaceNavigation"; import { FLOATING_TABS } from "./floating-workspace-tabs"; -import { WorkspaceTabsContext, useWorkspaceTabs } from "./WorkspaceTabsContext"; +import { + WorkspaceTabsContext, + useWorkspaceTabControls, + useWorkspaceTabsSelector, +} from "./WorkspaceTabsContext"; import { WorkspaceTabPanes } from "./WorkspaceTabPanes"; import { WorkspaceAppBarScope } from "../../../components/ui/WorkspaceAppBar.android"; import { usePaneRole } from "../../../components/ui/Pane"; @@ -39,106 +43,117 @@ function WorkspaceRoot() { const gt = useGT(); const floatingTabsEnabled = useAndroidFloatingTabs(); const { layout, startNewTask, workspacePageWidth } = useAdaptiveWorkspaceLayout(); - const workspace = useWorkspaceTabs()!; + const controls = useWorkspaceTabControls()!; + const tab = useWorkspaceTabsSelector((state) => state.selectedTab)!; + const searchResting = useWorkspaceTabsSelector( + (state) => state.tabs[state.selectedTab].searchMode === "resting", + ); const enabled = useEnabledNavigationTabs(); const insets = useSafeAreaInsets(); const { fabClearance, fabSize } = useAndroidControlSizing(); - const context = { - ...workspace, - bottomClearance: layout.usesSplitView - ? workspace.bottomClearance - : floatingTabsEnabled - ? insets.bottom + FLOATING_TABS.bottom + FLOATING_TABS.edge + fabSize - : workspace.state.selectedTab === "threads" - ? fabClearance + 16 - : 16, - }; - const tab = workspace.state.selectedTab; + // Each pane gets values for its own tab, so switching tabs leaves every pane's context alone + // and hidden panes do not re-render. + const panes = useMemo(() => { + const paneFor = (paneTab: WorkspaceTab) => { + const bottomClearance = layout.usesSplitView + ? controls.bottomClearance + : floatingTabsEnabled + ? insets.bottom + FLOATING_TABS.bottom + FLOATING_TABS.edge + fabSize + : paneTab === "threads" + ? fabClearance + 16 + : 16; + return { + context: { ...controls, bottomClearance }, + insets: layout.usesSplitView + ? insets + : floatingTabsEnabled + ? !workspaceUsesColumns(paneTab) + ? { ...insets, bottom: bottomClearance } + : insets + : { ...insets, bottom: 0 }, + }; + }; + return Object.fromEntries(TABS.map((paneTab) => [paneTab, paneFor(paneTab)])) as Record< + WorkspaceTab, + ReturnType + >; + }, [controls, layout.usesSplitView, floatingTabsEnabled, insets, fabClearance, fabSize]); const selectTab = useSelectWorkspaceTab(); // Tabs are panes of Home, not routes, so Back has nothing to pop and would leave the app. // An open search keeps Back for itself. useHardwareBack( - tab !== "threads" && - enabled.includes("threads") && - workspace.state.tabs[tab].searchMode === "resting", + tab !== "threads" && enabled.includes("threads") && searchResting === true, () => { selectTab("threads"); return true; }, ); + const renderPane = (tab: WorkspaceTab) => + tab === "threads" ? ( + + ) : tab === "usage" || tab === "workflows" ? ( + + + + ) : layout.usesSplitView ? ( + <> + + + + + ) : tab === "issues" ? ( + ( + <> + + {list} + + )} + /> + ) : ( + ( + <> + + {list} + + )} + /> + ); + return ( - + {!layout.usesSplitView ? ( ) : null} - - {enabled.length === 0 ? ( - layout.usesSplitView ? ( - - ) : ( - - ) - ) : ( - - - tab === "threads" ? ( - - ) : tab === "usage" || tab === "workflows" ? ( - - - - ) : layout.usesSplitView ? ( - <> - - - - - ) : tab === "issues" ? ( - ( - <> - - {list} - - )} - /> - ) : ( - ( - <> - - {list} - - )} - /> - ) - } - /> - - )} - + {enabled.length === 0 ? ( + + {layout.usesSplitView ? : } + + ) : ( + + ( + + + {renderPane(tab)} + + + )} + /> + + )} {layout.usesSplitView ? null : floatingTabsEnabled ? ( ) : ( diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx index cc489b9c72d11..06d6109624f35 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx @@ -34,6 +34,7 @@ import { IssuesScreen } from "../../issues/IssuesScreen"; import { WorkspaceTabsContext, WorkspaceTabsProvider, + useWorkspaceTabControls, useWorkspaceTabs, } from "./WorkspaceTabsContext"; import { WorkspaceToolbar } from "./WorkspaceToolbar"; @@ -110,6 +111,7 @@ function WorkspaceRootContent() { const insets = useSafeAreaInsets(); const keyboardHeight = useKeyboardState((keyboard) => keyboard.height); const workspace = useWorkspaceTabs()!; + const controls = useWorkspaceTabControls()!; const { state } = workspace; // Settings is a workspace tab too; its list takes the place of the selected tab's. const settingsOpen = workspace.settingsOpen; @@ -135,7 +137,7 @@ function WorkspaceRootContent() { ? 80 : 16 : WORKSPACE_DOCK.height + WORKSPACE_DOCK.bottomGap + 16); - const context = { ...workspace, bottomClearance }; + const context = { ...controls, bottomClearance }; return ( @@ -205,7 +207,7 @@ function WorkspaceRootContent() { } export function WorkspaceRootScreen() { - const workspace = useWorkspaceTabs(); + const workspace = useWorkspaceTabControls(); return workspace ? ( ) : ( diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceTabPanes.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceTabPanes.tsx index d4cc8c0c2efb6..3a91ada8b8efa 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceTabPanes.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceTabPanes.tsx @@ -19,8 +19,17 @@ export function WorkspaceTabPanes(props: { return props.tabs.map((tab) => visited.includes(tab) ? ( - {props.renderTab(tab)} + ) : null, ); } + +// A component of its own so the compiler keeps each pane's element while its inputs hold: a +// selection change then re-renders only what reads the selection, not every mounted tab. +function WorkspaceTabPane(props: { + readonly tab: Tab; + readonly renderTab: (tab: Tab) => ReactNode; +}) { + return {props.renderTab(props.tab)}; +} diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceTabsContext.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceTabsContext.tsx index c083cde764f7c..f2be6014788a9 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceTabsContext.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceTabsContext.tsx @@ -1,6 +1,6 @@ -import { RegistryContext, useAtomValue } from "@effect/atom-react"; +import { RegistryContext, useAtomMount, useAtomValue } from "@effect/atom-react"; import { AsyncResult, Atom } from "effect/reactivity"; -import { createContext, use, useState, type Dispatch, type ReactNode } from "react"; +import { createContext, use, useMemo, useState, type Dispatch, type ReactNode } from "react"; import { mobilePreferencesAtom, saveMobilePreferences } from "../../../state/preferences"; import { useAtomCommand } from "../../../state/use-atom-command"; @@ -21,8 +21,10 @@ import { type WorkspaceTabsState, } from "./workspace-tabs-state"; +// The context carries no tab state, so its value survives tab switches. Every mounted tab reads it, +// and a value that changed per switch re-rendered all of them, hidden ones included. export const WorkspaceTabsContext = createContext<{ - readonly state: WorkspaceTabsState; + readonly stateAtom: Atom.Atom; readonly dispatch: Dispatch; readonly isTabActive: (tab: WorkspaceTab) => boolean; readonly bottomClearance: number; @@ -33,10 +35,29 @@ export const WorkspaceTabsContext = createContext<{ readonly cancelSearch: (tab: WorkspaceSearchTab) => void; } | null>(null); -export function useWorkspaceTabs() { +const noWorkspaceTabsAtom = Atom.make(null); + +export function useWorkspaceTabControls() { return use(WorkspaceTabsContext); } +/** Re-renders only when the selected value changes, unlike `useWorkspaceTabs`. */ +export function useWorkspaceTabsSelector( + select: (state: WorkspaceTabsState) => A, +): A | undefined { + const controls = use(WorkspaceTabsContext); + return useAtomValue(controls?.stateAtom ?? noWorkspaceTabsAtom, (state) => + state === null ? undefined : select(state), + ); +} + +/** The whole tab state. Re-renders on every tab change, so tab panes use the selector instead. */ +export function useWorkspaceTabs() { + const controls = use(WorkspaceTabsContext); + const state = useWorkspaceTabsSelector((current) => current); + return useMemo(() => (controls && state ? { ...controls, state } : null), [controls, state]); +} + type MobilePreferencesResult = Atom.Type; /** Moves the selection off a tab the user has hidden or that no longer exists. */ @@ -89,7 +110,8 @@ export function WorkspaceTabsProvider(props: { }) { const registry = use(RegistryContext); const [model] = useState(() => createWorkspaceTabsModel(props.initialTab)); - const state = useAtomValue(model.resolved); + // Keeps the tab state alive without re-rendering this provider on each change. + useAtomMount(model.resolved); const savePreferences = useAtomCommand(saveMobilePreferences); const dispatch = (action: WorkspaceTabsAction) => { registry.set(model.stored, workspaceTabsReducer(registry.get(model.resolved), action)); @@ -97,7 +119,7 @@ export function WorkspaceTabsProvider(props: { void savePreferences({ sharedSlotTab: action.tab }); }; const context = { - state, + stateAtom: model.resolved, dispatch, isTabActive: (tab: WorkspaceTab) => registry.get(model.resolved).selectedTab === tab, bottomClearance: 0, diff --git a/apps/mobile/src/features/layout/workspace/navigation-tabs.ts b/apps/mobile/src/features/layout/workspace/navigation-tabs.ts index e65429198e090..a797d3a6bccf2 100644 --- a/apps/mobile/src/features/layout/workspace/navigation-tabs.ts +++ b/apps/mobile/src/features/layout/workspace/navigation-tabs.ts @@ -13,7 +13,7 @@ import { import type { AppSymbolName } from "../../../components/ui/AppSymbol"; import { mobilePreferencesAtom } from "../../../state/preferences"; import { PullRequestGlyph } from "../../pull-requests/pullRequestGlyphs"; -import { useWorkspaceTabs } from "./WorkspaceTabsContext"; +import { useWorkspaceTabsSelector } from "./WorkspaceTabsContext"; import { resolveWorkspaceTabOrder } from "./workspace-tabs-state"; export const WORKSPACE_TAB_LABELS = { @@ -44,7 +44,7 @@ export function useNavigationTabOrder() { export function useHiddenNavigationTabs() { const preferences = useAtomValue(mobilePreferencesAtom); - const selected = useWorkspaceTabs()?.state.selectedTab ?? "threads"; + const selected = useWorkspaceTabsSelector((state) => state.selectedTab) ?? "threads"; const saved = AsyncResult.isSuccess(preferences) ? preferences.value : undefined; return [ ...(navigationCustomizationAvailable() diff --git a/apps/mobile/src/features/layout/workspace/useSelectWorkspaceTab.ts b/apps/mobile/src/features/layout/workspace/useSelectWorkspaceTab.ts index 25d227b2736dc..3cb9692b91074 100644 --- a/apps/mobile/src/features/layout/workspace/useSelectWorkspaceTab.ts +++ b/apps/mobile/src/features/layout/workspace/useSelectWorkspaceTab.ts @@ -1,12 +1,12 @@ import { Keyboard } from "react-native"; import { useAdaptiveWorkspaceLayout } from "../adaptive-workspace-context"; -import { useWorkspaceTabs } from "./WorkspaceTabsContext"; +import { useWorkspaceTabControls } from "./WorkspaceTabsContext"; import type { WorkspaceTab } from "./workspace-tabs-state"; /** Opens a workspace tab, Settings included, from a tab bar, rail, toolbar or command. */ export function useSelectWorkspaceTab() { - const dispatch = useWorkspaceTabs()?.dispatch; + const dispatch = useWorkspaceTabControls()?.dispatch; const { openWorkspaceTab } = useAdaptiveWorkspaceLayout(); return (tab: WorkspaceTab | "settings") => { Keyboard.dismiss(); diff --git a/apps/mobile/src/features/layout/workspace/useSystemWorkspaceTabBar.ts b/apps/mobile/src/features/layout/workspace/useSystemWorkspaceTabBar.ts index 3cf78b71048d3..3cc569843435a 100644 --- a/apps/mobile/src/features/layout/workspace/useSystemWorkspaceTabBar.ts +++ b/apps/mobile/src/features/layout/workspace/useSystemWorkspaceTabBar.ts @@ -3,13 +3,14 @@ import { Platform } from "react-native"; import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../../native/native-glass"; import { useAdaptiveWorkspaceLayout } from "../adaptive-workspace-context"; import { useDeviceType, useNativeLayoutMetrics } from "../../../native/native-layout-metrics"; -import { useWorkspaceTabs } from "./WorkspaceTabsContext"; +import { useWorkspaceTabControls, useWorkspaceTabsSelector } from "./WorkspaceTabsContext"; import { workspaceUsesColumns } from "./workspace-tabs-state"; function useWorkspacePage() { - const workspace = useWorkspaceTabs(); + const settingsOpen = useWorkspaceTabControls()?.settingsOpen ?? false; return ( - workspace !== null && !workspaceUsesColumns(workspace.state.selectedTab, workspace.settingsOpen) + useWorkspaceTabsSelector((state) => !workspaceUsesColumns(state.selectedTab, settingsOpen)) === + true ); } diff --git a/apps/mobile/src/features/layout/workspace/useWorkspaceCompose.ts b/apps/mobile/src/features/layout/workspace/useWorkspaceCompose.ts index b3f084af573b9..b170bb34bcda6 100644 --- a/apps/mobile/src/features/layout/workspace/useWorkspaceCompose.ts +++ b/apps/mobile/src/features/layout/workspace/useWorkspaceCompose.ts @@ -1,14 +1,14 @@ import { useGT } from "gt-react-native"; import { useAdaptiveWorkspaceLayout } from "../adaptive-workspace-context"; -import { useWorkspaceTabs } from "./WorkspaceTabsContext"; +import { useWorkspaceTabControls, useWorkspaceTabsSelector } from "./WorkspaceTabsContext"; /** What the compose button starts on the selected tab; null where the tab has nothing to start. */ export function useWorkspaceCompose() { const gt = useGT(); - const workspace = useWorkspaceTabs(); + const workspace = useWorkspaceTabControls(); + const threadsSelected = useWorkspaceTabsSelector((state) => state.selectedTab === "threads"); const { startNewTask } = useAdaptiveWorkspaceLayout(); - if (!workspace || workspace.settingsOpen || workspace.state.selectedTab !== "threads") - return null; + if (!workspace || workspace.settingsOpen || threadsSelected !== true) return null; return { label: gt("New chat"), onPress: startNewTask } as const; } diff --git a/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts b/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts index 353292a689143..aca3ff41058dd 100644 --- a/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts +++ b/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts @@ -244,6 +244,9 @@ vi.mock("./navigation-tabs", () => ({ vi.mock("./WorkspaceTabsContext", () => ({ WorkspaceTabsContext: createContext(null), useWorkspaceTabs: () => ({ state: mocks.state, dispatch: () => undefined }), + useWorkspaceTabControls: () => ({ dispatch: () => undefined }), + useWorkspaceTabsSelector: (select: (state: WorkspaceTabsState) => A) => + mocks.state ? select(mocks.state) : undefined, })); vi.mock("./WorkspaceExtraTab", () => ({ WorkspaceExtraTab: function UsageProbe() { diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx index 211a563979c28..6454951bbf55d 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx @@ -47,7 +47,10 @@ import { pullRequestProjectChoices, } from "./pullRequestList"; import { useDebouncedValue } from "../../state/queries"; -import { useWorkspaceTabs } from "../layout/workspace/WorkspaceTabsContext"; +import { + useWorkspaceTabControls, + useWorkspaceTabsSelector, +} from "../layout/workspace/WorkspaceTabsContext"; import { useSearchScrollRestoration } from "../layout/workspace/useSearchScrollRestoration"; import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail"; @@ -100,7 +103,8 @@ export function PullRequestsScreen( const navigation = useNavigation(); const gt = useGT(); const primaryColumn = use(NativePrimaryColumnContext); - const workspace = useWorkspaceTabs()!; + const workspace = useWorkspaceTabControls()!; + const tab = useWorkspaceTabsSelector((state) => state.tabs.pullRequests)!; const { environments } = useWorkspaceState(); const configs = useAtomValue(environmentServerConfigsAtom); const insets = useSafeAreaInsets(); @@ -110,7 +114,6 @@ export function PullRequestsScreen( const bottomSafeArea = Platform.OS === "ios" ? (columnSafeBottom ?? insets.bottom) : insets.bottom; const listRef = useRef(null); - const tab = workspace.state.tabs.pullRequests; const [initialScrollOffset] = useState(() => workspace.getScrollOffset("pullRequests")); useSearchScrollRestoration(tab.searchMode, () => { void listRef.current?.scrollToOffset({ diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx index 2a0edba8a3cea..f8d6676146260 100644 --- a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx @@ -11,7 +11,10 @@ import { import { currentWorkspaceSelections } from "../layout/workspace/workspace-selection-store"; import { rememberedSettingsPage } from "../layout/workspace/workspace-tab-navigation"; import { useSelectWorkspaceTab } from "../layout/workspace/useSelectWorkspaceTab"; -import { useWorkspaceTabs } from "../layout/workspace/WorkspaceTabsContext"; +import { + useWorkspaceTabControls, + useWorkspaceTabsSelector, +} from "../layout/workspace/WorkspaceTabsContext"; import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; import { EmptyState } from "../../components/ui/EmptyState"; import { useAuth, useUser } from "@clerk/expo"; @@ -75,7 +78,8 @@ export function SettingsListScreen(props: { readonly selected: string | null; }) { const gt = useGT(); - const workspace = useWorkspaceTabs(); + const workspace = useWorkspaceTabControls(); + const settingsQuery = useWorkspaceTabsSelector((state) => state.tabs.settings.query); const environmentMenu = useSettingsEnvironmentMenu(); return ( @@ -87,7 +91,7 @@ export function SettingsListScreen(props: { search={ workspace ? { - value: workspace.state.tabs.settings.query, + value: settingsQuery ?? "", onChangeText: (query) => workspace.dispatch({ type: "query", tab: "settings", query }), placeholder: gt("Search settings"), @@ -175,8 +179,8 @@ function SettingsList(props: { readonly connections: readonly SettingsListRow[] const insets = useSafeAreaInsets(); // UIKit insets the scroll view by its column's safe area, which this context can report as 0. const bottomSafeArea = useNativeColumnLayoutMetrics()?.safeArea.bottom ?? insets.bottom; - const workspace = useWorkspaceTabs(); - const query = workspace?.state.tabs.settings.query ?? ""; + const workspace = useWorkspaceTabControls(); + const query = useWorkspaceTabsSelector((state) => state.tabs.settings.query) ?? ""; const overflowRows = useOverflowRows(); const indexSections = useSettingsIndexSections(); const sections = filterSettingsSections( diff --git a/apps/mobile/src/features/settings/components/SettingsScreen.tsx b/apps/mobile/src/features/settings/components/SettingsScreen.tsx index 240ac009bdc5a..078bd643575af 100644 --- a/apps/mobile/src/features/settings/components/SettingsScreen.tsx +++ b/apps/mobile/src/features/settings/components/SettingsScreen.tsx @@ -5,7 +5,7 @@ import { View } from "react-native"; import type { AppBarProps } from "../../../components/ui/AppBar.types"; import { AppBar } from "../../../components/ui/AppBar"; import { ScreenContent as SettingsScreenContent } from "../../../components/ui/ScreenContent"; -import { useWorkspaceTabs } from "../../layout/workspace/WorkspaceTabsContext"; +import { useWorkspaceTabControls } from "../../layout/workspace/WorkspaceTabsContext"; import { useDeviceType } from "../../../native/native-layout-metrics"; import { useCompactWorkspaceTabs } from "../../layout/workspace/useSystemWorkspaceTabBar"; import { useSettingsPageBack } from "../useSettingsPageBack"; @@ -26,7 +26,7 @@ export function SettingsScreen( }, ) { const route = useRoute(); - const workspace = useWorkspaceTabs(); + const workspace = useWorkspaceTabControls(); const deviceType = useDeviceType(); const compactTabs = useCompactWorkspaceTabs(); const back = useSettingsPageBack(); diff --git a/apps/mobile/src/i18n/intl-polyfills.ts b/apps/mobile/src/i18n/intl-polyfills.ts index 68ab81c65f994..47265c39279f8 100644 --- a/apps/mobile/src/i18n/intl-polyfills.ts +++ b/apps/mobile/src/i18n/intl-polyfills.ts @@ -16,3 +16,21 @@ import "@formatjs/intl-pluralrules/locale-data/pt"; import "@formatjs/intl-pluralrules/locale-data/ru"; import "@formatjs/intl-pluralrules/locale-data/sv"; import "@formatjs/intl-pluralrules/locale-data/zh"; +import { Platform } from "react-native"; + +// Hermes on Android builds a fresh collator across JNI for every localeCompare, so sorting a few +// hundred labels took a quarter second; one shared collator compares the same way ~17x faster. +if (Platform.OS === "android") { + const collator = new Intl.Collator(); + const localeCompare = String.prototype.localeCompare; + String.prototype.localeCompare = function ( + this: string, + that: string, + locales?: Intl.LocalesArgument, + options?: Intl.CollatorOptions, + ) { + return locales === undefined && options === undefined + ? collator.compare(this, that) + : localeCompare.call(this, that, locales, options); + }; +} From 2adb4f3165f3c6bfe692239f485f8c4bb40dd05d Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Sat, 28 Nov 2026 19:46:26 +0530 Subject: [PATCH 03/15] perf(mobile): the model picker scrolls without per-row native views Android drew each model row's radio with its own Jetpack Compose host, so expanding a provider with hundreds of models mounted a Compose view per row. The radio is now drawn with views. Catalog rows also dropped their keyed fade-in, which remounted every row scrolled into view and showed it half transparent; the list's layout animation still moves rows on filter changes. --- .../components/ui/RadioIndicator.android.tsx | 37 +++++++------- .../features/threads/ThreadSettingsSheet.tsx | 49 ++++++++----------- 2 files changed, 37 insertions(+), 49 deletions(-) diff --git a/apps/mobile/src/components/ui/RadioIndicator.android.tsx b/apps/mobile/src/components/ui/RadioIndicator.android.tsx index a0af5597b1c7f..c3066aae5db36 100644 --- a/apps/mobile/src/components/ui/RadioIndicator.android.tsx +++ b/apps/mobile/src/components/ui/RadioIndicator.android.tsx @@ -1,28 +1,25 @@ -import { RadioButton } from "@expo/ui/jetpack-compose"; -import { size } from "@expo/ui/jetpack-compose/modifiers"; import { View } from "react-native"; -import { NativeThemeHost } from "./NativeThemeHost.android"; -import { useControlTheme } from "./useControlTheme"; +import { cn } from "../../lib/cn"; + +// Material's radio, drawn with views: a Compose RadioButton needs a Compose host per row, and +// mounting hundreds of those made long pickers stutter while scrolling. /** The enclosing radio row owns selection, touch and accessibility. */ export function RadioIndicator({ selected }: { readonly selected: boolean }) { - const { colors, systemColorsActive } = useControlTheme(); return ( - - - - + + + {selected ? : null} + ); } diff --git a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx index 22d736b8143ed..5bd3466c24acd 100644 --- a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx @@ -138,8 +138,6 @@ const THREAD_SETTINGS_MAINTAIN_VISIBLE_CONTENT_POSITION = { size: true, } as const; const THREAD_SETTINGS_CATALOG_LAYOUT_TRANSITION = LinearTransition.duration(180); -const THREAD_SETTINGS_CATALOG_ENTER_TRANSITION = FadeIn.duration(140); -const THREAD_SETTINGS_CATALOG_EXIT_TRANSITION = FadeOut.duration(120); const THREAD_SETTINGS_OPTIONS_LAYOUT_TRANSITION = LinearTransition.duration(180); const THREAD_SETTINGS_OPTION_ENTER_TRANSITION = FadeIn.duration(140); const THREAD_SETTINGS_OPTION_EXIT_TRANSITION = FadeOut.duration(100); @@ -1133,26 +1131,30 @@ function ThreadSettingsMainContent(props: { ...(catalogItems.length === 0 ? ([{ kind: "empty", key: "empty" }] as const) : catalogItems), { kind: "options", key: "options" }, ] satisfies ReadonlyArray; + // Rows recycle without an entering fade: keyed fades remounted every row scrolled into view and + // showed it half transparent. The list's item layout animation still moves rows on filter changes. const renderCatalogItem = (itemProps: LegendListRenderItemProps) => { const item = itemProps.item; - let content: ReactNode; - if (item.kind === "provider") { - content = ; - } else if (item.kind === "subProvider") { - content = ; - } else if (item.kind === "model") { - content = ( + return ; + } + if (item.kind === "subProvider") { + return ; + } + if (item.kind === "model") { + return ( ); - } else if (item.kind === "notice") { - content = {item.text}; - } else if (item.kind === "empty") { - content = ( + } + if (item.kind === "notice") { + return {item.text}; + } + if (item.kind === "empty") { + return ( {session.favoritesOnly && @@ -1165,24 +1167,13 @@ function ThreadSettingsMainContent(props: { ); - } else { - content = ( - - ); } - return ( - - {content} - + ); }; From 974eb9d9ce600c912e2d21419407d1bae39dc9fb Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Sat, 28 Nov 2026 20:02:16 +0530 Subject: [PATCH 04/15] perf(mobile): Android date labels reuse one formatter Hermes on Android built a new date formatter for every toLocaleString call, about 25x the cost of a shared one, and the usage widget snapshot formats a label per limit window. Date's locale methods now cache a formatter per locale and options, with the same defaults and errors as the native methods. --- apps/mobile/src/i18n/intl-polyfills.ts | 54 ++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/apps/mobile/src/i18n/intl-polyfills.ts b/apps/mobile/src/i18n/intl-polyfills.ts index 47265c39279f8..0300cc683544b 100644 --- a/apps/mobile/src/i18n/intl-polyfills.ts +++ b/apps/mobile/src/i18n/intl-polyfills.ts @@ -33,4 +33,58 @@ if (Platform.OS === "android") { ? collator.compare(this, that) : localeCompare.call(this, that, locales, options); }; + + // Date's locale methods pay the same per-call cost (~25x a shared formatter), so they reuse one + // formatter per locale and options. Defaults follow ECMA-402 ToDateTimeOptions. + const dateFields = ["weekday", "year", "month", "day"] as const; + const timeFields = ["dayPeriod", "hour", "minute", "second", "fractionalSecondDigits"] as const; + const formatters = new Map(); + const cachedDateMethod = ( + native: (locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions) => string, + required: "any" | "date" | "time", + defaults: "all" | "date" | "time", + ) => + function (this: Date, locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions) { + // Native keeps the spec's TypeError for a time style on a date-only method (and the + // reverse) and its own text for an invalid date. + if ( + (required === "date" && options?.timeStyle !== undefined) || + (required === "time" && options?.dateStyle !== undefined) || + Number.isNaN(this.getTime()) + ) + return native.call(this, locales, options); + const key = JSON.stringify([required, defaults, locales, options]); + let formatter = formatters.get(key); + if (!formatter) { + const has = (fields: ReadonlyArray) => + fields.some((field) => options?.[field] !== undefined); + const needsDefaults = + options?.dateStyle === undefined && + options?.timeStyle === undefined && + !(required !== "time" && has(dateFields)) && + !(required !== "date" && has(timeFields)); + formatter = new Intl.DateTimeFormat(locales, { + ...options, + ...(needsDefaults && defaults !== "time" + ? { year: "numeric", month: "numeric", day: "numeric" } + : {}), + ...(needsDefaults && defaults !== "date" + ? { hour: "numeric", minute: "numeric", second: "numeric" } + : {}), + }); + formatters.set(key, formatter); + } + return formatter.format(this); + }; + Date.prototype.toLocaleString = cachedDateMethod(Date.prototype.toLocaleString, "any", "all"); + Date.prototype.toLocaleDateString = cachedDateMethod( + Date.prototype.toLocaleDateString, + "date", + "date", + ); + Date.prototype.toLocaleTimeString = cachedDateMethod( + Date.prototype.toLocaleTimeString, + "time", + "time", + ); } From 95f7c6e688d2e96ab6f83209b52ae5d95a422c2f Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Sat, 28 Nov 2026 20:32:14 +0530 Subject: [PATCH 05/15] perf(mobile): pull request lists skip per-row edit lookups when idle Every list update built a key and subscribed an atom per pull request to find its pending edits, about a second of work for a few hundred pull requests on Android. Rows now skip those lookups while the environment has no write in flight; the list still re-derives when one starts. --- .../mobile/src/features/pull-requests/usePullRequestList.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/mobile/src/features/pull-requests/usePullRequestList.ts b/apps/mobile/src/features/pull-requests/usePullRequestList.ts index b7ad230e69db8..1771fd2abe5fe 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestList.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestList.ts @@ -2,6 +2,7 @@ import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; import { editHeldPullRequestListEntries, pullRequestHostAnswer, + pullRequestPendingEditsAtom, pullRequestPendingEditsFor, } from "@t3tools/client-runtime/state/pull-requests"; import { RegistryContext, useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react"; @@ -61,6 +62,9 @@ const sourcesFamily = Atom.family((key: string) => { return Atom.make((get) => targets.map((target) => { const pages = currentPages(get, target); + // Per-row edit atoms cost a key and a subscription each, so rows skip them while the + // environment has no write in flight; this read still re-derives the list when one starts. + const editing = get(pullRequestPendingEditsAtom(target.environmentId)).length > 0; return { target, result: get(composerPullRequests.list(target)), @@ -70,7 +74,7 @@ const sourcesFamily = Atom.family((key: string) => { : { ...pages, entries: editHeldPullRequestListEntries(target.input, pages.entries, (entry) => - get(pullRequestPendingEditsFor(target.environmentId, entry)), + editing ? get(pullRequestPendingEditsFor(target.environmentId, entry)) : [], ), }, stats: get(pullRequestListStatsFamily(target.environmentId)), From ade99f67456768b34d574b564d3e875393f9b9de Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Sat, 28 Nov 2026 22:03:56 +0530 Subject: [PATCH 06/15] perf(mobile): SVG icon colors no longer stall Android renders React Native's color cache deleted and re-added its entry on every hit. Rendering a screen of SVG icons on Hermes then spent 100-360 ms at a time in Map.set. Hits now return the cached color directly. --- ...eact-native__normalize-colors@0.88.1.patch | 22 +++++++++++++++++++ pnpm-lock.yaml | 8 ++++--- pnpm-workspace.yaml | 4 ++++ 3 files changed, 31 insertions(+), 3 deletions(-) create mode 100644 patches/@react-native__normalize-colors@0.88.1.patch diff --git a/patches/@react-native__normalize-colors@0.88.1.patch b/patches/@react-native__normalize-colors@0.88.1.patch new file mode 100644 index 0000000000000..8625a7e1d86a9 --- /dev/null +++ b/patches/@react-native__normalize-colors@0.88.1.patch @@ -0,0 +1,22 @@ +diff --git a/index.js b/index.js +index 05bdc3a..7e4d727 100644 +--- a/index.js ++++ b/index.js +@@ -26,13 +26,11 @@ function normalizeColor(color) { + return null; + } + ++ // Hits return without re-inserting: deleting and re-adding on every hit made Hermes rebuild the ++ // map in bursts of hundreds of milliseconds when a screen of SVG icons rendered. Eviction is ++ // first-in first-out instead of least-recently-used. + if (cachedColors.has(color)) { +- // Map iteration order follows insertion order, so re-inserting on every +- // hit keeps the least-recently-used entry first. +- const cachedColor = cachedColors.get(color); +- cachedColors.delete(color); +- cachedColors.set(color, cachedColor); +- return cachedColor; ++ return cachedColors.get(color); + } + const normalizedColor = parseColorString(color); + if (cachedColors.size >= 1024) { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3a90e98ee1035..178959f4964dc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -275,6 +275,7 @@ catalogs: overrides: react-native-image-viewing: 0.2.2 + '@react-native/normalize-colors': 0.88.1 '@exodus/bytes': 1.15.1 mdast-util-math: 3.0.0 micromark-extension-llm-math: 3.1.0 @@ -380,6 +381,7 @@ patchedDependencies: '@muse-code/sdk@1.4.6': 7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101 '@pierre/diffs@1.7.0-beta.4': 7edcdd484a99c7ec0b2667499c4cb21d113ec9bea1f8570c0b0a030d33bbf1cd '@react-native-menu/menu@2.0.0': 6872ba71b9847c5a0210b1b896923dadc3860faedfe28d9f062bcedfe786ef1d + '@react-native/normalize-colors@0.88.1': 0c038b393348a4a113ca2e152d982c76f09f0cf5e46b19383c6232032b1e0928 '@react-navigation/native-stack@7.21.0': 990d575444c4af2ce8218b3b7a8280fe244c03abbdb32b822a2e862f791dbf42 alchemy@2.0.0-beta.85: 07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd app-builder-lib@26.16.1: 0fbe9ae51783f5768ebe197d12d1fdb7d477a08c92e5db2f6356bcce62613c53 @@ -15250,7 +15252,7 @@ snapshots: '@expo/config-types': 58.0.3 '@expo/image-utils': 0.12.7(supports-color@8.1.1)(typescript@6.0.3) '@expo/json-file': 11.2.1 - '@react-native/normalize-colors': 0.88.1 + '@react-native/normalize-colors': 0.88.1(patch_hash=0c038b393348a4a113ca2e152d982c76f09f0cf5e46b19383c6232032b1e0928) debug: 4.4.3(supports-color@8.1.1) expo-modules-autolinking: 58.1.0(supports-color@8.1.1)(typescript@6.0.3) resolve-from: 5.0.0 @@ -16838,7 +16840,7 @@ snapshots: - supports-color - utf-8-validate - '@react-native/normalize-colors@0.88.1': {} + '@react-native/normalize-colors@0.88.1(patch_hash=0c038b393348a4a113ca2e152d982c76f09f0cf5e46b19383c6232032b1e0928)': {} '@react-native/virtualized-lists@0.88.1(@types/react@19.3.0)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)': dependencies: @@ -22768,7 +22770,7 @@ snapshots: '@react-native/codegen': 0.88.1(@babel/core@7.29.7(supports-color@8.1.1)) '@react-native/community-cli-plugin': 0.88.1(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6) '@react-native/gradle-plugin': 0.88.1 - '@react-native/normalize-colors': 0.88.1 + '@react-native/normalize-colors': 0.88.1(patch_hash=0c038b393348a4a113ca2e152d982c76f09f0cf5e46b19383c6232032b1e0928) '@react-native/virtualized-lists': 0.88.1(@types/react@19.3.0)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) anser: 1.4.10 ansi-regex: 5.0.1 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 6fd627792f5e7..c62625c532b0e 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -104,6 +104,7 @@ overrides: # Pin every patched package, including transitive dependencies, so lockfile-free # release installs cannot drift past the patch. Update these with patchedDependencies. react-native-image-viewing: 0.2.2 + "@react-native/normalize-colors": 0.88.1 "@exodus/bytes": 1.15.1 mdast-util-math: 3.0.0 micromark-extension-llm-math: 3.1.0 @@ -298,6 +299,9 @@ patchedDependencies: # Every translated string reparsed its message and re-resolved its locale on each render, which # crosses JNI on Android and stalled taps for seconds; cache both per locale. "@generaltranslation/icu@0.1.2": patches/@generaltranslation__icu@0.1.2.patch + # Android: a color cache hit no longer deletes and re-adds its entry, which stalled renders of + # SVG icons on Hermes. + "@react-native/normalize-colors@0.88.1": patches/@react-native__normalize-colors@0.88.1.patch # Unmet peers fail resolution, so a pin outside a dependency's peer range is # caught when the lockfile changes instead of scrolling past as a warning. From 59a5b368d990576fe768d5a6263a9d301123d716 Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Sat, 28 Nov 2026 22:03:58 +0530 Subject: [PATCH 07/15] perf(client-runtime): provider check stamps no longer rewrite the config cache Hosts re-stamp every provider's checkedAt on each status check. With several environments, clients re-encoded and saved the whole server config, model lists included, every few seconds. That was about 13% of JS time on Android. A change to only checkedAt is now saved at most every five minutes; any other change still saves at once. --- .../client-runtime/src/state/server.test.ts | 45 +++++++++++++++++++ packages/client-runtime/src/state/server.ts | 34 +++++++++++--- 2 files changed, 74 insertions(+), 5 deletions(-) diff --git a/packages/client-runtime/src/state/server.test.ts b/packages/client-runtime/src/state/server.test.ts index ed8458d3dd189..2ec6154fbf095 100644 --- a/packages/client-runtime/src/state/server.test.ts +++ b/packages/client-runtime/src/state/server.test.ts @@ -576,6 +576,51 @@ describe("server state projection", () => { }), ); + it.effect("saves provider check stamps at most every five minutes", () => + Effect.gen(function* () { + const saved = yield* Ref.make>([]); + const checked = (checkedAt: string, enabled = true) => + snapshotEvent({ + ...CONFIG, + providers: [ + { + instanceId: ProviderInstanceId.make("codex"), + enabled, + checkedAt, + usageLimits: { checkedAt }, + } as unknown as ServerConfig["providers"][number], + ], + }); + const savedStamps = Effect.map(Ref.get(saved), (configs) => + configs.map((config) => config.providers[0]?.checkedAt), + ); + yield* Effect.scoped( + Effect.gen(function* () { + const h = yield* makeConfigPersistenceHarness((_id, config) => + Ref.update(saved, (values) => [...values, config]), + ); + yield* h.send(checked("2026-11-28T00:00:00.000Z")); + yield* TestClock.adjust("10 seconds"); + yield* h.send(checked("2026-11-28T00:00:10.000Z")); + yield* TestClock.adjust("10 seconds"); + expect(yield* savedStamps).toEqual(["2026-11-28T00:00:00.000Z"]); + + yield* h.send(checked("2026-11-28T00:00:20.000Z", false)); + yield* TestClock.adjust("10 seconds"); + expect(yield* savedStamps).toEqual([ + "2026-11-28T00:00:00.000Z", + "2026-11-28T00:00:20.000Z", + ]); + + yield* TestClock.adjust("5 minutes"); + yield* h.send(checked("2026-11-28T00:05:40.000Z", false)); + yield* TestClock.adjust("10 seconds"); + expect((yield* savedStamps).at(-1)).toBe("2026-11-28T00:05:40.000Z"); + }), + ); + }), + ); + it.effect("saves once across transient themes, usage sources and stall updates", () => Effect.gen(function* () { const saved = yield* Ref.make>([]); diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index 492a9e9268714..356b0cf6c43cd 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -26,6 +26,7 @@ import { WS_METHODS, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; import * as Duration from "effect/Duration"; import * as Equal from "effect/Equal"; import * as Deferred from "effect/Deferred"; @@ -530,7 +531,8 @@ function withFetchedMachineCatalogs( } // Configs are JSON-shaped. Missing and undefined object fields persist identically. -function sameCacheValue(previous: unknown, next: unknown): boolean { +// `ignoreCheckStamps` treats `checkedAt` fields as equal. +function sameCacheValue(previous: unknown, next: unknown, ignoreCheckStamps = false): boolean { if (previous === next) return true; if ( previous === null || @@ -545,7 +547,7 @@ function sameCacheValue(previous: unknown, next: unknown): boolean { return false; } for (let index = 0; index < previous.length; index += 1) { - if (!sameCacheValue(previous[index], next[index])) return false; + if (!sameCacheValue(previous[index], next[index], ignoreCheckStamps)) return false; } return true; } @@ -558,12 +560,20 @@ function sameCacheValue(previous: unknown, next: unknown): boolean { const before = previous as Record; const after = next as Record; return ( - Object.keys(before).every((key) => - sameCacheValue(before[key], Object.hasOwn(after, key) ? after[key] : undefined), + Object.keys(before).every( + (key) => + (ignoreCheckStamps && key === "checkedAt") || + sameCacheValue( + before[key], + Object.hasOwn(after, key) ? after[key] : undefined, + ignoreCheckStamps, + ), ) && Object.keys(after).every((key) => Object.hasOwn(before, key) || after[key] === undefined) ); } +const CHECK_STAMP_SAVE_INTERVAL_MS = 5 * 60_000; + export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConfigState.make")( function* ( subscription: ServerConfigSubscriptionOptions, @@ -594,6 +604,7 @@ export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConf const persistence = yield* Queue.sliding(1); const pendingPersistence = yield* Ref.make>(Option.none()); let lastPersisted: ServerConfig | undefined; + let lastPersistedAt = 0; const persist = Effect.fn("EnvironmentServerConfigState.persist")(function* ( config: ServerConfig, @@ -610,6 +621,16 @@ export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConf if (lastPersisted !== undefined && sameCacheValue(lastPersisted, cacheable)) { return true; } + // Hosts re-stamp every provider's `checkedAt` each status check, every few seconds across + // several hosts, and each save re-encodes the whole config with its model lists. + const now = yield* Clock.currentTimeMillis; + if ( + lastPersisted !== undefined && + now - lastPersistedAt < CHECK_STAMP_SAVE_INTERVAL_MS && + sameCacheValue(lastPersisted, cacheable, true) + ) { + return true; + } const saved = yield* cache.saveServerConfig(environmentId, cacheable).pipe( Effect.as(true), Effect.catch((error) => @@ -622,7 +643,10 @@ export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConf ), ), ); - if (saved) lastPersisted = cacheable; + if (saved) { + lastPersisted = cacheable; + lastPersistedAt = now; + } return saved; }); From 4c053af4111a6a524976b31ac076bb9a6009f435 Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Sat, 28 Nov 2026 22:04:26 +0530 Subject: [PATCH 08/15] perf(mobile): environment details open without a delay The connection row's resize and fade animations ran 10-11 slow frames (450-640 ms on a low-end emulator) before the details settled. The details now appear in place in 3-4 frames. --- .../connection/ConnectionEnvironmentRow.tsx | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx b/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx index 8174b6bdfe8ef..af38ebec174fc 100644 --- a/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx +++ b/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx @@ -11,7 +11,6 @@ import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; import { useState } from "react"; import { Platform, Pressable, View } from "react-native"; -import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated"; import { m as resolveMessage } from "../../i18n/messages"; import { AppText as Text } from "../../components/ui/AppText"; @@ -118,7 +117,7 @@ export function ConnectionEnvironmentRow(props: { }); return ( - + + {/* Opens in place without a resize or fade: those animations held the details back for + about half a second on slower Android phones. */} {props.expanded ? ( - + {diagnosis ? ( )} - + ) : null} - + ); } From bdd2a805b5cb2e088fa69f89d71c2556b6286c14 Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Sat, 28 Nov 2026 22:38:51 +0530 Subject: [PATCH 09/15] fix(mobile): hidden iOS tabs keep the page they showed A retained iOS tab slot read the selected tab live through the tabs atom, so after switching away it could re-render with the newly selected tab's page. Each slot now reads the tab state with its own tab pinned as selected. --- .../workspace/WorkspaceNativeTabs.ios.tsx | 32 ++++++++++----- .../workspace/workspace-tabs-state.test.ts | 14 +++++++ .../layout/workspace/workspace-tabs-state.ts | 9 +++++ apps/mobile/src/i18n/intl-polyfills.test.ts | 40 +++++++++++++++++++ 4 files changed, 86 insertions(+), 9 deletions(-) create mode 100644 apps/mobile/src/i18n/intl-polyfills.test.ts diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx index 0e09ba631da31..94a3cd098777f 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx @@ -1,4 +1,3 @@ -import { Atom } from "effect/reactivity"; import { useGT, useMessages } from "gt-react-native"; import { WORKSPACE_TAB_LABELS, @@ -8,6 +7,7 @@ import { import { useEffect, useLayoutEffect, + useMemo, useRef, useState, type Dispatch, @@ -21,6 +21,7 @@ import { WorkspaceTabsContext, useWorkspaceTabs } from "./WorkspaceTabsContext"; import type { NavigationTab } from "./navigation-tab-order"; import { NATIVE_WORKSPACE_TAB_SLOTS, + pinnedWorkspaceTabsAtom, workspaceTabForNativeSlot, workspaceUsesColumns, } from "./workspace-tabs-state"; @@ -59,24 +60,37 @@ function RetainedWorkspaceTab(props: { activeRef.current = props.active; }, [props.active]); const isActive = () => activeRef.current; + // Bound to this slot's tab, so a hidden slot keeps the page it showed while its search state + // stays live. + const slotAtom = useMemo( + () => pinnedWorkspaceTabsAtom(workspace.stateAtom, props.tab), + [workspace.stateAtom, props.tab], + ); + const slotWorkspace = { + ...workspace, + // The settings slot also shows an overflow tab, which it does without Settings open. + settingsOpen: props.active ? workspace.settingsOpen : props.slot === "settings", + state: { ...workspace.state, selectedTab: props.tab }, + stateAtom: slotAtom, + }; const [content, setContent] = useState( props.active - ? { source: workspace, workspace, children: props.children, headerOnly: false } + ? { source: workspace, workspace: slotWorkspace, children: props.children, headerOnly: false } : null, ); const stale = content?.source !== workspace || content?.children !== props.children; if (props.active && (content?.headerOnly !== false || stale)) - setContent({ source: workspace, workspace, children: props.children, headerOnly: false }); + setContent({ + source: workspace, + workspace: slotWorkspace, + children: props.children, + headerOnly: false, + }); // A slot not shown yet follows the workspace, so the page it opens with stays current. else if (!props.active && props.prewarm && (content === null || (content.headerOnly && stale))) setContent({ source: workspace, - workspace: { - ...workspace, - settingsOpen: props.slot === "settings", - state: { ...workspace.state, selectedTab: props.tab }, - stateAtom: Atom.make((get) => ({ ...get(workspace.stateAtom), selectedTab: props.tab })), - }, + workspace: slotWorkspace, children: props.children, headerOnly: true, }); diff --git a/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts b/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts index aca3ff41058dd..3fe4ba555c3d1 100644 --- a/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts +++ b/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts @@ -1,9 +1,11 @@ import { describe, expect, it, vi } from "vite-plus/test"; import { act, createElement, createContext, useState, type ReactNode } from "react"; import { createRoot } from "react-dom/client"; +import { Atom, AtomRegistry } from "effect/reactivity"; import { WorkspaceRootScreen } from "./WorkspaceRootScreen.android"; import { initialWorkspaceTabsState, + pinnedWorkspaceTabsAtom, workspaceTabsReducer, shouldRestoreNativeSearch, workspaceTabForNativeSlot, @@ -193,6 +195,18 @@ describe("workspace root navigation", () => { state = workspaceTabsReducer(state, { type: "select", tab: "threads" }); expect(state.tabs.threads.query).toBe("retained"); }); + it("a retained slot keeps its own tab after the user switches away, with live search state", () => { + const registry = AtomRegistry.make(); + const base = Atom.make(initialWorkspaceTabsState()); + const threadsSlot = pinnedWorkspaceTabsAtom(base, "threads"); + using _mount = { [Symbol.dispose]: registry.mount(threadsSlot) }; + let state = workspaceTabsReducer(registry.get(base), { type: "select", tab: "issues" }); + state = workspaceTabsReducer(state, { type: "query", query: "crash", tab: "threads" }); + registry.set(base, state); + expect(registry.get(threadsSlot).selectedTab).toBe("threads"); + expect(registry.get(threadsSlot).tabs.threads.query).toBe("crash"); + }); + it("opens Settings on native reselection instead of selecting its overflow section", () => { const order = ["threads", "pullRequests", "usage"] as const; expect(workspaceTabForNativeSlot(order, "settings")).toBe("settings"); diff --git a/apps/mobile/src/features/layout/workspace/workspace-tabs-state.ts b/apps/mobile/src/features/layout/workspace/workspace-tabs-state.ts index 3bf3a447aac3d..e6d071a702595 100644 --- a/apps/mobile/src/features/layout/workspace/workspace-tabs-state.ts +++ b/apps/mobile/src/features/layout/workspace/workspace-tabs-state.ts @@ -1,3 +1,4 @@ +import { Atom } from "effect/reactivity"; import { NAVIGATION_TAB_ORDER, navigationCustomizationAvailable, @@ -34,6 +35,14 @@ export interface WorkspaceTabsState { readonly tabs: Readonly>; } +/** + * The tab state as a slot for `tab` sees it: live, except that its own tab stays selected, so a + * retained iOS slot keeps rendering its own page after the user switches away. + */ +export function pinnedWorkspaceTabsAtom(base: Atom.Atom, tab: WorkspaceTab) { + return Atom.make((get) => ({ ...get(base), selectedTab: tab })); +} + function emptyTab(): WorkspaceTabState { return { query: "", searchMode: "resting", scrollOffset: 0, searchEntryOffset: 0 }; } diff --git a/apps/mobile/src/i18n/intl-polyfills.test.ts b/apps/mobile/src/i18n/intl-polyfills.test.ts new file mode 100644 index 0000000000000..9375d85b6f4f4 --- /dev/null +++ b/apps/mobile/src/i18n/intl-polyfills.test.ts @@ -0,0 +1,40 @@ +import { afterAll, beforeAll, describe, expect, it, vi } from "vite-plus/test"; + +vi.mock("react-native", () => ({ Platform: { OS: "android" } })); + +const native = { + localeCompare: String.prototype.localeCompare, + toLocaleString: Date.prototype.toLocaleString, + toLocaleDateString: Date.prototype.toLocaleDateString, + toLocaleTimeString: Date.prototype.toLocaleTimeString, +}; +const timeZone = process.env.TZ; + +describe("Android Date locale formatter cache", () => { + beforeAll(async () => { + await import("./intl-polyfills"); + }); + afterAll(() => { + String.prototype.localeCompare = native.localeCompare; + Date.prototype.toLocaleString = native.toLocaleString; + Date.prototype.toLocaleDateString = native.toLocaleDateString; + Date.prototype.toLocaleTimeString = native.toLocaleTimeString; + process.env.TZ = timeZone; + }); + + it("keeps different Intl.Locale objects apart", () => { + const date = new Date(Date.UTC(2026, 0, 31, 12)); + const options = { month: "long", timeZone: "UTC" } as const; + expect(date.toLocaleDateString(new Intl.Locale("en-US"), options)).toBe("January"); + expect(date.toLocaleDateString(new Intl.Locale("de-DE"), options)).toBe("Januar"); + }); + + it("follows a device time zone change", () => { + const date = new Date(Date.UTC(2026, 0, 31, 12)); + process.env.TZ = "UTC"; + const utc = date.toLocaleTimeString("en-US"); + process.env.TZ = "Asia/Kolkata"; + expect(date.toLocaleTimeString("en-US")).not.toBe(utc); + expect(date.toLocaleTimeString("en-US")).toBe(native.toLocaleTimeString.call(date, "en-US")); + }); +}); From 956944dd0922a44b73069b23bc525246530bacbd Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Sat, 28 Nov 2026 22:39:52 +0530 Subject: [PATCH 10/15] fix(mobile): Android date formatter cache keys locales and time zone Intl.Locale objects all keyed as {} and shared one formatter, and a device time zone change kept formatting in the old zone. The key now uses locale tags and, without an explicit zone, the local offset. --- apps/mobile/src/i18n/intl-polyfills.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/apps/mobile/src/i18n/intl-polyfills.ts b/apps/mobile/src/i18n/intl-polyfills.ts index 0300cc683544b..5239c8a67fb45 100644 --- a/apps/mobile/src/i18n/intl-polyfills.ts +++ b/apps/mobile/src/i18n/intl-polyfills.ts @@ -53,7 +53,16 @@ if (Platform.OS === "android") { Number.isNaN(this.getTime()) ) return native.call(this, locales, options); - const key = JSON.stringify([required, defaults, locales, options]); + // Intl.Locale objects stringify to their tags; JSON would collapse them all to {}. Without an + // explicit zone the key carries the local offset, a cheap native read, so a device zone change + // gets a new formatter; reading the zone's name would mean building a formatter per call. + const key = JSON.stringify([ + required, + defaults, + typeof locales === "object" ? [locales].flat().map(String) : locales, + options, + options?.timeZone === undefined ? this.getTimezoneOffset() : null, + ]); let formatter = formatters.get(key); if (!formatter) { const has = (fields: ReadonlyArray) => From 019900d1de0165faaf5a25dcf20967ac290090c0 Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Sat, 28 Nov 2026 22:42:12 +0530 Subject: [PATCH 11/15] fix(mobile): Android date formatting keeps inherited options Options with a custom prototype lost their inherited fields to the spread in the formatter cache. They now go to the native method, which reads them. --- apps/mobile/src/i18n/intl-polyfills.test.ts | 6 ++++++ apps/mobile/src/i18n/intl-polyfills.ts | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/apps/mobile/src/i18n/intl-polyfills.test.ts b/apps/mobile/src/i18n/intl-polyfills.test.ts index 9375d85b6f4f4..8872254d4bbe8 100644 --- a/apps/mobile/src/i18n/intl-polyfills.test.ts +++ b/apps/mobile/src/i18n/intl-polyfills.test.ts @@ -29,6 +29,12 @@ describe("Android Date locale formatter cache", () => { expect(date.toLocaleDateString(new Intl.Locale("de-DE"), options)).toBe("Januar"); }); + it("reads inherited options", () => { + const date = new Date(Date.UTC(2026, 0, 31, 9)); + const options = Object.create({ hour: "2-digit", timeZone: "UTC" }); + expect(date.toLocaleString("en-US", options)).toBe("09 AM"); + }); + it("follows a device time zone change", () => { const date = new Date(Date.UTC(2026, 0, 31, 12)); process.env.TZ = "UTC"; diff --git a/apps/mobile/src/i18n/intl-polyfills.ts b/apps/mobile/src/i18n/intl-polyfills.ts index 5239c8a67fb45..ce57371e7ff0b 100644 --- a/apps/mobile/src/i18n/intl-polyfills.ts +++ b/apps/mobile/src/i18n/intl-polyfills.ts @@ -46,8 +46,9 @@ if (Platform.OS === "android") { ) => function (this: Date, locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions) { // Native keeps the spec's TypeError for a time style on a date-only method (and the - // reverse) and its own text for an invalid date. + // reverse), its own text for an invalid date, and inherited options the spread would drop. if ( + (options != null && Object.getPrototypeOf(options) !== Object.prototype) || (required === "date" && options?.timeStyle !== undefined) || (required === "time" && options?.dateStyle !== undefined) || Number.isNaN(this.getTime()) From 1b5fc5d128faaa61a98e1daee2e49746749299e5 Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Sun, 29 Nov 2026 01:48:01 +0530 Subject: [PATCH 12/15] perf(mobile): Android tabs stay live instead of rebuilding on every switch Hidden tab panes used , whose display:none makes Fabric drop and rebuild the pane's native views on each switch. Panes now stay mounted under the shown one, like iOS's retained tabs, and Back and hardware keyboard commands only register for the shown tab. --- .../keyboard/hardwareKeyboardCommands.ts | 10 +++- .../layout/workspace/WorkspaceTabPanes.tsx | 55 ++++++++++++++----- .../workspace/workspace-tabs-state.test.ts | 1 + apps/mobile/src/lib/backHandler.ts | 7 ++- 4 files changed, 56 insertions(+), 17 deletions(-) diff --git a/apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts b/apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts index 3525e17828099..96cc420d5cb42 100644 --- a/apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts +++ b/apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts @@ -1,5 +1,7 @@ import { EnvironmentId, ThreadId, type ThreadJumpKeybindingCommand } from "@t3tools/contracts"; -import { useEffect } from "react"; +import { use, useEffect } from "react"; + +import { NativeWorkspaceTabActivityContext } from "../../native/v5-workspace-context"; export type HardwareKeyboardCommand = | ThreadJumpKeybindingCommand @@ -27,8 +29,12 @@ export function useHardwareKeyboardCommand( command: HardwareKeyboardCommand | ReadonlyArray, handler: CommandHandler, ): void { + // A retained tab stays mounted while another is shown; the newest handler wins, so a hidden tab + // must not register. + const tabActive = use(NativeWorkspaceTabActivityContext)?.active ?? true; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the handler in the module-level hardware keyboard command registry useEffect(() => { + if (!tabActive) return; const commands = typeof command === "string" ? [command] : command; for (const command of commands) { const commandHandlers = handlers.get(command) ?? new Set(); @@ -46,7 +52,7 @@ export function useHardwareKeyboardCommand( registrationVersion += 1; registrationListeners.forEach((listener) => listener()); }; - }, [command, handler]); + }, [command, handler, tabActive]); } export function getRegisteredHardwareKeyboardCommands(): ReadonlySet { diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceTabPanes.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceTabPanes.tsx index 3a91ada8b8efa..90abc65e9d3c4 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceTabPanes.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceTabPanes.tsx @@ -1,11 +1,12 @@ -import { Activity, useState, type ReactNode } from "react"; -import { View } from "react-native"; +import { useLayoutEffect, useRef, useState, type ReactNode } from "react"; +import { StyleSheet, View } from "react-native"; + +import { NativeWorkspaceTabActivityContext } from "../../../native/v5-workspace-context"; /** - * Top-level tabs swap in a single frame. A tab mounts on its first visit and then stays mounted - * while hidden, so returning to it shows its list as it was left instead of an empty one that - * fills in. Hidden tabs keep their state but run no effects, so they register no keyboard - * commands, back handlers, or header options. + * A tab mounts on first visit, then stays a live native view under the shown one, like iOS's + * retained tabs. `display: none` (what `` does) makes Fabric rebuild a pane's views on + * every switch. Code that must act for the shown tab only reads `NativeWorkspaceTabActivityContext`. */ export function WorkspaceTabPanes(props: { readonly tabs: readonly Tab[]; @@ -16,12 +17,19 @@ export function WorkspaceTabPanes(props: { if (!visited.includes(props.selected)) { setVisited([...visited, props.selected]); } - return props.tabs.map((tab) => - visited.includes(tab) ? ( - - - - ) : null, + return ( + + {props.tabs.map((tab) => + visited.includes(tab) ? ( + + ) : null, + )} + ); } @@ -29,7 +37,28 @@ export function WorkspaceTabPanes(props: { // selection change then re-renders only what reads the selection, not every mounted tab. function WorkspaceTabPane(props: { readonly tab: Tab; + readonly active: boolean; readonly renderTab: (tab: Tab) => ReactNode; }) { - return {props.renderTab(props.tab)}; + // Whether this pane is the shown one, read by cleanups after the switch has committed. + const activeRef = useRef(props.active); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed active flag to a ref that cleanups read after the tab switch commits + useLayoutEffect(() => { + activeRef.current = props.active; + }, [props.active]); + const activity = { active: props.active, isActive: () => activeRef.current }; + return ( + + + {props.renderTab(props.tab)} + + + ); } + +const styles = StyleSheet.create({ hidden: { opacity: 0 } }); diff --git a/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts b/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts index 3fe4ba555c3d1..483e70edb5436 100644 --- a/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts +++ b/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts @@ -235,6 +235,7 @@ vi.mock("react-native", () => ({ }, }, Keyboard: { dismiss: () => undefined }, + StyleSheet: { absoluteFill: {}, create: (styles: T) => styles }, useWindowDimensions: () => ({ width: 400, height: 800 }), View: ({ children }: { children: ReactNode }) => createElement("div", null, children), })); diff --git a/apps/mobile/src/lib/backHandler.ts b/apps/mobile/src/lib/backHandler.ts index 57990fa3b88de..26a080ee4052d 100644 --- a/apps/mobile/src/lib/backHandler.ts +++ b/apps/mobile/src/lib/backHandler.ts @@ -1,8 +1,9 @@ import { useIsFocused } from "@react-navigation/native"; -import { useEffect, useEffectEvent } from "react"; +import { use, useEffect, useEffectEvent } from "react"; import { BackHandler } from "react-native"; import { usePaneRole } from "../components/ui/Pane"; +import { NativeWorkspaceTabActivityContext } from "../native/v5-workspace-context"; /** * Android hardware back while `active` and the owning screen is focused. @@ -12,7 +13,9 @@ import { usePaneRole } from "../components/ui/Pane"; export function useHardwareBack(active: boolean, onBack: () => boolean) { // The sidebar's route stays unfocused under the page beside it. const inSidebar = usePaneRole() === "sidebar"; - const focused = useIsFocused() || inSidebar; + // A retained tab stays mounted while another tab is shown. + const tabActive = use(NativeWorkspaceTabActivityContext)?.active ?? true; + const focused = (useIsFocused() || inSidebar) && tabActive; const handleBack = useEffectEvent(onBack); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to BackHandler for the focused screen's lifetime useEffect(() => { From 2747e50222911a2008675285990114ee98dc0870 Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Sun, 29 Nov 2026 01:48:30 +0530 Subject: [PATCH 13/15] perf(mobile): Android list tab taps skip a no-op root stack reset Between list tabs over Home alone the reset changed nothing, but its new navigation state re-rendered every screen that reads focus. --- .../workspace/AndroidWorkspaceNavigation.android.tsx | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/apps/mobile/src/features/layout/workspace/AndroidWorkspaceNavigation.android.tsx b/apps/mobile/src/features/layout/workspace/AndroidWorkspaceNavigation.android.tsx index 6276fcc2ef8c8..d2b4bbfda2557 100644 --- a/apps/mobile/src/features/layout/workspace/AndroidWorkspaceNavigation.android.tsx +++ b/apps/mobile/src/features/layout/workspace/AndroidWorkspaceNavigation.android.tsx @@ -160,7 +160,13 @@ export function AndroidWorkspaceNavigation(props: { // The provider renders inside the root stack's layout, so the container's root state is // that stack's current state. const rootState = rootNavigationRef.getRootState(); - if (root && rootState) { + // Between list tabs over Home alone the reset changes nothing, but its new state object + // still re-renders every screen that reads focus. + const alreadyHome = + tab !== "settings" && + rootState?.routes.length === 1 && + rootState.routes[0]?.name === "Home"; + if (root && rootState && !alreadyHome) { navigation.dispatch({ ...CommonActions.reset( androidWorkspaceTabNavigationState(rootState, tab, layout.usesSplitView), From 76f202bc8b5a5318e3e6727d5fd0d232cb074526 Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Sun, 29 Nov 2026 02:07:57 +0530 Subject: [PATCH 14/15] perf(mobile): hidden Usage and Pulls tabs stop re-rendering on provider updates A retained tab stays mounted while another is shown, and every provider status check rewrote the presentations and server configs those tabs read. They now hold their last values until shown, the Usage minute clock pauses, and the limits auto refresh runs again on each visit. --- .../pull-requests/PullRequestsScreen.tsx | 13 ++++++++++--- .../src/features/usage/UsageLimitsPooled.tsx | 9 +++++++-- .../src/features/usage/UsageLimitsSection.tsx | 17 +++++++++++++---- apps/mobile/src/lib/clock.ts | 12 +++++++++--- 4 files changed, 39 insertions(+), 12 deletions(-) diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx index 6454951bbf55d..63e645324ce85 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx @@ -10,7 +10,6 @@ import { LegendList, type LegendListRef } from "@legendapp/list/react-native"; import { useNavigation } from "@react-navigation/native"; import { useGT } from "gt-react-native"; import { use, useMemo, useRef, useState, type ReactNode } from "react"; -import { useAtomValue } from "@effect/atom-react"; import { Keyboard, Platform, Pressable, View } from "react-native"; import { RefreshControl } from "../../components/ui/RefreshControl"; import { NativeScrollView } from "../../native/NativeScrollViewMarker"; @@ -20,7 +19,11 @@ import { AppText as Text } from "../../components/ui/AppText"; import { useContentTopInset } from "../../components/ui/useBarInset"; import { SymbolView } from "../../components/ui/AppSymbol"; import { EmptyState } from "../../components/ui/EmptyState"; -import { NativePrimaryColumnContext } from "../../native/v5-workspace-context"; +import { + NativePrimaryColumnContext, + NativeWorkspaceTabActivityContext, +} from "../../native/v5-workspace-context"; +import { useAtomValueWhileVisible } from "../home/home-route-visibility"; import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics"; import { useWorkspaceState } from "../../state/workspace"; import { useProjects } from "../../state/entities"; @@ -106,7 +109,11 @@ export function PullRequestsScreen( const workspace = useWorkspaceTabControls()!; const tab = useWorkspaceTabsSelector((state) => state.tabs.pullRequests)!; const { environments } = useWorkspaceState(); - const configs = useAtomValue(environmentServerConfigsAtom); + // Every provider check rewrites the configs; a retained, hidden tab only needs them once shown. + const configs = useAtomValueWhileVisible( + environmentServerConfigsAtom, + use(NativeWorkspaceTabActivityContext)?.active ?? true, + ); const insets = useSafeAreaInsets(); const contentTopInset = useContentTopInset(); // UIKit insets the list by its column's safe area, which this context can report as 0. diff --git a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx index adb1b1e4f7f54..0a7aa604c79ce 100644 --- a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx @@ -19,7 +19,7 @@ import { cursorUsageWindowDetails, } from "@t3tools/shared/usageLimitsCopy"; import { msg, T, useGT, useMessages, Var } from "gt-react-native"; -import { Fragment, type ReactNode, useId, useState } from "react"; +import { Fragment, type ReactNode, use, useId, useState } from "react"; import { Pressable, View } from "react-native"; import { useNowMinuteMs } from "../../lib/clock"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; @@ -33,6 +33,8 @@ import { ProviderIcon } from "../../components/ProviderIcon"; import type { MessageResolver } from "../../i18n/messages"; import { SettingsScreen } from "../settings/components/SettingsScreen"; import { environmentPresentations } from "../../state/presentation"; +import { NativeWorkspaceTabActivityContext } from "../../native/v5-workspace-context"; +import { useAtomValueWhileVisible } from "../home/home-route-visibility"; import { refillLabel, ResetCredits, resetLabels } from "./UsageLimitsSection"; import { usageProviderKind, useProviderColors } from "./usageProviders"; @@ -477,7 +479,10 @@ export function UsageLimitsSection({ readonly selectedEnvironmentIds: ReadonlySet | null; readonly wide?: boolean; }) { - const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom); + const presentations = useAtomValueWhileVisible( + environmentPresentations.presentationsWithProvidersAtom, + use(NativeWorkspaceTabActivityContext)?.active ?? true, + ); const selected = selectedEnvironmentIds === null ? presentations diff --git a/apps/mobile/src/features/usage/UsageLimitsSection.tsx b/apps/mobile/src/features/usage/UsageLimitsSection.tsx index 043ceb7f4ec26..2b3ee8c2df85b 100644 --- a/apps/mobile/src/features/usage/UsageLimitsSection.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsSection.tsx @@ -20,7 +20,7 @@ import { } from "@t3tools/shared/usageLimits"; import { formatDuration, limitsNotice, resetCreditChoices } from "@t3tools/shared/usageLimitsCopy"; import { msg, T, useGT, useMessages, Var } from "gt-react-native"; -import { type ReactNode, useContext, useRef, useState } from "react"; +import { type ReactNode, use, useContext, useRef, useState } from "react"; import { Atom } from "effect/reactivity"; import { Pressable, View } from "react-native"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; @@ -33,6 +33,8 @@ import { serverEnvironment } from "../../state/server"; import { readEnvironmentScope, useEnvironmentScope } from "../../state/session"; import { useAtomCommand } from "../../state/use-atom-command"; import { useNowMinuteMs } from "../../lib/clock"; +import { NativeWorkspaceTabActivityContext } from "../../native/v5-workspace-context"; +import { useAtomValueWhileVisible } from "../home/home-route-visibility"; import { environmentIdsKey, limitsAutoRefreshSetAtom, @@ -336,8 +338,13 @@ export function useRefreshLimits( active = false, ) { const registry = useContext(RegistryContext); - const presentations = useAtomValue(environmentPresentations.presentationsAtom); - const now = useNowMinuteMs(); + // A retained Usage tab stays mounted while another tab is shown; it holds still until shown. + const tabActive = use(NativeWorkspaceTabActivityContext)?.active ?? true; + const presentations = useAtomValueWhileVisible( + environmentPresentations.presentationsAtom, + tabActive, + ); + const now = useNowMinuteMs(tabActive); const [refreshing, setRefreshing] = useState(false); const refreshingRef = useRef(false); const selected = [...presentations].filter( @@ -348,7 +355,9 @@ export function useRefreshLimits( .filter(([, presentation]) => presentation.connection.phase === "connected") .map(([environmentId]) => environmentId); const connectedKey = environmentIdsKey(connectedIds); - useAtomMount(active && connectedKey !== "" ? limitsAutoRefreshSetAtom(connectedKey) : IDLE_ATOM); + useAtomMount( + active && tabActive && connectedKey !== "" ? limitsAutoRefreshSetAtom(connectedKey) : IDLE_ATOM, + ); const failedIds = new Set( useAtomValue(limitsRefreshFailuresAtom(environmentIdsKey(selected.map(([id]) => id)))), ); diff --git a/apps/mobile/src/lib/clock.ts b/apps/mobile/src/lib/clock.ts index 58dc38cfd5f13..4649e5022ca80 100644 --- a/apps/mobile/src/lib/clock.ts +++ b/apps/mobile/src/lib/clock.ts @@ -30,9 +30,15 @@ export function minuteTickToEpochMs(minute: string): number { return Date.parse(`${minute}:00Z`); } -/** Epoch ms floored to the minute, advancing each wall-clock minute. */ -export function useNowMinuteMs(): number { +const holdMinute = () => () => undefined; + +/** Epoch ms floored to the minute, advancing each wall-clock minute while `live`. */ +export function useNowMinuteMs(live = true): number { return minuteTickToEpochMs( - useSyncExternalStore(minuteTick.subscribe, minuteTick.getSnapshot, minuteTick.getSnapshot), + useSyncExternalStore( + live ? minuteTick.subscribe : holdMinute, + minuteTick.getSnapshot, + minuteTick.getSnapshot, + ), ); } From 8b4b30a0cc295196fcc6b2652f5084be53259d4b Mon Sep 17 00:00:00 2001 From: vkpdeveloper Date: Sun, 29 Nov 2026 04:22:15 +0530 Subject: [PATCH 15/15] fix(mobile): Android tab header no longer shows a hidden tab's bar Retained tab panes keep their effects while hidden, and a hidden tab that re-rendered projected its header over the shown one, so Chats could show the Pull requests bar and its search. Only the shown tab now writes the shared bar, and it releases the bar when it hides. --- .../src/components/ui/WorkspaceAppBar.android.tsx | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/components/ui/WorkspaceAppBar.android.tsx b/apps/mobile/src/components/ui/WorkspaceAppBar.android.tsx index 61354bbf3b7a4..46a514bd88a6c 100644 --- a/apps/mobile/src/components/ui/WorkspaceAppBar.android.tsx +++ b/apps/mobile/src/components/ui/WorkspaceAppBar.android.tsx @@ -12,6 +12,7 @@ import { } from "react"; import { Pressable, View } from "react-native"; +import { NativeWorkspaceTabActivityContext } from "../../native/v5-workspace-context"; import { AndroidAnchoredMenu } from "./AndroidAnchoredMenu.android"; import { AndroidHeaderIconButton } from "./AndroidScreenHeader.android"; import { AppText } from "./AppText"; @@ -112,13 +113,17 @@ export function useHasWorkspaceAppBar() { export function WorkspaceAppBar(props: WorkspaceAppBarProps) { const store = use(WorkspaceAppBarStoreContext); const [owner] = useState(() => ({})); + // A retained tab stays mounted while hidden and still re-renders, so only the shown tab writes. + const tabActive = use(NativeWorkspaceTabActivityContext)?.active ?? true; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- projects this tab's header into the out-of-tree workspace bar after every commit useLayoutEffect(() => { - store?.set(owner, props); + if (tabActive) store?.set(owner, props); }); - // Hidden panes destroy their effects, so the tab leaving the screen releases the bar. // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- releases the workspace bar when this tab hides or unmounts - useLayoutEffect(() => (store ? () => store.clear(owner) : undefined), [store, owner]); + useLayoutEffect( + () => (store && tabActive ? () => store.clear(owner) : undefined), + [store, owner, tabActive], + ); return store ? null : ; }