The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 14:30 UTC
refactor(mobile): workspace tabs, home filters and connection status derive instead of syncing (#25813)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 27, 2026 at 04:22 UTC
79f6cd30c7ed4772d5989d08ce26f64f161dfe49
8 files changed
+176
-125
apps/mobile/src/features/home/WorkspaceConnectionTitle.tsx
+17
-22
@@ -1,5 +1,5 @@
1
import type { NativeStackNavigationOptions } from "@react-navigation/native-stack";
2
-import { createContext, use, useEffect, useMemo, useState, type ReactNode } from "react";
2
+import { createContext, use, useEffect, useState, type ReactNode } from "react";
3
import { Animated, Platform, Pressable, View } from "react-native";
4
5
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
@@ -11,6 +11,7 @@ import {
11
CompactBrandTitle,
12
getCompactBrandHeaderOptions,
13
} from "../../components/CompactBrandTitle";
14
+import { useDeadlinePassed } from "../../lib/clock";
15
import { useWorkspaceState } from "../../state/workspace";
16
import {
17
workspaceConnectionStatusPresentation,
@@ -37,29 +38,24 @@ export function WorkspaceConnectionStatusProvider(props: { readonly children: Re
38
const { state } = useWorkspaceState();
39
const presentation = workspaceConnectionStatusPresentation(state);
40
const hasStatus = presentation !== null;
40
- const [phase, setPhase] = useState<"waiting" | "fading" | "shown">("waiting");
41
-
42
- useEffect(() => {
43
- if (!hasStatus) return;
44
- const timers = [
45
- setTimeout(() => setPhase("fading"), STATUS_SHOW_DELAY_MS),
46
- setTimeout(() => setPhase("shown"), STATUS_SHOW_DELAY_MS + FADE_IN_MS),
47
- ];
48
- return () => {
49
- for (const timer of timers) clearTimeout(timer);
50
- setPhase("waiting");
51
- };
52
- }, [hasStatus]);
41
+ // When the current status run began; a gap in the status restarts the delay.
42
+ const [statusSince, setStatusSince] = useState(() => (hasStatus ? Date.now() : null));
43
+ if (hasStatus !== (statusSince !== null)) {
44
+ // oxlint-disable-next-line react/purity -- Reads the clock only in the render-phase adjustment that runs when the status appears.
45
+ setStatusSince(hasStatus ? Date.now() : null);
46
+ }
47
+ const since = hasStatus ? statusSince : null;
48
+ const fadeStarted = useDeadlinePassed(since === null ? null : since + STATUS_SHOW_DELAY_MS);
49
+ const fadeEnded = useDeadlinePassed(
50
+ since === null ? null : since + STATUS_SHOW_DELAY_MS + FADE_IN_MS,
51
+ );
52
53
const label = presentation?.label;
54
const showsProgress = presentation?.showsProgress ?? false;
56
- const status = useMemo(
57
- () =>
58
- label === undefined || phase === "waiting"
59
- ? null
60
- : { label, showsProgress, fadeIn: phase === "fading" },
61
- [label, showsProgress, phase],
62
- );
55
+ const status =
56
+ label === undefined || since === null || !fadeStarted
57
+ ? null
58
+ : { label, showsProgress, fadeIn: !fadeEnded };
59
return <ConnectionStatusContext value={status}>{props.children}</ConnectionStatusContext>;
60
}
61
@@ -72,7 +68,6 @@ function StatusFadeIn(props: {
68
}) {
69
const { animate } = props;
70
const [opacity] = useState(() => new Animated.Value(0));
75
-
71
useEffect(() => {
72
if (!animate) return;
73
const animation = Animated.timing(opacity, {
apps/mobile/src/features/home/home-list-options.test.tsx
new
+49
@@ -0,0 +1,49 @@
1
+import type { EnvironmentId } from "@t3tools/contracts";
2
+import { act, useLayoutEffect } from "react";
3
+import { createRoot } from "react-dom/client";
4
+import { expect, it, vi } from "vite-plus/test";
5
+
6
+const harness = vi.hoisted(() => ({ saved: [] as unknown[] }));
7
+
8
+vi.mock("../../state/preferences", () => ({ updateMobilePreferencesAtom: {} }));
9
+vi.mock("@effect/atom-react", async (importOriginal) => ({
10
+ ...(await importOriginal<typeof import("@effect/atom-react")>()),
11
+ useAtomSet: () => (value: unknown) => harness.saved.push(value),
12
+}));
13
+
14
+import { HomeListOptionsProvider, useHomeListOptions } from "./home-list-options";
15
+
16
+const ENVIRONMENT = "env-1" as EnvironmentId;
17
+const AVAILABLE = new Set([ENVIRONMENT]);
18
+
19
+it("saves the scope from every update made in one event", async () => {
20
+ harness.saved = [];
21
+ let controls: ReturnType<typeof useHomeListOptions> | undefined;
22
+ function Probe() {
23
+ const result = useHomeListOptions(AVAILABLE);
24
+ useLayoutEffect(() => {
25
+ controls = result;
26
+ });
27
+ return null;
28
+ }
29
+
30
+ const root = createRoot(document.createElement("div"));
31
+ await act(async () =>
32
+ root.render(
33
+ <HomeListOptionsProvider projectGroupingMode="repository">
34
+ <Probe />
35
+ </HomeListOptionsProvider>,
36
+ ),
37
+ );
38
+ act(() => {
39
+ controls!.setSelectedEnvironmentId(ENVIRONMENT);
40
+ controls!.setSelectedProjectKey("env-1:project-1");
41
+ });
42
+
43
+ expect(harness.saved.at(-1)).toEqual({
44
+ threadListFilters: { environmentId: ENVIRONMENT, projectKey: "env-1:project-1" },
45
+ });
46
+ expect(controls!.options.selectedEnvironmentId).toBe(ENVIRONMENT);
47
+ expect(controls!.options.selectedProjectKey).toBe("env-1:project-1");
48
+ act(() => root.unmount());
49
+});
apps/mobile/src/features/home/home-list-options.ts
+31
-29
@@ -1,17 +1,8 @@
1
import type { EnvironmentId, SidebarProjectGroupingMode } from "@t3tools/contracts";
2
import { DEFAULT_SIDEBAR_PROJECT_SORT_ORDER } from "@t3tools/contracts";
3
-import { useAtomSet } from "@effect/atom-react";
4
-import {
5
- createContext,
6
- createElement,
7
- useContext,
8
- useEffect,
9
- useRef,
10
- useState,
11
- type PropsWithChildren,
12
- type Dispatch,
13
- type SetStateAction,
14
-} from "react";
3
+import { RegistryContext, useAtomSet, useAtomValue } from "@effect/atom-react";
4
+import { Atom } from "effect/reactivity";
5
+import { createContext, createElement, useContext, useState, type PropsWithChildren } from "react";
6
7
import type { ThreadListFilters } from "../../persistence/mobile-preferences";
8
import { updateMobilePreferencesAtom } from "../../state/preferences";
@@ -40,7 +31,7 @@ function defaultHomeListOptions(filters?: ThreadListFilters): HomeListOptions {
31
32
interface HomeListOptionsContextValue {
33
readonly options: HomeListOptions;
43
- readonly setOptions: Dispatch<SetStateAction<HomeListOptions>>;
34
+ readonly updateOptions: (patch: Partial<HomeListOptions>) => void;
35
readonly projectGroupingMode: SidebarProjectGroupingMode;
36
}
37
@@ -54,20 +45,29 @@ export function HomeListOptionsProvider({
45
readonly projectGroupingMode: SidebarProjectGroupingMode;
46
readonly savedFilters?: ThreadListFilters | undefined;
47
}>) {
57
- const [options, setOptions] = useState(() => defaultHomeListOptions(savedFilters));
48
+ const registry = useContext(RegistryContext);
49
+ const [optionsAtom] = useState(() => Atom.make(defaultHomeListOptions(savedFilters)));
50
+ const options = useAtomValue(optionsAtom);
51
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
59
- const saved = useRef(savedFilters);
60
- const { selectedEnvironmentId: environmentId, selectedProjectKey: projectKey } = options;
61
- useEffect(() => {
52
+ // Only the scope persists; the sort order is per session. Updates read the
53
+ // registry, so several in one event each build on the last and save it.
54
+ const updateOptions = (patch: Partial<HomeListOptions>) => {
55
+ const current = registry.get(optionsAtom);
56
+ const next = { ...current, ...patch };
57
+ registry.set(optionsAtom, next);
58
if (
63
- (saved.current?.environmentId ?? null) === environmentId &&
64
- (saved.current?.projectKey ?? null) === projectKey
65
- )
66
- return;
67
- saved.current = { environmentId, projectKey };
68
- savePreferences({ threadListFilters: saved.current });
69
- }, [environmentId, projectKey, savePreferences]);
70
- const value = { options, setOptions, projectGroupingMode };
59
+ next.selectedEnvironmentId !== current.selectedEnvironmentId ||
60
+ next.selectedProjectKey !== current.selectedProjectKey
61
+ ) {
62
+ savePreferences({
63
+ threadListFilters: {
64
+ environmentId: next.selectedEnvironmentId,
65
+ projectKey: next.selectedProjectKey,
66
+ },
67
+ });
68
+ }
69
+ };
70
+ const value = { options, updateOptions, projectGroupingMode };
71
return createElement(HomeListOptionsContext, { value }, children);
72
}
73
@@ -75,7 +75,9 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environm
75
const shared = useContext(HomeListOptionsContext);
76
const [localOptions, setLocalOptions] = useState<HomeListOptions>(defaultHomeListOptions);
77
const options = shared?.options ?? localOptions;
78
- const setOptions = shared?.setOptions ?? setLocalOptions;
78
+ const updateOptions =
79
+ shared?.updateOptions ??
80
+ ((patch: Partial<HomeListOptions>) => setLocalOptions((current) => ({ ...current, ...patch })));
81
const selectedEnvironmentId =
82
options.selectedEnvironmentId !== null &&
83
availableEnvironmentIds.has(options.selectedEnvironmentId)
@@ -91,13 +93,13 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environm
93
};
94
95
const setSelectedEnvironmentId = (value: EnvironmentId | null) => {
94
- setOptions((current) => ({ ...current, selectedEnvironmentId: value }));
96
+ updateOptions({ selectedEnvironmentId: value });
97
};
98
const setSelectedProjectKey = (value: string | null) => {
97
- setOptions((current) => ({ ...current, selectedProjectKey: value }));
99
+ updateOptions({ selectedProjectKey: value });
100
};
101
const setProjectSortOrder = (value: HomeProjectSortOrder) => {
100
- setOptions((current) => ({ ...current, projectSortOrder: value }));
102
+ updateOptions({ projectSortOrder: value });
103
};
104
return {
105
options: resolvedOptions,
apps/mobile/src/features/workspace/AndroidWorkspaceNavigation.android.tsx
+6
-4
@@ -13,6 +13,7 @@ import { useKeyboardState } from "react-native-keyboard-controller";
13
14
import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";
15
import { useToolbarLayout } from "../../components/ui/useToolbarLayout";
16
+import { rootNavigationRef } from "../../lib/rootNavigation";
17
import { useWorkspaceConnectionState } from "../../state/workspace";
18
import { androidWorkspaceNavigationColors } from "./android-workspace-navigation-colors";
19
import {
@@ -116,11 +117,12 @@ export function AndroidWorkspaceNavigation(props: {
117
const tab = event.nativeEvent.tab;
118
if (tab !== "settings") workspace.dispatch({ type: "select", tab });
119
// Reset the root stack even when a nested settings navigator has focus.
119
- if (root) {
120
+ // The provider renders inside the root stack's layout, so the container's root state is
121
+ // that stack's current state.
122
+ const rootState = rootNavigationRef.getRootState();
123
+ if (root && rootState) {
124
navigation.dispatch({
121
- ...CommonActions.reset(
122
- androidWorkspaceTabNavigationState(root.getState(), tab, rail),
123
- ),
125
+ ...CommonActions.reset(androidWorkspaceTabNavigationState(rootState, tab, rail)),
126
target: root.key,
127
});
128
}
apps/mobile/src/features/workspace/AndroidWorkspaceTabsProvider.tsx
+3
-20
@@ -1,13 +1,5 @@
1
import type { NavigationState } from "@react-navigation/native";
2
-import {
3
- createContext,
4
- use,
5
- useCallback,
6
- useLayoutEffect,
7
- useMemo,
8
- useRef,
9
- type ReactNode,
10
-} from "react";
2
+import { createContext, use, type ReactNode } from "react";
3
import { Platform } from "react-native";
4
import { androidWorkspaceSettingsOpen } from "./android-workspace-tabs";
5
import { WorkspaceTabsProvider } from "./WorkspaceTabsContext";
@@ -15,10 +7,9 @@ import { WorkspaceTabsProvider } from "./WorkspaceTabsContext";
7
interface AndroidWorkspaceRoot {
8
/**
9
* The rail's `useNavigation()` dispatches to the focused navigator, which may be nested Settings.
18
- * Use the root stack's state and key so a tab press resets the root.
10
+ * Target the root stack's key (and read `rootNavigationRef`'s state) so a tab press resets the root.
11
*/
12
readonly key: string;
21
- readonly getState: () => NavigationState;
13
/** Settings is derived from navigation rather than kept in the tab reducer. */
14
readonly settingsOpen: boolean;
15
readonly settingsRoute: NavigationState["routes"][number] | undefined;
@@ -36,21 +27,13 @@ export function AndroidWorkspaceTabsProvider(props: {
27
readonly state: NavigationState;
28
readonly children: ReactNode;
29
}) {
39
- const stateRef = useRef(props.state);
40
- useLayoutEffect(() => {
41
- stateRef.current = props.state;
42
- }, [props.state]);
43
- const getState = useCallback(() => stateRef.current, []);
30
const key = props.state.key;
31
const settingsOpen = Platform.OS === "android" && androidWorkspaceSettingsOpen(props.state);
32
const settingsIndex = props.state.routes.findIndex((route) => route.name === "Settings");
33
const settingsRoute = settingsIndex < 0 ? undefined : props.state.routes[settingsIndex];
34
const settingsPage =
35
settingsIndex < 0 ? null : (props.state.routes[settingsIndex + 1]?.name ?? null);
50
- const root = useMemo(
51
- () => ({ key, getState, settingsOpen, settingsRoute, settingsPage }),
52
- [key, getState, settingsOpen, settingsRoute, settingsPage],
53
- );
36
+ const root = { key, settingsOpen, settingsRoute, settingsPage };
37
return Platform.OS === "android" ? (
38
<WorkspaceTabsProvider>
39
<AndroidWorkspaceRootContext value={root}>{props.children}</AndroidWorkspaceRootContext>
apps/mobile/src/features/workspace/WorkspaceTabsContext.tsx
+63
-39
@@ -1,18 +1,16 @@
1
-import { resolveSelectedNavigationTab } from "./navigation-tab-order";
2
-import { useNavigationTabOrder, useHiddenNavigationTabs } from "./navigation-tabs";
1
+import { RegistryContext, useAtomValue } from "@effect/atom-react";
2
+import { AsyncResult, Atom } from "effect/reactivity";
3
+import { createContext, use, useState, type Dispatch, type ReactNode } from "react";
4
+
5
+import { mobilePreferencesAtom } from "../../state/preferences";
6
import {
4
- createContext,
5
- use,
6
- useCallback,
7
- useLayoutEffect,
8
- useMemo,
9
- useReducer,
10
- useRef,
11
- type Dispatch,
12
- type ReactNode,
13
-} from "react";
7
+ navigationCustomizationAvailable,
8
+ resolveHiddenNavigationTabs,
9
+ resolveSelectedNavigationTab,
10
+} from "./navigation-tab-order";
11
import {
12
initialWorkspaceTabsState,
13
+ resolveWorkspaceTabOrder,
14
workspaceTabsReducer,
15
type WorkspaceSearchTab,
16
type WorkspaceTab,
@@ -34,36 +32,62 @@ export function useWorkspaceTabs() {
32
return use(WorkspaceTabsContext);
33
}
34
35
+type MobilePreferencesResult = Atom.Type<typeof mobilePreferencesAtom>;
36
+
37
+/** Moves the selection off a tab the user has hidden or that no longer exists. */
38
+function resolveWorkspaceTabsSelection(
39
+ state: WorkspaceTabsState,
40
+ preferences: MobilePreferencesResult,
41
+): WorkspaceTabsState {
42
+ const saved = AsyncResult.isSuccess(preferences) ? preferences.value : undefined;
43
+ const order = resolveWorkspaceTabOrder(saved?.navigationTabOrder);
44
+ const hidden = navigationCustomizationAvailable()
45
+ ? resolveHiddenNavigationTabs(saved?.hiddenNavigationTabs)
46
+ : [];
47
+ const selected = resolveSelectedNavigationTab(order, hidden, state.selectedTab);
48
+ return selected && selected !== state.selectedTab
49
+ ? workspaceTabsReducer(state, { type: "select", tab: selected })
50
+ : state;
51
+}
52
+
53
+// One model per provider. Handlers on frozen screens keep stale closures, so
54
+// they read the current selection from the registry at call time.
55
+function createWorkspaceTabsModel() {
56
+ const stored = Atom.make(initialWorkspaceTabsState());
57
+ const scrollOffsets: Record<WorkspaceSearchTab, number> = {
58
+ threads: 0,
59
+ pullRequests: 0,
60
+ usage: 0,
61
+ settings: 0,
62
+ };
63
+ return {
64
+ stored,
65
+ resolved: Atom.make((get) =>
66
+ resolveWorkspaceTabsSelection(get(stored), get(mobilePreferencesAtom)),
67
+ ),
68
+ getScrollOffset: (tab: WorkspaceSearchTab) => scrollOffsets[tab],
69
+ recordScrollOffset: (tab: WorkspaceSearchTab, offset: number) => {
70
+ scrollOffsets[tab] = offset;
71
+ },
72
+ };
73
+}
74
+
75
export function WorkspaceTabsProvider(props: {
76
readonly children: ReactNode;
77
readonly settingsOpen?: boolean;
78
}) {
41
- const [state, dispatch] = useReducer(workspaceTabsReducer, undefined, initialWorkspaceTabsState);
42
- const order = useNavigationTabOrder();
43
- const hidden = useHiddenNavigationTabs();
44
- const selected = resolveSelectedNavigationTab(order, hidden, state.selectedTab);
45
- if (selected && selected !== state.selectedTab) dispatch({ type: "select", tab: selected });
46
- const activeTab = useRef(state.selectedTab);
47
- useLayoutEffect(() => {
48
- activeTab.current = state.selectedTab;
49
- }, [state.selectedTab]);
50
- const isTabActive = useCallback((tab: WorkspaceTab) => activeTab.current === tab, []);
51
- const scrollOffsets = useRef({ threads: 0, pullRequests: 0, usage: 0, settings: 0 });
52
- const getScrollOffset = useCallback((tab: WorkspaceSearchTab) => scrollOffsets.current[tab], []);
53
- const recordScrollOffset = useCallback((tab: WorkspaceSearchTab, offset: number) => {
54
- scrollOffsets.current[tab] = offset;
55
- }, []);
56
- const context = useMemo(
57
- () => ({
58
- state,
59
- dispatch,
60
- isTabActive,
61
- bottomClearance: 0,
62
- settingsOpen: props.settingsOpen ?? false,
63
- getScrollOffset,
64
- recordScrollOffset,
65
- }),
66
- [state, isTabActive, getScrollOffset, recordScrollOffset, props.settingsOpen],
67
- );
79
+ const registry = use(RegistryContext);
80
+ const [model] = useState(createWorkspaceTabsModel);
81
+ const state = useAtomValue(model.resolved);
82
+ const context = {
83
+ state,
84
+ dispatch: (action: WorkspaceTabsAction) =>
85
+ registry.set(model.stored, workspaceTabsReducer(registry.get(model.resolved), action)),
86
+ isTabActive: (tab: WorkspaceTab) => registry.get(model.resolved).selectedTab === tab,
87
+ bottomClearance: 0,
88
+ settingsOpen: props.settingsOpen ?? false,
89
+ getScrollOffset: model.getScrollOffset,
90
+ recordScrollOffset: model.recordScrollOffset,
91
+ };
92
return <WorkspaceTabsContext value={context}>{props.children}</WorkspaceTabsContext>;
93
}
apps/mobile/src/features/workspace/WorkspaceToolbar.tsx
+6
-11
@@ -1,9 +1,7 @@
1
import { useFocusEffect } from "@react-navigation/native";
2
-import { useCallback, useEffect, useEffectEvent, useRef, useState } from "react";
2
+import { useCallback, useEffect, useRef, useState } from "react";
3
import {
4
- BackHandler,
4
Keyboard,
6
- Platform,
5
Pressable,
6
View,
7
useWindowDimensions,
@@ -14,6 +12,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
12
13
import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
14
import { GlassSurface } from "../../components/ui/GlassSurface";
15
+import { useHardwareBack } from "../../lib/backHandler";
16
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
17
import { WorkspaceDock } from "./WorkspaceDock";
18
import { WorkspaceSearchField } from "./WorkspaceSearchField";
@@ -79,18 +78,14 @@ export function WorkspaceToolbar(props: {
78
);
79
workspace?.dispatch({ type: "cancel" });
80
}, [workspace]);
82
- const handleBack = useEffectEvent(() => {
83
- if (!workspace || workspace.state.tabs[workspace.state.selectedTab].searchMode === "resting")
84
- return false;
81
+ const searchOpen =
82
+ workspace !== null &&
83
+ workspace.state.tabs[workspace.state.selectedTab].searchMode !== "resting";
84
+ useHardwareBack(searchOpen, () => {
85
if (keyboardVisible) Keyboard.dismiss();
86
else cancelSearch();
87
return true;
88
});
89
- useEffect(() => {
90
- if (Platform.OS !== "android") return;
91
- const subscription = BackHandler.addEventListener("hardwareBackPress", handleBack);
92
- return () => subscription.remove();
93
- }, []);
89
useEffect(() => {
90
if (focusRequest > 0) input.current?.focus();
91
}, [focusRequest]);
apps/mobile/vite.config.ts
+1
@@ -26,6 +26,7 @@ const reactTests = [
26
"src/state/use-selected-thread-git-actions.test.tsx",
27
"src/features/terminal/useTerminalExitNavigation.test.tsx",
28
"src/features/threads/use-thread-list-now.test.tsx",
29
+ "src/features/home/home-list-options.test.tsx",
30
];
31
32
const sourceRoot = `${normalizePath(NodeURL.fileURLToPath(new URL("./src", import.meta.url)))}/`;