TypeScript
fix(mobile): one way to select a page, so split view stops pushing (#24742)
Julius Marminge8c0670b2be8e
diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsxindex 1d5b2cdd570..8b444aa08f4 100644--- a/apps/mobile/src/App.tsx+++ b/apps/mobile/src/App.tsx@@ -6,7 +6,12 @@ import { StatusBar } from "react-native";import { GestureHandlerRootView } from "react-native-gesture-handler";import { KeyboardProvider } from "react-native-keyboard-controller";import { SafeAreaProvider } from "react-native-safe-area-context";-import { createStaticNavigation, getStateFromPath } from "@react-navigation/native";+import {+ createNavigationContainerRef,+ createStaticNavigation,+ getActionFromState,+ getStateFromPath,+} from "@react-navigation/native";import { RegistryContext } from "@effect/atom-react";import { ProjectChipIconRasterizer } from "./native/ProjectChipIconImages";@@ -38,6 +43,7 @@ import {recordWorkspaceSelections,settingsLinkPage,} from "./features/workspace/workspace-selection-store";+import { workspaceDetailLinkAction } from "./features/workspace/workspace-detail-selection";import { NativeLayoutMetricsProvider } from "./native/native-layout-metrics";import "../global.css";@@ -54,6 +60,13 @@ const appLinking = {config: { initialRouteName: "Home" },filter: shouldHandleAppLink,getInitialURL: async () => (await Linking.getInitialURL()) ?? (await launchWorkspaceURL()),+ getActionFromState: (+ state: Parameters<typeof getActionFromState>[0],+ options: Parameters<typeof getActionFromState>[1],+ ): ReturnType<typeof getActionFromState> =>+ // Our router handles the selection; React Navigation's type only lists its own actions.+ (workspaceDetailLinkAction(state) as ReturnType<typeof getActionFromState>) ??+ getActionFromState(state, options),getStateFromPath: (path: string, options: Parameters<typeof getStateFromPath>[1]) =>restoreSettingsLinkState(restoreDraftLinkState(getStateFromPath(path, options), path),@@ -62,6 +75,7 @@ const appLinking = {};const Navigation = createStaticNavigation(RootStack);+const navigationRef = createNavigationContainerRef();function SplashScreenCoordinator() {const { isReady } = useAppearancePreferences();@@ -116,7 +130,9 @@ function AppContent() {<NativeLayoutMetricsProvider><IncomingShareProvider><Navigation+ ref={navigationRef}linking={appLinking}+ onReady={() => recordWorkspaceSelections(navigationRef.getRootState())}theme={navigationTheme}onStateChange={recordWorkspaceSelections}/>diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsxindex fad15278907..8a07f8b7a08 100644--- a/apps/mobile/src/Stack.tsx+++ b/apps/mobile/src/Stack.tsx@@ -149,6 +149,10 @@ import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";import { HORIZONTAL_FORM_SHEET_OPTIONS, formSheetDetents } from "./native/sheet-surface";import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";import { useComposerAttachmentUploadWorker } from "./state/composer-attachment-uploads";+import {+ selectWorkspaceDetail,+ workspaceDetailRouter,+} from "./features/workspace/workspace-detail-selection";const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);@@ -525,7 +529,12 @@ function RootStackLayout(props: {if (!transition.shareIdToPresent) {return;}- navigation.navigate("Thread", { draft: { incomingShareId: transition.shareIdToPresent } });+ navigation.dispatch(+ selectWorkspaceDetail({+ name: "Thread",+ params: { draft: { incomingShareId: transition.shareIdToPresent } },+ }),+ );}, [navigation, pendingShare, props.state]);return (@@ -599,6 +608,7 @@ function NotFoundScreen() {const RootStackConfig = createWorkspaceStackNavigator({initialRouteName: "Home",+ UNSTABLE_router: workspaceDetailRouter,// React Navigation calls layouts inline; compiled components would share the navigator's memo cache.layout: (props) => <RootStackLayout {...props} />,screenOptions: {diff --git a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsxindex 9ef668a9fa1..7df96335579 100644--- a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx+++ b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx@@ -22,7 +22,6 @@ import { AudioFilePreview } from "./AudioFilePreview";import { EmptyState } from "../../components/ui/EmptyState";import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";import { LoadingScreen } from "../../components/LoadingScreen";-import { resolveFileSelectionNavigationAction } from "../../lib/adaptive-navigation";import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";import { isPdfFile } from "../../lib/filePreview";import { tryOpenExternalUrl } from "../../lib/openExternalUrl";@@ -478,10 +477,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {navigation.navigate("NewTaskFile", params);return;}- const navigationAction = resolveFileSelectionNavigationAction({- hasPersistentFileInspector: hasFileInspector,- });- if (navigationAction === "replace") {+ if (hasFileInspector) {navigation.dispatch(StackActions.replace("ThreadFile", params));return;}diff --git a/apps/mobile/src/features/home/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsxindex d6f5262b255..5756a140e77 100644--- a/apps/mobile/src/features/home/HomeRouteScreen.tsx+++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx@@ -28,7 +28,6 @@ import { HomeScreen } from "./HomeScreen";import { HomeHeader } from "./HomeHeader";import { useHomeListOptions } from "./home-list-options";import { useAtomValueWhileVisible, useHomeRouteVisible } from "./home-route-visibility";-import { useHomeThreadRouteSelection, useHomeThreadSelection } from "./home-thread-navigation";import { buildHomeProjectScopes } from "./homeThreadList";import { usePendingTaskListActions } from "./usePendingTaskListActions";import { useThreadListActions } from "./useThreadListActions";@@ -36,6 +35,7 @@ import { getConnectionAwareBrandHeaderOptions } from "./WorkspaceConnectionTitleimport { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";import { openSettings } from "../settings/settings-navigation";import { useSelectWorkspaceTab } from "../workspace/useSelectWorkspaceTab";+import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";export function HomeRouteScreen() {const { width: windowWidth } = useWindowDimensions();@@ -45,6 +45,7 @@ export function HomeRouteScreen() {const headerWidth = nativePrimaryColumn ? (columnMetrics?.width ?? windowWidth) : windowWidth;const { layout, panes, primarySidebarSearchQuery, setPrimarySidebarSearchQuery, startNewTask } =useAdaptiveWorkspaceLayout();+ const selectDetail = useSelectWorkspaceDetail();const projects = useProjects();// Stop rebuilding the streaming thread list while Thread covers Home.const visible = useHomeRouteVisible();@@ -67,8 +68,18 @@ export function HomeRouteScreen() {else if (workspace) workspace.dispatch({ type: "query", query, tab: "threads" });else setLocalSearchQuery(query);};- const handleSelectThread = useHomeThreadSelection();- const selectThreadRoute = useHomeThreadRouteSelection();+ const handleSelectThread = useCallback(+ (thread: EnvironmentThreadShell) =>+ selectDetail({+ name: "Thread",+ params: { environmentId: String(thread.environmentId), threadId: String(thread.id) },+ }),+ [selectDetail],+ );+ const selectThreadRoute = useCallback(+ (params: ReactNavigation.RootParamList["Thread"]) => selectDetail({ name: "Thread", params }),+ [selectDetail],+ );const handleNewThreadOnBranch = useCallback((thread: EnvironmentThreadShell) => {selectThreadRoute({@@ -104,7 +115,8 @@ export function HomeRouteScreen() {unsettleThread,} = useThreadListActions();const pendingTasks = usePendingNewTasks();- const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();+ const { openPendingTask, confirmDeletePendingTask } =+ usePendingTaskListActions(selectThreadRoute);const environments = useMemo(() => {const connectionStateByEnvironmentId = new Map(workspaceEnvironments.map(diff --git a/apps/mobile/src/features/home/home-thread-navigation.test.ts b/apps/mobile/src/features/home/home-thread-navigation.test.tsdeleted file mode 100644index d02d602767a..00000000000--- a/apps/mobile/src/features/home/home-thread-navigation.test.ts+++ /dev/null@@ -1,238 +0,0 @@-import * as NodeModule from "node:module";-import type {- StackNavigationState,- StackRouter as StackRouterType,- StackActions as StackActionsType,-} from "@react-navigation/native";-import { describe, expect, it, vi } from "vite-plus/test";--function loadRouters() {- const require = NodeModule.createRequire(import.meta.url);- const nativePackage = require.resolve("@react-navigation/native/package.json");- const requireFromNative = NodeModule.createRequire(nativePackage);- const corePackage = requireFromNative.resolve("@react-navigation/core/package.json");- const requireFromCore = NodeModule.createRequire(corePackage);- return requireFromCore("@react-navigation/routers") as {- readonly CommonActions: typeof import("@react-navigation/native").CommonActions;- readonly StackActions: typeof StackActionsType;- readonly StackRouter: typeof StackRouterType;- };-}--vi.mock("react-native", () => ({ Platform: { OS: "ios" }, Keyboard: { dismiss: vi.fn() } }));--vi.mock("../workspace/useAndroidWorkspaceSelection", () => ({- useAndroidWorkspaceSelection: vi.fn(),-}));--vi.mock("@react-navigation/native", () => {- const { CommonActions, StackActions } = loadRouters();- return { CommonActions, StackActions };-});--import {- createHomeThreadRouteAction,- createHomeThreadNavigationAction,-} from "./home-thread-navigation";--const { StackActions, StackRouter } = loadRouters();-const routeNames = ["Home", "Thread"];-const routeParamList = {- Home: undefined,- Thread: undefined,-};-const router = StackRouter({});-const routerOptions = {- routeNames,- routeParamList,- routeGetIdList: {},-};--type ThreadSelection = Parameters<typeof createHomeThreadNavigationAction>[0]["thread"];--function thread(id: string): ThreadSelection {- return {- environmentId: "environment-1",- id,- } as ThreadSelection;-}--function initialState() {- return router.getInitialState(routerOptions);-}--function apply(- state: StackNavigationState<Record<string, object | undefined>>,- action: Parameters<typeof router.getStateForAction>[1],-) {- const nextState = router.getStateForAction(state, action, routerOptions);- expect(nextState).not.toBeNull();- return nextState as StackNavigationState<Record<string, object | undefined>>;-}--function selectThread(- state: ReturnType<typeof initialState>,- selectedThread: ThreadSelection,- dismissingRouteKey: string | null = null,-) {- return apply(- state,- createHomeThreadNavigationAction({- state,- dismissingRouteKey,- thread: selectedThread,- }),- );-}--function dismissRoute(state: ReturnType<typeof initialState>, routeKey: string) {- return apply(state, {- ...StackActions.pop(),- source: routeKey,- target: state.key,- });-}--describe("createHomeThreadNavigationAction", () => {- it("coalesces ordinary repeat selections onto the current thread route", () => {- const firstState = selectThread(initialState(), thread("thread-a"));- const threadRouteKey = firstState.routes[firstState.index]?.key;- const secondAction = createHomeThreadNavigationAction({- state: firstState,- dismissingRouteKey: null,- thread: thread("thread-b"),- });-- const secondState = apply(firstState, secondAction);- expect(secondState.routes).toHaveLength(2);- expect(secondState.routes[secondState.index]).toMatchObject({- key: threadRouteKey,- name: "Thread",- params: { environmentId: "environment-1", threadId: "thread-b" },- });- });-- it("keeps an overlap selection after native dismisses the outgoing route", () => {- const outgoingState = selectThread(initialState(), thread("thread-a"));- const outgoingRouteKey = outgoingState.routes[outgoingState.index]?.key;- expect(outgoingRouteKey).toBeDefined();-- const overlapAction = createHomeThreadNavigationAction({- state: outgoingState,- dismissingRouteKey: outgoingRouteKey ?? null,- thread: thread("thread-b"),- });- const overlapState = apply(outgoingState, overlapAction);- const incomingRoute = overlapState.routes[overlapState.index];- expect(incomingRoute?.key).not.toBe(outgoingRouteKey);-- const dismissedState = dismissRoute(overlapState, outgoingRouteKey!);- expect(dismissedState.routes).toHaveLength(2);- expect(dismissedState.routes[dismissedState.index]).toMatchObject({- key: incomingRoute?.key,- name: "Thread",- params: { environmentId: "environment-1", threadId: "thread-b" },- });- });-- it("uses a fresh key for the same thread selected during dismissal", () => {- const outgoingState = selectThread(initialState(), thread("thread-a"));- const outgoingRouteKey = outgoingState.routes[outgoingState.index]?.key;- expect(outgoingRouteKey).toBeDefined();-- const overlapState = selectThread(outgoingState, thread("thread-a"), outgoingRouteKey ?? null);- const incomingRouteKey = overlapState.routes[overlapState.index]?.key;- expect(incomingRouteKey).not.toBe(outgoingRouteKey);-- const dismissedState = dismissRoute(overlapState, outgoingRouteKey!);- expect(dismissedState.routes[dismissedState.index]).toMatchObject({- key: incomingRouteKey,- params: { environmentId: "environment-1", threadId: "thread-a" },- });- });-- it("coalesces a second overlap selection onto the fresh incoming route", () => {- const outgoingState = selectThread(initialState(), thread("thread-a"));- const outgoingRouteKey = outgoingState.routes[outgoingState.index]?.key;- expect(outgoingRouteKey).toBeDefined();-- const firstOverlapState = selectThread(- outgoingState,- thread("thread-b"),- outgoingRouteKey ?? null,- );- const incomingRouteKey = firstOverlapState.routes[firstOverlapState.index]?.key;- const secondOverlapAction = createHomeThreadNavigationAction({- state: firstOverlapState,- dismissingRouteKey: outgoingRouteKey ?? null,- thread: thread("thread-c"),- });-- const secondOverlapState = apply(firstOverlapState, secondOverlapAction);- expect(secondOverlapState.routes).toHaveLength(3);- expect(secondOverlapState.routes[secondOverlapState.index]).toMatchObject({- key: incomingRouteKey,- params: { environmentId: "environment-1", threadId: "thread-c" },- });-- const dismissedState = dismissRoute(secondOverlapState, outgoingRouteKey!);- expect(dismissedState.routes).toHaveLength(2);- expect(dismissedState.routes[dismissedState.index]).toMatchObject({- key: incomingRouteKey,- params: { environmentId: "environment-1", threadId: "thread-c" },- });- });-- it("uses ordinary navigation when native pops before the selection", () => {- const outgoingState = selectThread(initialState(), thread("thread-a"));- const outgoingRouteKey = outgoingState.routes[outgoingState.index]?.key;- expect(outgoingRouteKey).toBeDefined();-- const poppedState = dismissRoute(outgoingState, outgoingRouteKey!);- const action = createHomeThreadNavigationAction({- state: poppedState,- dismissingRouteKey: outgoingRouteKey ?? null,- thread: thread("thread-b"),- });-- const selectedState = apply(poppedState, action);- expect(selectedState.routes).toHaveLength(2);- expect(selectedState.routes[selectedState.index]).toMatchObject({- name: "Thread",- params: { environmentId: "environment-1", threadId: "thread-b" },- });- });-});--describe("draft and live thread selection", () => {- it("keeps the screen key and clears old identity when switching both ways", () => {- const live = selectThread(initialState(), thread("thread-a"));- const key = live.routes[live.index]!.key;- const draft = apply(- live,- createHomeThreadRouteAction({- state: live,- dismissingRouteKey: null,- params: { draft: { draftId: "new-task:draft-a" } },- }),- );- expect(draft.routes[draft.index]).toMatchObject({- key,- params: {- environmentId: undefined,- threadId: undefined,- draft: { draftId: "new-task:draft-a" },- },- });- const restored = selectThread(draft, thread("thread-b"));- expect(restored.routes[restored.index]).toMatchObject({- key,- params: {- environmentId: "environment-1",- threadId: "thread-b",- draft: undefined,- },- });- expect(restored.routes).toHaveLength(live.routes.length);- });-});diff --git a/apps/mobile/src/features/home/home-thread-navigation.ts b/apps/mobile/src/features/home/home-thread-navigation.tsdeleted file mode 100644index 3c1b18bf610..00000000000--- a/apps/mobile/src/features/home/home-thread-navigation.ts+++ /dev/null@@ -1,114 +0,0 @@-import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";-import {- CommonActions,- StackActions,- useNavigation,- type NavigationState,-} from "@react-navigation/native";-import type { NativeStackNavigationProp } from "@react-navigation/native-stack";-import { useCallback, useEffect, useRef } from "react";-import { Platform } from "react-native";-import { useAdaptiveWorkspaceLayout } from "../layout/adaptive-workspace-context";-import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSelection";--type ThreadSelection = Pick<EnvironmentThreadShell, "environmentId" | "id">;--export function createHomeThreadRouteAction(input: {- readonly state: Pick<NavigationState, "index" | "routes">;- readonly dismissingRouteKey: string | null;- readonly params: ReactNavigation.RootParamList["Thread"];-}) {- const currentRoute = input.state.routes[input.state.index];- if (input.dismissingRouteKey !== null && currentRoute?.key === input.dismissingRouteKey) {- return StackActions.push("Thread", input.params);- }- if (currentRoute?.name === "Thread") {- return {- ...CommonActions.setParams({- environmentId: undefined,- threadId: undefined,- draft: undefined,- ...input.params,- }),- source: currentRoute.key,- };- }- return CommonActions.navigate("Thread", input.params);-}--export function createHomeThreadNavigationAction(input: {- readonly state: Pick<NavigationState, "index" | "routes">;- readonly dismissingRouteKey: string | null;- readonly thread: ThreadSelection;-}) {- return createHomeThreadRouteAction({- ...input,- params: {- environmentId: input.thread.environmentId,- threadId: input.thread.id,- },- });-}--export function useHomeThreadRouteSelection() {- const navigation =- useNavigation<NativeStackNavigationProp<ReactNavigation.RootParamList, "Home">>();- const dismissingRouteKey = useRef<string | null>(null);- const { layout, setPrimarySidebarVisible } = useAdaptiveWorkspaceLayout();- const selectAndroidWorkspace = useAndroidWorkspaceSelection();-- useEffect(() => {- const clear = () => {- dismissingRouteKey.current = null;- };- // For Home, swipe-back is opening; Thread's closing event targets the outgoing route.- const removeTransitionStart = navigation.addListener("transitionStart", ({ data }) => {- const state = navigation.getState();- const currentRoute = state.routes[state.index];- dismissingRouteKey.current =- !data.closing && currentRoute?.name === "Thread" ? currentRoute.key : null;- });- const removeFocus = navigation.addListener("focus", clear);-- return () => {- clear();- removeTransitionStart();- removeFocus();- };- }, [navigation]);-- return useCallback(- (params: ReactNavigation.RootParamList["Thread"]) => {- if (Platform.OS === "android") {- selectAndroidWorkspace({- name: "Thread",- params,- });- return;- }- if (layout.primarySidebarOverlaysContent) setPrimarySidebarVisible(false);- navigation.dispatch((state) =>- createHomeThreadRouteAction({- state,- dismissingRouteKey: dismissingRouteKey.current,- params,- }),- );- },- [- layout.primarySidebarOverlaysContent,- navigation,- selectAndroidWorkspace,- setPrimarySidebarVisible,- ],- );-}--export function useHomeThreadSelection() {- const selectRoute = useHomeThreadRouteSelection();- return useCallback(- (thread: ThreadSelection) =>- selectRoute({ environmentId: thread.environmentId, threadId: thread.id }),- [selectRoute],- );-}diff --git a/apps/mobile/src/features/home/usePendingTaskListActions.ts b/apps/mobile/src/features/home/usePendingTaskListActions.tsindex f9c9d47f526..698df0bfce7 100644--- a/apps/mobile/src/features/home/usePendingTaskListActions.ts+++ b/apps/mobile/src/features/home/usePendingTaskListActions.ts@@ -1,5 +1,4 @@import * as Dialog from "../../components/ui/Dialog";-import { useHomeThreadRouteSelection } from "./home-thread-navigation";import { useCallback } from "react";import { removeThreadOutboxMessage } from "../../state/thread-outbox-removal";@@ -14,14 +13,11 @@ import {import { withThreadDismissal } from "./thread-dismissal";export function usePendingTaskListActions(- selectRoute?: (params: ReactNavigation.RootParamList["Thread"]) => void,+ selectThreadRoute: (params: ReactNavigation.RootParamList["Thread"]) => void,): {readonly openPendingTask: (pendingTask: PendingNewTask) => void;readonly confirmDeletePendingTask: (pendingTask: PendingNewTask) => void;} {- const selectHomeRoute = useHomeThreadRouteSelection();- const selectThreadRoute = selectRoute ?? selectHomeRoute;-const openPendingTask = useCallback((pendingTask: PendingNewTask) => {selectThreadRoute(diff --git a/apps/mobile/src/features/keyboard/CommandPalette.tsx b/apps/mobile/src/features/keyboard/CommandPalette.tsxindex 425fab9c56c..c5c3608f6c7 100644--- a/apps/mobile/src/features/keyboard/CommandPalette.tsx+++ b/apps/mobile/src/features/keyboard/CommandPalette.tsx@@ -48,7 +48,6 @@ import { threadEnvironment } from "../../state/threads";import { useAtomCommand } from "../../state/use-atom-command";import { useWorkspaceEnvironments } from "../../state/workspace";import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";-import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";import { ThreadSearchMatchExcerpt } from "../threads/thread-search-match";import {@@ -62,6 +61,7 @@ import { threadJumpIndex } from "./threadKeyboardShortcuts";import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs";import { openSettings } from "../settings/settings-navigation";import { useSelectWorkspaceTab } from "../workspace/useSelectWorkspaceTab";+import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";const PALETTE_COMMANDS: ReadonlyArray<HardwareKeyboardCommand> = ["commandPalette",@@ -212,7 +212,7 @@ export function CommandPalette(props: {const navigation = useNavigation();const selectTab = useSelectWorkspaceTab();const { themeVariables } = useAppearancePreferences();- const { selectThread, selectThreadRoute } = useAdaptiveWorkspaceLayout();+ const selectDetail = useSelectWorkspaceDetail();const runCommand = props.onCommand;const projects = useProjects();const threads = useThreadShells();@@ -323,12 +323,15 @@ export function CommandPalette(props: {title: `New thread in ${activeProject.title}`,searchTerms: ["new task", "chat", "create"],run: () =>- selectThreadRoute({- draft: {- requestId: uuidv4(),- environmentId: activeProject.environmentId,- projectId: activeProject.id,- title: activeProject.title,+ selectDetail({+ name: "Thread",+ params: {+ draft: {+ requestId: uuidv4(),+ environmentId: activeProject.environmentId,+ projectId: activeProject.id,+ title: activeProject.title,+ },},}),});@@ -358,12 +361,15 @@ export function CommandPalette(props: {detail: `New thread · ${savedConnectionsById[project.environmentId]?.environmentLabel ?? project.environmentId}`,searchTerms: [project.workspaceRoot, "new thread", "project"],run: () =>- selectThreadRoute({- draft: {- requestId: uuidv4(),- environmentId: project.environmentId,- projectId: project.id,- title: project.title,+ selectDetail({+ name: "Thread",+ params: {+ draft: {+ requestId: uuidv4(),+ environmentId: project.environmentId,+ projectId: project.id,+ title: project.title,+ },},}),}));@@ -391,7 +397,11 @@ export function CommandPalette(props: {...(thread.environmentId === activeThread?.environmentId && thread.id === activeThread.id? { secondary: true }: {}),- run: () => selectThread(thread),+ run: () =>+ selectDetail({+ name: "Thread",+ params: { environmentId: String(thread.environmentId), threadId: String(thread.id) },+ }),};});// Recent means used recently: written in or opened, whichever is later.@@ -410,8 +420,7 @@ export function CommandPalette(props: {projects,runCommand,savedConnectionsById,- selectThread,- selectThreadRoute,+ selectDetail,threads,]);const rankedMessageKeys = useMemo(() => {diff --git a/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx b/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsxindex df104a71188..eeb06c4e2e3 100644--- a/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx+++ b/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx@@ -32,6 +32,7 @@ import {subscribeToHardwareKeyboardCommandRegistrations,type HardwareKeyboardCommand,} from "./hardwareKeyboardCommands";+import { selectWorkspaceDetail } from "../workspace/workspace-detail-selection";const EMPTY_COPY_FEEDBACK: GitActionProgress = {phase: "idle",@@ -153,7 +154,7 @@ export function HardwareKeyboardCommandProvider({}if (command === "newTask") {- navigation.navigate("Thread", { draft: {} });+ navigation.dispatch(selectWorkspaceDetail({ name: "Thread", params: { draft: {} } }));return;}if (command === "back") {diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsxindex 70463d79535..8de05e3118d 100644--- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx+++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx@@ -9,13 +9,7 @@ import type {import { EnvironmentId, ThreadId, type SidebarProjectGroupingMode } from "@t3tools/contracts";import { useAtomValue } from "@effect/atom-react";import { useFocusEffect } from "@react-navigation/native";-import {- CommonActions,- NavigationContext,- NavigationRouteContext,- StackActions,- useNavigation,-} from "@react-navigation/native";+import { NavigationContext, NavigationRouteContext, useNavigation } from "@react-navigation/native";import {use,useDeferredValue,@@ -26,7 +20,7 @@ import {useState,type ReactNode,} from "react";-import { Platform, useWindowDimensions, View } from "react-native";+import { Keyboard, Platform, useWindowDimensions, View } from "react-native";import { KeyboardController, useKeyboardState } from "react-native-keyboard-controller";import Animated, {runOnJS,@@ -47,10 +41,6 @@ import {isWorkspaceListPath,type WorkspaceAuxiliaryPaneRole,} from "../../lib/layout";-import {- resolveThreadSelectionNavigationAction,- resolveThreadSelectionOverlayState,-} from "../../lib/adaptive-navigation";import { scopedThreadKey } from "../../lib/scopedEntities";import type { ThreadListFilters } from "../../persistence/mobile-preferences";import { appAtomRegistry } from "../../state/atom-registry";@@ -71,7 +61,11 @@ import {ANDROID_WORKSPACE_RAIL_WIDTH,} from "../workspace/AndroidWorkspaceNavigation";import { AndroidWorkspaceSidebar } from "../workspace/AndroidWorkspaceSidebar";-import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSelection";+import {+ selectWorkspaceDetail,+ type WorkspaceDetail,+ type WorkspaceDetailSheet,+} from "../workspace/workspace-detail-selection";import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";import { HomeListOptionsProvider } from "../home/home-list-options";import { newTaskDestination } from "../threads/new-task-project-selection";@@ -493,78 +487,46 @@ function AdaptiveWorkspaceLayoutContent(};const handleOpenSettings = () => openWorkspaceTab("settings");- const selectAndroidWorkspace = useAndroidWorkspaceSelection();const deferredThreadSelection = useMemo(() => createDeferredNavigation(), []);- function handleSelectThreadRoute(params: ReactNavigation.RootParamList["Thread"]) {- deferredThreadSelection.run(() => applyThreadRouteSelection(params));- }- function applyThreadRouteSelection(params: ReactNavigation.RootParamList["Thread"]) {- if (Platform.OS === "android") {+ /** The one way to show a page in the detail column; see `selectWorkspaceDetail`. */+ function handleSelectDetail(detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) {+ deferredThreadSelection.run(() => {+ if (Platform.OS === "android") Keyboard.dismiss();setFileInspectorPreferredVisible(false);- selectAndroidWorkspace({ name: "Thread", params });- return;- }- const navigationAction = resolveThreadSelectionNavigationAction({- usesSplitView: layout.usesSplitView,- pathname,- workspaceRouteName: navigation- .getState()- ?.routes.find((route) => route.key === props.workspaceRouteKey)?.name,- });- const overlayState = resolveThreadSelectionOverlayState({- state: navigation.getState(),- workspaceRouteKey: props.workspaceRouteKey,- action: navigationAction,- params,+ if (layout.primarySidebarOverlaysContent) setPrimarySidebarVisible(false);+ workspace?.dispatch({+ type: "select",+ tab: detail.name === "Thread" ? "threads" : "pullRequests",+ });+ navigation.dispatch(selectWorkspaceDetail(detail, sheet));});- if (overlayState !== null) {- setFileInspectorPreferredVisible(false);- navigation.dispatch(CommonActions.reset(overlayState));- return;- }- if (navigationAction === "set-params") {- setFileInspectorPreferredVisible(false);- const state = navigation.getState();- const route = state?.routes.find((candidate) => candidate.key === props.workspaceRouteKey);- if (route?.name === "Thread") {- navigation.dispatch({- ...CommonActions.setParams({- environmentId: undefined,- threadId: undefined,- draft: undefined,- ...params,- }),- source: route.key,- });- } else {- navigation.navigate("Thread", params);- }- return;- }- if (navigationAction === "replace") {- setFileInspectorPreferredVisible(false);- navigation.dispatch(StackActions.replace("Thread", params));- return;- }- navigation.navigate("Thread", params);}+ const handleSelectThreadRoute = (params: ReactNavigation.RootParamList["Thread"]) =>+ handleSelectDetail({ name: "Thread", params });const projects = useProjects();const compactAndroidSettings =Platform.OS === "android" && androidSettingsOpen && !layout.usesSplitView;+ // Reads the open page when pressed, so the layout context doesn't change on every navigation.const handleStartNewTask = () => {- const thread = appAtomRegistry- .get(environmentThreadShells.navigationThreadShellsAtom)- .find((candidate) => candidate.environmentId === environmentId && candidate.id === threadId);- const currentRoute = navigation- .getState()- ?.routes.find((route) => route.key === props.workspaceRouteKey);- const draft =+ const state = rootStackState(navigation);+ const currentRoute = workspaceRoutesOf(+ state?.routes.slice(0, state.index + 1) ?? [],+ ).workspace.at(-1);+ const params =currentRoute?.name === "Thread"- ? (currentRoute.params as ReactNavigation.RootParamList["Thread"])?.draft+ ? (currentRoute.params as ReactNavigation.RootParamList["Thread"]): undefined;const first = (value: string | string[] | undefined) =>Array.isArray(value) ? value[0] : value;+ const thread = appAtomRegistry+ .get(environmentThreadShells.navigationThreadShellsAtom)+ .find(+ (candidate) =>+ candidate.environmentId === first(params?.environmentId) &&+ candidate.id === first(params?.threadId),+ );+ const draft = params?.draft;const draftEnvironmentId = first(draft?.environmentId);const draftProjectId = first(draft?.projectId);const currentProject = thread@@ -786,8 +748,7 @@ function AdaptiveWorkspaceLayoutContent(primarySidebarSearchQuery,startNewTask: handleStartNewTask,deferThreadSelectionUntil: deferredThreadSelection.waitFor,- selectThread: handleSelectThread,- selectThreadRoute: handleSelectThreadRoute,+ selectDetail: handleSelectDetail,activateAuxiliaryPaneRole,registerWorkspaceInspector,setPrimarySidebarSearchQuery,diff --git a/apps/mobile/src/features/layout/adaptive-workspace-context.ts b/apps/mobile/src/features/layout/adaptive-workspace-context.tsindex 04d82f548f3..4f5f2033e02 100644--- a/apps/mobile/src/features/layout/adaptive-workspace-context.ts+++ b/apps/mobile/src/features/layout/adaptive-workspace-context.ts@@ -1,6 +1,9 @@import type { WorkspaceTab } from "../workspace/workspace-tabs-state";import { createContext, use, type ReactNode } from "react";-import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";+import type {+ WorkspaceDetail,+ WorkspaceDetailSheet,+} from "../workspace/workspace-detail-selection";import {deriveFileInspectorPaneLayout,deriveLayout,@@ -18,8 +21,8 @@ interface AdaptiveWorkspaceContextValue {readonly primarySidebarSearchQuery: string;readonly startNewTask: () => void;readonly deferThreadSelectionUntil: (operation: Promise<unknown>) => void;- readonly selectThread: (thread: EnvironmentThreadShell) => void;- readonly selectThreadRoute: (params: ReactNavigation.RootParamList["Thread"]) => void;+ /** Use `useSelectWorkspaceDetail`, which also works outside the layout. */+ readonly selectDetail?: (detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) => void;readonly activateAuxiliaryPaneRole: (role: WorkspaceAuxiliaryPaneRole) => () => void;readonly registerWorkspaceInspector: (render: () => ReactNode) => () => void;readonly setPrimarySidebarSearchQuery: (query: string) => void;@@ -60,8 +63,6 @@ export const AdaptiveWorkspaceContext = createContext<AdaptiveWorkspaceContextVaprimarySidebarSearchQuery: "",startNewTask: () => undefined,deferThreadSelectionUntil: () => undefined,- selectThread: () => undefined,- selectThreadRoute: () => undefined,activateAuxiliaryPaneRole: () => () => undefined,registerWorkspaceInspector: () => () => undefined,setPrimarySidebarSearchQuery: () => undefined,diff --git a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsxindex 136a1d50e14..61075bad190 100644--- a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx+++ b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx@@ -29,6 +29,7 @@ import { WorkspaceNativeTabs } from "../workspace/WorkspaceNativeTabs.ios";import { workspaceUsesColumns } from "../workspace/workspace-tabs-state";import { isSettingsRoute, settingsOpenIn } from "../settings/settings-navigation";import { workspaceRoutesOf } from "./workspace-overlay-routes";+import { setNativelyPoppingWorkspaceRoute } from "../workspace/workspace-detail-selection";import { useWorkspaceSidebarHeaderItem } from "./useWorkspaceSidebarHeaderItem";import { useDeviceType, useNativeLayoutMetrics } from "../../native/native-layout-metrics";@@ -71,18 +72,12 @@ const isPullRequestRoute = (route: Route) =>route.name === "PullRequestFile" ||route.name === "PullRequestFiles";-/** Only these screens follow the sidebar's state; a thread's header draws its own toggle. */-function SidebarToggleHeader(props: ComponentProps<typeof V5StackHeader>) {- const sidebarItem = useWorkspaceSidebarHeaderItem();- const options = {- ...props.options,- unstable_headerLeftItems: () => [sidebarItem],- } as AppNativeStackNavigationOptions as typeof props.options;- return <V5StackHeader {...props} options={options} />;-}+/** Beside the list, the first Settings page shows on one native screen that swaps its content. */+const SETTINGS_DETAIL_SCREEN = "settings-detail";function ColumnScreen(props: {readonly descriptor: Descriptor;+ readonly screenKey?: string;readonly primary?: boolean;readonly attached?: boolean;readonly selectedThreadKey?: string | null;@@ -96,13 +91,20 @@ function ColumnScreen(props: {}) {const { descriptor } = props;// Options a screen set inside this workspace tab slot, over its route's.- const options = slotScreenOptions(+ const slotOptions = slotScreenOptions(use(WorkspaceSlotOptionsContext),descriptor.route.key,descriptor.options,);- const Header =- props.sidebarToggle && !options.unstable_headerLeftItems ? SidebarToggleHeader : V5StackHeader;+ const sidebarItem = useWorkspaceSidebarHeaderItem();+ // Swapping header components would unmount the native header config, which hides the bar.+ const options =+ props.sidebarToggle && !slotOptions.unstable_headerLeftItems+ ? ({+ ...slotOptions,+ unstable_headerLeftItems: () => [sidebarItem],+ } as AppNativeStackNavigationOptions as typeof slotOptions)+ : slotOptions;const [presented, setPresented] = useState(false);const primaryColumn = useMemo(() =>@@ -118,7 +120,7 @@ function ColumnScreen(props: {const key = descriptor.route.key;return (<Split.Screen- screenKey={key}+ screenKey={props.screenKey ?? key}activityMode={props.attached === false ? "detached" : "attached"}onDismiss={(event) => {props.onDismiss(key, event.nativeEvent.isNativeDismiss);@@ -143,7 +145,7 @@ function ColumnScreen(props: {><NavigationContext value={descriptor.navigation}><NavigationRouteContext value={descriptor.route}>- <Header+ <V5StackHeaderoptions={options}canGoBack={!props.primary}column={props.primary ? "primary" : "detail"}@@ -156,6 +158,7 @@ function ColumnScreen(props: {}/><ColumnContent+ key={key}primary={props.primary}insetHorizontally={(options as AppNativeStackNavigationOptions).nativeContentInsetHorizontally@@ -184,6 +187,8 @@ function WorkspaceColumns(openWorkspaceTab,} = useAdaptiveWorkspaceLayout();const deviceType = useDeviceType();+ const settingsDetailIn = (detail: readonly Route[]) =>+ layout.usesSplitView && detail[0] && isSettingsRoute(detail[0].name) ? detail[0] : undefined;// Split screens must remain mounted while UIKit animates a detached route away.const [screens, setScreens] = useState({routes: props.detail,@@ -196,9 +201,13 @@ function WorkspaceColumns(screens.observedRoutes !== props.detail ||screens.observedDescriptors !== props.descriptors) {- const routes = reconcileStackScreens(screens.routes, props.detail, screens.completed);- const retained = new Set(routes.map((route) => route.key));const active = new Set(props.detail.map((route) => route.key));+ const settingsSlot = settingsDetailIn(props.detail);+ const routes = reconcileStackScreens(screens.routes, props.detail, screens.completed).filter(+ // The slot's native screen stays; the pages it showed, and any above them, just go.+ (route) => !settingsSlot || active.has(route.key) || !isSettingsRoute(route.name),+ );+ const retained = new Set(routes.map((route) => route.key));setScreens({routes,descriptors: Object.fromEntries(@@ -280,6 +289,7 @@ function WorkspaceColumns(props.primary.key,);collapsedColumn.current = transition.column;+ setNativelyPoppingWorkspaceRoute(transition.column.leaving);if (transition.pop) props.navigation.dispatch(transition.pop);};@@ -301,9 +311,11 @@ function WorkspaceColumns(onCollapse={() => {collapsed.current = true;collapsedColumn.current = { visible: compactColumn, leaving: null };+ setNativelyPoppingWorkspaceRoute(null);}}onExpand={() => {collapsed.current = false;+ setNativelyPoppingWorkspaceRoute(null);// Native callbacks can outlive the render that created them, so decide from the live// router state. An expanded split has columns, so its tab gets a page beside the list.const live = props.navigation.getState();@@ -392,15 +404,14 @@ function WorkspaceColumns(</Split.Screen>{screens.routes.map((route) => {const descriptor = props.descriptors[route.key] ?? screens.descriptors[route.key];+ const inSettingsSlot = settingsDetailIn(props.detail)?.key === route.key;+ const screenKey = inSettingsSlot ? SETTINGS_DETAIL_SCREEN : route.key;return descriptor ? (<ColumnScreen- key={route.key}+ key={screenKey}+ screenKey={screenKey}descriptor={descriptor}- sidebarToggle={- layout.usesSplitView &&- props.detail[0]?.key === route.key &&- isSettingsRoute(route.name)- }+ sidebarToggle={inSettingsSlot}attached={props.detail.some((current) => current.key === route.key)}onDismiss={handleNativeDismiss}onAppearance={followCollapsedSplit}@@ -469,6 +480,7 @@ function WorkspaceStackView(props: ViewProps & { readonly nativeColumns: boolean<V5CardStackView{...props}onRootVisibilityChange={setPrimaryVisible}+ onNativePopChange={setNativelyPoppingWorkspaceRoute}descriptors={descriptors}state={{...props.state,diff --git a/apps/mobile/src/features/pull-requests/PullRequestStackCard.tsx b/apps/mobile/src/features/pull-requests/PullRequestStackCard.tsxindex 734be2162a6..b2f51a9bd0a 100644--- a/apps/mobile/src/features/pull-requests/PullRequestStackCard.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestStackCard.tsx@@ -1,7 +1,7 @@import { StackActions, useNavigation } from "@react-navigation/native";import { useState } from "react";import { Platform, View } from "react-native";-import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSelection";+import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";import { AppText as Text } from "../../components/ui/AppText";import { PullRequestCardGroup, PullRequestCardRow } from "./PullRequestControls";import { pullRequestStatus } from "./pullRequestStatus";@@ -14,7 +14,7 @@ export function PullRequestStackCard(props: {readonly state: PullRequestStackState;}) {const navigation = useNavigation();- const selectAndroidWorkspace = useAndroidWorkspaceSelection();+ const selectDetail = useSelectWorkspaceDetail();const [expanded, setExpanded] = useState(false);const stack = props.state.stack;if (!stack) {@@ -68,7 +68,7 @@ export function PullRequestStackCard(props: {: () => {const params = { ...props.params, number: layer.number };if (Platform.OS === "android")- selectAndroidWorkspace({ name: "PullRequest", params });+ selectDetail({ name: "PullRequest", params });else navigation.dispatch(StackActions.push("PullRequest", params));}}diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsxindex 6c48ceb446e..1554c184d39 100644--- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx@@ -42,7 +42,7 @@ import {} from "./pullRequestList";import { useDebouncedValue } from "../../state/queries";import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";-import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSelection";+import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";function PullRequestScrollView(props: ScrollViewProps) {return (@@ -106,7 +106,7 @@ export function PullRequestsScreen(const environmentId = environments.some((item) => item.environmentId === selectedEnvironmentId)? selectedEnvironmentId: null;- const selectAndroidWorkspace = useAndroidWorkspaceSelection();+ const selectDetail = useSelectWorkspaceDetail();const selectPullRequest = useCallback((item: EnvironmentPullRequestListEntry) => {Keyboard.dismiss();@@ -118,10 +118,9 @@ export function PullRequestsScreen(host: item.host,initialSummary: item,};- if (Platform.OS === "android") selectAndroidWorkspace({ name: "PullRequest", params });- else navigation.navigate("PullRequest", params);+ selectDetail({ name: "PullRequest", params });},- [navigation, selectAndroidWorkspace],+ [selectDetail],);const allProjects = useProjects();const savedControls = listControls.controlsFor(environmentId);diff --git a/apps/mobile/src/features/pull-requests/usePullRequestListActions.ts b/apps/mobile/src/features/pull-requests/usePullRequestListActions.tsindex 188ecdd439a..c7cfe62f43b 100644--- a/apps/mobile/src/features/pull-requests/usePullRequestListActions.ts+++ b/apps/mobile/src/features/pull-requests/usePullRequestListActions.ts@@ -22,7 +22,7 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-cliimport { scopedPullRequestListKey, type EnvironmentPullRequestListEntry } from "./pullRequestList";import { copyPullRequestLink, sharePullRequestLink } from "./pullRequestLink";import { pullRequestTarget } from "./usePullRequestDiff";-import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSelection";+import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";export function usePullRequestListActions(environmentIds: readonly EnvironmentId[],@@ -33,7 +33,7 @@ export function usePullRequestListActions() {const registry = use(RegistryContext);const navigation = useNavigation();- const selectAndroidWorkspace = useAndroidWorkspaceSelection();+ const selectDetail = useSelectWorkspaceDetail();const permissionKey = JSON.stringify(environmentIds);const permissionAtom = (() => {const ids: readonly EnvironmentId[] = JSON.parse(permissionKey);@@ -80,7 +80,10 @@ export function usePullRequestListActions()throw new Error(`Review requests aren't available for this ${terminology.singular}.`);if (Platform.OS === "android") {- selectAndroidWorkspace({ name: "PullRequest", params: params(entry) }, params(entry));+ selectDetail(+ { name: "PullRequest", params: params(entry) },+ { name: "PullRequestReviewers", params: params(entry) },+ );} else navigation.navigate("PullRequestReviewers", params(entry));return;}@@ -112,9 +115,7 @@ export function usePullRequestListActions(};const select = (entry: EnvironmentPullRequestListEntry, action: string) => {if (action === "open") {- if (Platform.OS === "android")- selectAndroidWorkspace({ name: "PullRequest", params: params(entry) });- else navigation.navigate("PullRequest", params(entry));+ selectDetail({ name: "PullRequest", params: params(entry) });return;}if (action === "request-review") {diff --git a/apps/mobile/src/features/pull-requests/usePullRequestThreads.ts b/apps/mobile/src/features/pull-requests/usePullRequestThreads.tsindex 16e04b593d4..e1d9d871510 100644--- a/apps/mobile/src/features/pull-requests/usePullRequestThreads.ts+++ b/apps/mobile/src/features/pull-requests/usePullRequestThreads.ts@@ -1,7 +1,12 @@import { AsyncResult } from "effect/reactivity";import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";import * as Dialog from "../../components/ui/Dialog";-import { useNavigation, useNavigationState, useRoute } from "@react-navigation/native";+import {+ StackActions,+ useNavigation,+ useNavigationState,+ useRoute,+} from "@react-navigation/native";import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility";import {AuthOrchestrationOperateScope,@@ -15,7 +20,7 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-cliimport { normalizeThreadPullRequestKey } from "@t3tools/client-runtime/thread-pull-requests";import { useRef, useState } from "react";import { Platform } from "react-native";-import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSelection";+import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";import { pullRequestComposerContext } from "../../lib/composerContext";import { scopedThreadKey } from "../../lib/scopedEntities";import { uuidv4 } from "../../lib/uuid";@@ -71,13 +76,16 @@ export function usePullRequestThreads(const canAsk = !connected || canOperate;const canCheckout = useEnvironmentScope(target.environmentId, AuthSourceControlWriteScope);const navigation = useNavigation();- const selectAndroidWorkspace = useAndroidWorkspaceSelection();+ const selectDetail = useSelectWorkspaceDetail();const pending = useRef(false);const previousPrompts = useRef(new Map<string, string>());const openThread = (thread: LinkedThread) => {- const destination = { environmentId: params.environmentId, threadId: thread.id };- if (Platform.OS === "android") selectAndroidWorkspace({ name: "Thread", params: destination });- else navigation.navigate("Thread", destination);+ openThreadRoute({ environmentId: params.environmentId, threadId: thread.id });+ };+ // Android shows one page at a time; iOS opens the thread over the pull request, so Back returns.+ const openThreadRoute = (destination: ReactNavigation.RootParamList["Thread"]) => {+ if (Platform.OS === "android") selectDetail({ name: "Thread", params: destination });+ else navigation.dispatch(StackActions.push("Thread", destination));};const [busy, setBusy] = useState(false);const ask = async (thread?: LinkedThread, task: PullRequestAgentTask = "ask") => {@@ -152,10 +160,7 @@ export function usePullRequestThreads();previousPrompts.current.set(draftKey, pullRequestAgentPrompt(task, terminology));if (thread) openThread(thread);- else- navigation.navigate("Thread", {- draft: { draftId: draftKey, title: `Ask about #${pr.number}` },- });+ else openThreadRoute({ draft: { draftId: draftKey, title: `Ask about #${pr.number}` } });});pending.current = false;setBusy(false);diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsxindex 03cb70c8a49..6e864e2f3f5 100644--- a/apps/mobile/src/features/review/ReviewSheet.tsx+++ b/apps/mobile/src/features/review/ReviewSheet.tsx@@ -68,6 +68,7 @@ import { resolveReviewAvailability } from "./reviewAvailability";import { resolveSelectedReviewFileId } from "./reviewPaneSelection";import { buildReviewSectionMenu } from "./review-section-menu";import { reportShowcaseSceneRendered } from "../showcase/showcaseRenderSignal";+import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";function ReviewHeader(props: Parameters<typeof useReviewHeaderPresentation>[0] & {@@ -433,6 +434,7 @@ export function ReviewSheet(props: ReviewSheetProps) {useAdaptiveWorkspacePaneRole("inspector");const { panes, showAuxiliaryPane } = useAdaptiveWorkspaceLayout();const navigation = useNavigation();+ const selectDetail = useSelectWorkspaceDetail();const insets = useSafeAreaInsets();const { themeAppearance: selectedTheme } = useAppearancePreferences();const headerIcon = String(useUniwindTheme()["--color-icon"]);@@ -610,9 +612,9 @@ export function ReviewSheet(props: ReviewSheetProps) {navigation.goBack();return;}- navigation.navigate("Thread", {- environmentId: String(environmentId),- threadId: String(threadId),+ selectDetail({+ name: "Thread",+ params: { environmentId: String(environmentId), threadId: String(threadId) },});};const androidHeaderSubtitle = [diff --git a/apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx b/apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsxindex bd6e79adc19..10df7a298a4 100644--- a/apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx+++ b/apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx@@ -34,6 +34,7 @@ import {} from "./showcaseRenderSignal";import { stageShowcaseAgentActivity } from "./stageShowcaseAgentActivity";import { openSettings } from "../settings/settings-navigation";+import { selectWorkspaceDetail } from "../workspace/workspace-detail-selection";const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";const SHOWCASE_THREAD_ID = "remote-command-center";@@ -250,7 +251,7 @@ function EnabledShowcaseCaptureCoordinator(props: { readonly pathname: string })} else if (requestedScene === "review") {navigation.dispatch(CommonActions.navigate("ThreadReview", params));} else {- navigation.dispatch(CommonActions.navigate("Thread", params));+ navigation.dispatch(selectWorkspaceDetail({ name: "Thread", params }));}}, [hasFixture, navigation, requestedScene, scene, showcaseThread]);diff --git a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsxindex f6e7354dfca..01b3ed0c0f4 100644--- a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx+++ b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx@@ -37,6 +37,7 @@ import { usePromptLinkResolver } from "../prompt-links/usePromptLinkResolver";import { useIncomingShare } from "../sharing/IncomingShareProvider";import { useNewTaskFlow } from "./new-task-flow-provider";import { filterProjectScopes, getProjectScopeSelectionTarget } from "./new-task-project-selection";+import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";type NewTaskRouteParams = {readonly incomingShareId?: string | string[];@@ -154,6 +155,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParaconst { projectScopes, selectedEnvironmentId, setProject } = useNewTaskFlow();const { state: catalogState } = useWorkspaceState();const navigation = useNavigation();+ const selectDetail = useSelectWorkspaceDetail();const isFocused = useIsFocused();const insets = useSafeAreaInsets();const { getShare, releaseShareReservation } = useIncomingShare();@@ -231,11 +233,14 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePararoot?.goBack();return;}- root?.navigate("Thread", {- draft: {- environmentId: String(project.environmentId),- projectId: String(project.id),- incomingShareId: incomingShare?.id,+ selectDetail({+ name: "Thread",+ params: {+ draft: {+ environmentId: String(project.environmentId),+ projectId: String(project.id),+ incomingShareId: incomingShare?.id,+ },},});}@@ -282,18 +287,18 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParareturn;}resumedDestinationKeyRef.current = destinationKey;- (navigation.getState()?.routeNames.includes("NewTaskProject")- ? navigation- : navigation.getParent()- )?.navigate("Thread", {- draft: {- environmentId: reservedDestinationProject.environmentId,- projectId: reservedDestinationProject.id,- title: reservedDestinationProject.title,- incomingShareId: incomingShare.id,+ selectDetail({+ name: "Thread",+ params: {+ draft: {+ environmentId: reservedDestinationProject.environmentId,+ projectId: reservedDestinationProject.id,+ title: reservedDestinationProject.title,+ incomingShareId: incomingShare.id,+ },},});- }, [incomingShare, isFocused, navigation, reservedDestinationProject]);+ }, [incomingShare, isFocused, reservedDestinationProject, selectDetail]);return (<View collapsable={false} className="flex-1 bg-sheet">diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsxindex 815794df304..70aa6f22a61 100644--- a/apps/mobile/src/features/threads/ThreadFeed.tsx+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx@@ -289,6 +289,7 @@ import {ThreadMarkdownImageView,} from "./ThreadMarkdownImage";import { openSettings } from "../settings/settings-navigation";+import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";const WIDE_MARKDOWN_BLOCK_OPTIONS = {// iOS blockquotes and selectable text measure separately; definite bubble width matches UIKit's drawing width.@@ -435,6 +436,7 @@ function AssistantForkButton(props: {});const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun, "fork from response");const navigation = useNavigation();+ const selectDetail = useSelectWorkspaceDetail();const [busy, setBusy] = useState(false);const canFork = canForkProjectedAssistantItem({projectedItem: props.projectedItem,@@ -473,9 +475,9 @@ function AssistantForkButton(props: {);return;}- navigation.navigate("Thread", {- environmentId: props.environmentId,- threadId: targetThreadId,+ selectDetail({+ name: "Thread",+ params: { environmentId: props.environmentId, threadId: targetThreadId },});}).finally(() => setBusy(false));diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsxindex 2b6d7b30627..d56f635a04a 100644--- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx+++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx@@ -78,6 +78,7 @@ import {THREAD_LIST_V2_SETTLED_PAGE_COUNT,type ThreadListV2ListItem,} from "./threadListV2";+import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";type SidebarListItem =| ThreadListV2ListItem@@ -158,7 +159,10 @@ function ThreadNavigationSidebarPane(const pendingTasks = usePendingNewTasks();const activeNewTask = useActiveNewTask();const queuedThreadKeys = useQueuedThreadKeys();- const { confirmDeletePendingTask } = usePendingTaskListActions();+ const selectDetail = useSelectWorkspaceDetail();+ const { confirmDeletePendingTask } = usePendingTaskListActions((params) =>+ selectDetail({ name: "Thread", params }),+ );const environments = Object.values(savedConnectionsById).map((connection) => ({environmentId: connection.environmentId,diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsxindex 851fe0fb7ce..45b11324c13 100644--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx@@ -99,6 +99,7 @@ import {useWorkspaceBackNavigation,} from "../workspace/useAndroidWorkspaceNavigation";import { openSettings } from "../settings/settings-navigation";+import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";interface ThreadInspectorSelection {readonly routeThreadIdentity: string | null;@@ -340,6 +341,7 @@ function ThreadRouteContent(};})();const navigation = useNavigation();+ const selectDetail = useSelectWorkspaceDetail();const openPullRequest = useOpenPullRequest();const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");const mergeBackTargetThreadId = resolveMergeBackTargetThreadId(selectedThreadDetail);@@ -367,9 +369,9 @@ function ThreadRouteContent(});mergeBackBusyRef.current = false;if (result._tag !== "Success") return;- navigation.navigate("Thread", {- environmentId: selectedThread.environmentId,- threadId: mergeBackTargetThreadId,+ selectDetail({+ name: "Thread",+ params: { environmentId: selectedThread.environmentId, threadId: mergeBackTargetThreadId },});};const params = props.route.params ?? {};diff --git a/apps/mobile/src/features/workspace/useAndroidWorkspaceSelection.ts b/apps/mobile/src/features/workspace/useAndroidWorkspaceSelection.tsdeleted file mode 100644index fc536eedf3f..00000000000--- a/apps/mobile/src/features/workspace/useAndroidWorkspaceSelection.ts+++ /dev/null@@ -1,27 +0,0 @@-import { useNavigation } from "@react-navigation/native";-import { useCallback } from "react";-import { Keyboard } from "react-native";-import {- resetAndroidWorkspace,- type AndroidWorkspaceDestination,-} from "../../lib/android-workspace-navigation";-import { useWorkspaceTabs } from "./WorkspaceTabsContext";--export function useAndroidWorkspaceSelection() {- const navigation = useNavigation();- const dispatch = useWorkspaceTabs()?.dispatch;- return useCallback(- (- destination: AndroidWorkspaceDestination,- reviewers?: ReactNavigation.RootParamList["PullRequestReviewers"],- ) => {- Keyboard.dismiss();- dispatch?.({- type: "select",- tab: destination.name === "Thread" ? "threads" : "pullRequests",- });- resetAndroidWorkspace(navigation, destination, reviewers);- },- [navigation, dispatch],- );-}diff --git a/apps/mobile/src/features/workspace/useSelectWorkspaceDetail.ts b/apps/mobile/src/features/workspace/useSelectWorkspaceDetail.tsnew file mode 100644index 00000000000..a149212ba43--- /dev/null+++ b/apps/mobile/src/features/workspace/useSelectWorkspaceDetail.ts@@ -0,0 +1,21 @@+import { useNavigation } from "@react-navigation/native";+import { useAdaptiveWorkspaceLayout } from "../layout/adaptive-workspace-context";+import {+ selectWorkspaceDetail,+ type WorkspaceDetail,+ type WorkspaceDetailSheet,+} from "./workspace-detail-selection";++/**+ * Shows a page in the detail column the way selecting its list row does. Inside the workspace+ * layout this also settles its panes; outside it, the root stack's router still does the rest.+ */+export function useSelectWorkspaceDetail() {+ const navigation = useNavigation();+ const { selectDetail } = useAdaptiveWorkspaceLayout();+ return (+ selectDetail ??+ ((detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) =>+ navigation.dispatch(selectWorkspaceDetail(detail, sheet)))+ );+}diff --git a/apps/mobile/src/features/workspace/workspace-detail-selection.test.ts b/apps/mobile/src/features/workspace/workspace-detail-selection.test.tsnew file mode 100644index 00000000000..94e4e3be7db--- /dev/null+++ b/apps/mobile/src/features/workspace/workspace-detail-selection.test.ts@@ -0,0 +1,141 @@+import * as NodeModule from "node:module";+import { describe, expect, it } from "vite-plus/test";+import {+ selectWorkspaceDetail,+ setNativelyPoppingWorkspaceRoute,+ workspaceDetailLinkAction,+ workspaceDetailRouter,+ type WorkspaceDetail,+} from "./workspace-detail-selection";++const require = NodeModule.createRequire(import.meta.url);+const requireFromNative = NodeModule.createRequire(+ require.resolve("@react-navigation/native/package.json"),+);+const requireFromCore = NodeModule.createRequire(+ requireFromNative.resolve("@react-navigation/core/package.json"),+);+const { StackActions, StackRouter } = requireFromCore("@react-navigation/routers") as {+ readonly StackActions: typeof import("@react-navigation/native").StackActions;+ readonly StackRouter: typeof import("@react-navigation/native").StackRouter;+};++const base = StackRouter({});+const router = { ...base, ...workspaceDetailRouter(base) };+const options = {+ routeNames: [+ "Home",+ "Thread",+ "ThreadFiles",+ "PullRequest",+ "PullRequestReviewers",+ "Settings",+ "SettingsAppearance",+ "GitOverview",+ ],+ routeParamList: {},+ routeGetIdList: {},+};+type State = ReturnType<typeof base.getInitialState>;+type RouterAction = Parameters<typeof base.getStateForAction>[1];++const threadA = { name: "Thread", params: { environmentId: "env", threadId: "a" } } as const;+const threadB = { name: "Thread", params: { environmentId: "env", threadId: "b" } } as const;+const pullRequest = {+ name: "PullRequest",+ params: { environmentId: "env", projectId: "p", repository: "o/r", number: 1, host: "h" },+} as const;++function apply(state: State, action: Parameters<typeof base.getStateForAction>[1]) {+ const next = router.getStateForAction(state, action, options);+ if (!next) throw new Error(`Router rejected ${action.type}`);+ // React Navigation rehydrates every state a router returns, as a stale RESET needs.+ return base.getRehydratedState(next as State, options);+}++function select(+ state: State,+ detail: WorkspaceDetail,+ sheet?: Parameters<typeof selectWorkspaceDetail>[1],+) {+ return apply(state, selectWorkspaceDetail(detail, sheet) as unknown as RouterAction);+}++function push(state: State, name: string, params?: object) {+ return apply(state, StackActions.push(name, params));+}++const home = () => base.getInitialState(options);+const page = (state: State) => ({+ names: state.routes.map((route) => route.name),+ index: state.index,+});++describe("selectWorkspaceDetail", () => {+ it("swaps the open thread in place instead of pushing another", () => {+ const first = select(home(), threadA);+ const second = select(first, threadB);+ expect(page(second)).toEqual({ names: ["Home", "Thread"], index: 1 });+ expect(second.routes[1]?.key).toBe(first.routes[1]?.key);+ expect(second.routes[1]?.params).toEqual(threadB.params);+ });++ it.each([+ ["a page drilled into from the thread", (state: State) => push(state, "ThreadFiles")],+ ["a linked thread", (state: State) => push(state, "Thread", threadB.params)],+ ["a pull request opened from the thread", (state: State) => push(state, "PullRequest")],+ ["a sheet", (state: State) => push(state, "GitOverview")],+ ])("leaves only the selection when %s is on top", (_, drillIn) => {+ const thread = select(home(), threadA);+ const selected = select(drillIn(thread), threadA);+ expect(page(selected)).toEqual({ names: ["Home", "Thread"], index: 1 });+ expect(selected.routes[1]?.key).toBe(thread.routes[1]?.key);+ });++ it("replaces another tab's page and Settings with the selection", () => {+ const settings = push(push(select(home(), threadA), "Settings"), "SettingsAppearance");+ const selected = select(settings, pullRequest);+ expect(page(selected)).toEqual({ names: ["Home", "PullRequest"], index: 1 });+ expect(selected.routes[0]?.key).toBe(settings.routes[0]?.key);+ });++ it("puts Home under a cold-linked page and a sheet over the selection", () => {+ const cold = apply(home(), { type: "RESET", payload: { index: 0, routes: [pullRequest] } });+ const selected = select(cold, pullRequest, {+ name: "PullRequestReviewers",+ params: pullRequest.params,+ });+ expect(page(selected)).toEqual({+ names: ["Home", "PullRequest", "PullRequestReviewers"],+ index: 2,+ });+ });++ it("never reuses the page native Back is popping", () => {+ const thread = select(home(), threadA);+ setNativelyPoppingWorkspaceRoute(thread.routes[1]!.key);+ try {+ const selected = select(thread, threadA);+ expect(page(selected)).toEqual({ names: ["Home", "Thread"], index: 1 });+ expect(selected.routes[1]?.key).not.toBe(thread.routes[1]?.key);+ } finally {+ setNativelyPoppingWorkspaceRoute(null);+ }+ });+});++describe("workspaceDetailLinkAction", () => {+ it("selects a linked thread or pull request, and leaves other links alone", () => {+ expect(workspaceDetailLinkAction({ routes: [{ name: "Home" }, threadA] })).toEqual(+ selectWorkspaceDetail(threadA),+ );+ expect(workspaceDetailLinkAction({ routes: [pullRequest] })).toEqual(+ selectWorkspaceDetail(pullRequest),+ );+ expect(+ workspaceDetailLinkAction({+ routes: [{ name: "Home" }, { name: "Settings" }, { name: "SettingsAppearance" }],+ }),+ ).toBeUndefined();+ });+});diff --git a/apps/mobile/src/features/workspace/workspace-detail-selection.ts b/apps/mobile/src/features/workspace/workspace-detail-selection.tsnew file mode 100644index 00000000000..70131d6681f--- /dev/null+++ b/apps/mobile/src/features/workspace/workspace-detail-selection.ts@@ -0,0 +1,114 @@+import type {+ NavigationAction,+ ParamListBase,+ PartialState,+ NavigationState,+ Router,+ StackNavigationState,+} from "@react-navigation/native";+import { workspaceRoutesOf } from "../layout/workspace-overlay-routes";++type RootParams = ReactNavigation.RootParamList;++/** A page the workspace's detail column shows on its own: what a list row selects. */+export type WorkspaceDetail =+ | { readonly name: "Thread"; readonly params: RootParams["Thread"] }+ | { readonly name: "PullRequest"; readonly params: RootParams["PullRequest"] };++/** Android opens the reviewers sheet over the pull request in the same step. */+export type WorkspaceDetailSheet = {+ readonly name: "PullRequestReviewers";+ readonly params: RootParams["PullRequestReviewers"];+};++const SELECT_WORKSPACE_DETAIL = "SELECT_WORKSPACE_DETAIL";++export interface SelectWorkspaceDetailAction {+ readonly type: typeof SELECT_WORKSPACE_DETAIL;+ readonly payload: { readonly detail: WorkspaceDetail; readonly sheet?: WorkspaceDetailSheet };+}++/**+ * Shows `detail` as the workspace's only page, the way selecting a list row does. Drilling in+ * from a page pushes instead.+ */+export function selectWorkspaceDetail(+ detail: WorkspaceDetail,+ sheet?: WorkspaceDetailSheet,+): SelectWorkspaceDetailAction {+ return { type: SELECT_WORKSPACE_DETAIL, payload: sheet ? { detail, sheet } : { detail } };+}++const IDENTITY = {+ Thread: ["environmentId", "threadId"],+ PullRequest: ["environmentId", "projectId", "repository", "number", "host"],+} as const;++type RouteLike = { readonly name: string; readonly key?: string; readonly params?: object };++function showsDetail(route: RouteLike, detail: WorkspaceDetail) {+ if (route.name !== detail.name) return false;+ const current = route.params as Readonly<Record<string, unknown>> | undefined;+ const target = detail.params as Readonly<Record<string, unknown>> | undefined;+ return IDENTITY[detail.name].every((key) => current?.[key] === target?.[key]);+}++// UIKit pops a card by native Back before the router hears of it, so a row tapped meanwhile+// must not reuse the card on its way out.+let nativelyPoppingRoute: string | null = null;++export function setNativelyPoppingWorkspaceRoute(key: string | null) {+ nativelyPoppingRoute = key;+}++/**+ * The root stack after selecting `detail`: Home, then the detail alone. The route already showing+ * it, or else the detail column's current page of the same kind, keeps its key, so the column+ * updates in place instead of pushing.+ */+export function workspaceDetailState<+ State extends { readonly index: number; readonly routes: readonly RouteLike[] },+>(state: State, detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet, popping?: string | null) {+ const { workspace } = workspaceRoutesOf(state.routes.slice(0, state.index + 1));+ const leaving = workspace.findIndex((route) => route.key !== undefined && route.key === popping);+ const live = leaving < 0 ? workspace : workspace.slice(0, leaving);+ const home = live.find((route) => route.name === "Home") ?? { name: "Home" };+ const page = live.find((route) => route.name !== "Home" && route.name !== "Settings");+ const reused =+ live.findLast((route) => showsDetail(route, detail)) ??+ (page?.name === detail.name ? page : undefined);+ const routes = [+ home,+ reused ? { ...reused, params: detail.params } : { name: detail.name, params: detail.params },+ ...(sheet ? [sheet] : []),+ ];+ return { ...state, index: routes.length - 1, routes };+}++/** Root stack router overrides that handle `selectWorkspaceDetail`. */+export function workspaceDetailRouter<Action extends NavigationAction>(+ original: Router<StackNavigationState<ParamListBase>, Action>,+): Partial<Router<StackNavigationState<ParamListBase>, Action>> {+ return {+ getStateForAction(state, action, options) {+ if (action.type !== SELECT_WORKSPACE_DETAIL) {+ return original.getStateForAction(state, action, options);+ }+ const { detail, sheet } = (action as unknown as SelectWorkspaceDetailAction).payload;+ const next = workspaceDetailState(state, detail, sheet, nativelyPoppingRoute);+ const reset = { type: "RESET", payload: { ...next, stale: false } };+ return original.getStateForAction(state, reset as unknown as Action, options);+ },+ };+}++/** A link to a single thread or pull request selects it, like its list row would. */+export function workspaceDetailLinkAction(+ state: PartialState<NavigationState> | NavigationState,+): SelectWorkspaceDetailAction | undefined {+ const pages = state.routes.filter((route) => route.name !== "Home");+ const [page] = pages;+ if (pages.length !== 1 || !page || page.state) return undefined;+ if (page.name !== "Thread" && page.name !== "PullRequest") return undefined;+ return selectWorkspaceDetail({ name: page.name, params: page.params } as WorkspaceDetail);+}diff --git a/apps/mobile/src/features/workspace/workspace-selection-store.ts b/apps/mobile/src/features/workspace/workspace-selection-store.tsindex 52c11038719..aaabc0f1715 100644--- a/apps/mobile/src/features/workspace/workspace-selection-store.ts+++ b/apps/mobile/src/features/workspace/workspace-selection-store.ts@@ -46,12 +46,25 @@ function save() {.catch(() => undefined);}+// Route keys only name routes of the session that wrote them; a saved one would make a tab rebuild+// its page under a stale key, which UIKit animates as a pop and a push.+function withoutRouteKeys(saved: WorkspaceSelections | undefined): WorkspaceSelections {+ const omitKey = <Selection extends { readonly key?: string }>({ key: _, ...rest }: Selection) =>+ rest;+ const { threads, pullRequests, settingsKey: _, ...rest } = saved ?? {};+ return {+ ...rest,+ ...(threads ? { threads: omitKey(threads) } : {}),+ ...(pullRequests ? { pullRequests: omitKey(pullRequests) } : {}),+ };+}+/** Loads the saved selections once; pages visited before it resolves win over saved ones. */export function hydrateWorkspaceSelections() {if (!REMEMBERS) return Promise.resolve();hydration ??= loadPreferences().then((preferences) => {- selections = { ...preferences.workspaceSelections, ...selections };+ selections = { ...withoutRouteKeys(preferences.workspaceSelections), ...selections };saved = selections;AppState.addEventListener("change", (status) => {if (status !== "active") save();@@ -65,7 +78,10 @@ export function currentWorkspaceSelections() {return selections;}-/** The navigation container's `onStateChange`: remembers the page each tab is showing. */+/**+ * The navigation container's `onReady` and `onStateChange`: remembers the page each tab is+ * showing. The initial state, such as a cold start's reopened chat, reaches only `onReady`.+ */export function recordWorkspaceSelections(state: NavigationState | undefined) {if (!REMEMBERS || !state) return;selections = workspaceSelectionsIn(state.routes.slice(0, state.index + 1), selections);diff --git a/apps/mobile/src/lib/adaptive-navigation.test.ts b/apps/mobile/src/lib/adaptive-navigation.test.tsdeleted file mode 100644index 320b92a803e..00000000000--- a/apps/mobile/src/lib/adaptive-navigation.test.ts+++ /dev/null@@ -1,113 +0,0 @@-import { describe, expect, it } from "vite-plus/test";--import {- resolveThreadSelectionNavigationAction,- resolveThreadSelectionOverlayState,-} from "./adaptive-navigation";--describe("resolveThreadSelectionNavigationAction", () => {- it("retains the draft screen despite its query-shaped path", () => {- expect(- resolveThreadSelectionNavigationAction({- usesSplitView: true,- pathname: "/threads?draft=local",- workspaceRouteName: "Thread",- }),- ).toBe("set-params");- });- it("replaces nested thread content when a persistent sidebar selects a peer", () => {- expect(- resolveThreadSelectionNavigationAction({- usesSplitView: true,- pathname: "/threads/environment/thread/files/path",- }),- ).toBe("replace");- });-- it("pushes from Home so the back stack survives collapsing to compact", () => {- expect(- resolveThreadSelectionNavigationAction({- usesSplitView: true,- pathname: "/",- }),- ).toBe("push");- });-});--describe("resolveThreadSelectionOverlayState", () => {- const stack = {- key: "workspace",- type: "stack",- stale: false as const,- routeNames: ["Home", "Thread", "ThreadFiles", "Connections", "SettingsLegal"],- };- const home = { key: "home", name: "Home" };- const thread = {- key: "thread",- name: "Thread",- params: { environmentId: "environment", threadId: "old-thread" },- };- const files = { key: "files", name: "ThreadFiles", params: thread.params };- const settings = { key: "settings", name: "Connections" };- const params = { environmentId: "environment", threadId: "new-thread" };-- it("replaces the underlying file route and dismisses every overlay above it", () => {- expect(- resolveThreadSelectionOverlayState({- state: {- ...stack,- index: 4,- routes: [home, thread, files, settings, { key: "legal", name: "SettingsLegal" }],- },- workspaceRouteKey: files.key,- action: "replace",- params,- }),- ).toEqual({ ...stack, index: 2, routes: [home, thread, { name: "Thread", params }] });- });-- it("dismisses an overlay when selecting the current thread without replacing its route key", () => {- expect(- resolveThreadSelectionOverlayState({- state: { ...stack, index: 2, routes: [home, thread, settings] },- workspaceRouteKey: thread.key,- action: "set-params",- params: thread.params,- }),- ).toEqual({ ...stack, index: 1, routes: [home, thread] });- });-- it.each([home, files])(- "keeps $name in the back stack when pushing from beneath a sheet",- (route) => {- expect(- resolveThreadSelectionOverlayState({- state: { ...stack, index: 1, routes: [route, settings] },- workspaceRouteKey: route.key,- action: "push",- params,- }),- ).toEqual({ ...stack, index: 1, routes: [route, { name: "Thread", params }] });- },- );-});--it("replacing a draft underneath an overlay removes its draft identity", () => {- const result = resolveThreadSelectionOverlayState({- state: {- key: "root",- type: "stack",- stale: false,- routeNames: ["Thread", "Connections"],- index: 1,- routes: [- { key: "draft", name: "Thread", params: { draft: { draftId: "old" } } },- { key: "settings", name: "Connections" },- ],- },- workspaceRouteKey: "draft",- action: "set-params",- params: { environmentId: "env", threadId: "live" },- });- expect(result?.routes[0]?.params).toEqual({ environmentId: "env", threadId: "live" });-});diff --git a/apps/mobile/src/lib/adaptive-navigation.ts b/apps/mobile/src/lib/adaptive-navigation.tsdeleted file mode 100644index d19739369ef..00000000000--- a/apps/mobile/src/lib/adaptive-navigation.ts+++ /dev/null@@ -1,56 +0,0 @@-import type { NavigationState } from "@react-navigation/native";--export type AdaptiveNavigationAction = "push" | "replace" | "set-params";--const BASE_THREAD_ROUTE_PATTERN = /^\/threads\/[^/]+\/[^/]+\/?$/;--export function isBaseThreadRoute(pathname: string): boolean {- return BASE_THREAD_ROUTE_PATTERN.test(pathname) || /^\/new\/draft\/?$/.test(pathname);-}--/** Push from Home so it stays beneath Thread when split view collapses. */-export function resolveThreadSelectionNavigationAction(input: {- readonly usesSplitView: boolean;- readonly pathname: string;- readonly workspaceRouteName?: string;-}): AdaptiveNavigationAction {- if (!input.usesSplitView || input.pathname === "/") {- return "push";- }-- return input.workspaceRouteName === "Thread" || isBaseThreadRoute(input.pathname)- ? "set-params"- : "replace";-}--export function resolveThreadSelectionOverlayState(input: {- readonly state: NavigationState | undefined;- readonly workspaceRouteKey: string | undefined;- readonly action: AdaptiveNavigationAction;- readonly params: ReactNavigation.RootParamList["Thread"];-}) {- if (input.state === undefined) return null;- const workspaceIndex = input.state.routes.findIndex(- (route) => route.key === input.workspaceRouteKey,- );- if (workspaceIndex < 0 || workspaceIndex >= input.state.index) return null;-- const workspaceRoute = input.state.routes[workspaceIndex];- const routes = input.state.routes.slice(0, workspaceIndex + (input.action === "push" ? 1 : 0));- return {- ...input.state,- index: routes.length,- routes: [- ...routes,- input.action === "set-params" && workspaceRoute?.name === "Thread"- ? { ...workspaceRoute, params: input.params }- : { name: "Thread", params: input.params },- ],- };-}--export function resolveFileSelectionNavigationAction(input: {- readonly hasPersistentFileInspector: boolean;-}): AdaptiveNavigationAction {- return input.hasPersistentFileInspector ? "replace" : "push";-}diff --git a/apps/mobile/src/lib/android-workspace-navigation.test.ts b/apps/mobile/src/lib/android-workspace-navigation.test.tsindex c55c3a9e98d..822ea694434 100644--- a/apps/mobile/src/lib/android-workspace-navigation.test.ts+++ b/apps/mobile/src/lib/android-workspace-navigation.test.ts@@ -11,7 +11,6 @@ import {parentThreadIsBelow,resetAndroidWorkspace,returnToAndroidWorkspaceList,- type AndroidWorkspaceDestination,} from "./android-workspace-navigation";import type { RootStackResetAction } from "./root-stack-reset";@@ -69,15 +68,8 @@ function apply(return router.getRehydratedState(result, options);}-function select(- state: ReturnType<typeof router.getInitialState>,- destination?: AndroidWorkspaceDestination,- reviewers?: ReactNavigation.RootParamList["PullRequestReviewers"],-) {- return apply(- state,- CommonActions.reset(androidWorkspaceNavigationState(state, destination, reviewers)),- );+function withThread() {+ return apply(router.getInitialState(options), StackActions.push(thread.name, thread.params));}function legacyHistory() {@@ -92,69 +84,8 @@ function names(state: ReturnType<typeof router.getInitialState>) {}describe("Android workspace navigation", () => {- it("replaces cross-tab history with one detail and returns directly to its list", () => {- const previous = legacyHistory();- const state = select(previous, pullRequest);- expect(names(state)).toEqual(["Home", "PullRequest"]);- expect(state.routes[0]?.key).toBe(previous.routes[0]?.key);- expect(state.routes[1]?.key).toBe(previous.routes[2]?.key);- expect(names(apply(state, StackActions.pop()))).toEqual(["Home"]);- });-- it("replaces peer thread selections without leaving the previous thread underneath", () => {- const first = select(router.getInitialState(options), thread);- const second = select(first, {- name: "Thread",- params: { ...thread.params, threadId: "thread-b" },- });- expect(names(second)).toEqual(["Home", "Thread"]);- expect(second.routes[1]?.params).toEqual({ ...thread.params, threadId: "thread-b" });- expect(second.routes[1]?.key).not.toBe(first.routes[1]?.key);- expect(names(apply(second, StackActions.pop()))).toEqual(["Home"]);- });-- it("creates Home beneath cold-linked details and gives direct list escape", () => {- const initial = router.getInitialState(options);- const cold = apply(initial, CommonActions.reset({ index: 0, routes: [pullRequest] }));- expect(names(select(cold, pullRequest))).toEqual(["Home", "PullRequest"]);- expect(names(select(cold))).toEqual(["Home"]);- });-- it("keeps a request-review flow above the chosen PR instead of an old chat", () => {- const state = select(legacyHistory(), pullRequest, pullRequest.params);- expect(names(state)).toEqual(["Home", "PullRequest", "PullRequestReviewers"]);- const back = apply(state, StackActions.pop());- expect(names(back)).toEqual(["Home", "PullRequest"]);- expect(back.routes[back.index]?.params).toEqual(pullRequest.params);- });-- it.each(["ThreadFiles", "ThreadTerminal", "GitOverview"])(- "returns to chat when its sidebar row is selected from %s",- (route) => {- const detail = select(router.getInitialState(options), thread);- const nested = apply(detail, StackActions.push(route, thread.params));- const selected = select(nested, thread);- expect(names(selected)).toEqual(["Home", "Thread"]);- expect(selected.routes[1]?.key).toBe(detail.routes[1]?.key);- expect(names(apply(selected, StackActions.pop()))).toEqual(["Home"]);- },- );-- it.each([{ environmentId: "environment-b" }, { repository: "owner/other" }])(- "does not reuse another PR's key when its scope differs: %o",- (change) => {- const previous = select(router.getInitialState(options), pullRequest);- const state = select(previous, {- name: "PullRequest",- params: { ...pullRequest.params, ...change },- });- expect(state.routes[1]?.key).not.toBe(previous.routes[1]?.key);- expect(state.routes[1]?.params).toEqual({ ...pullRequest.params, ...change });- },- );-it("returns to a distinct previous thread, otherwise to the workspace list", () => {- const parent = select(router.getInitialState(options), thread);+ const parent = withThread();let state = apply(parent,StackActions.push("Thread", { ...thread.params, threadId: "child-a" }),@@ -206,7 +137,7 @@ describe("Android workspace navigation", () => {});it("opens a linked thread above the current one so Back returns to it", () => {- const parent = select(router.getInitialState(options), thread);+ const parent = withThread();const child = { ...thread.params, threadId: "child-a" };const open = (state: ReturnType<typeof router.getInitialState>,@@ -230,7 +161,7 @@ describe("Android workspace navigation", () => {});it("recognizes a parent only when its environment and thread are immediately below", () => {- const parent = select(router.getInitialState(options), thread);+ const parent = withThread();const child = apply(parent,StackActions.push("Thread", { ...thread.params, threadId: "child-a" }),@@ -259,35 +190,29 @@ describe("Android workspace navigation", () => {getParent: () => undefined,getState: () => root,};- resetAndroidWorkspace(- {- dispatch: (action) => actions.push(action),- getParent: () => rootNavigation,- getState: () => nested,- },- thread,- );+ resetAndroidWorkspace({+ dispatch: (action) => actions.push(action),+ getParent: () => rootNavigation,+ getState: () => nested,+ });const [action] = actions;expect(action?.target).toBe(root.key);- expect(names(apply(root, action!))).toEqual(["Home", "Thread"]);+ expect(names(apply(root, action!))).toEqual(["Home"]);});it("resets from the navigation container before any navigation action", () => {const root = router.getInitialState(options);const actions: RootStackResetAction[] = [];// The container only learns the root state after the first action.- resetAndroidWorkspace(- {- dispatch: (action) => actions.push(action),- getParent: () => undefined,- getState: () => undefined,- getRootState: () => root,- },- thread,- );+ resetAndroidWorkspace({+ dispatch: (action) => actions.push(action),+ getParent: () => undefined,+ getState: () => undefined,+ getRootState: () => root,+ });const [action] = actions;expect(action?.target).toBe(root.key);- expect(names(apply(root, action!))).toEqual(["Home", "Thread"]);+ expect(names(apply(root, action!))).toEqual(["Home"]);});});diff --git a/apps/mobile/src/lib/android-workspace-navigation.ts b/apps/mobile/src/lib/android-workspace-navigation.tsindex 0c5408d82b6..3c2a995e41a 100644--- a/apps/mobile/src/lib/android-workspace-navigation.ts+++ b/apps/mobile/src/lib/android-workspace-navigation.ts@@ -1,10 +1,6 @@import type { NavigationState } from "@react-navigation/native";import { resetRootStack, type RootStackNavigation } from "./root-stack-reset";-export type AndroidWorkspaceDestination =- | { readonly name: "Thread"; readonly params: ReactNavigation.RootParamList["Thread"] }- | { readonly name: "PullRequest"; readonly params: ReactNavigation.RootParamList["PullRequest"] };-function androidWorkspaceBackReturnsToThread(state: NavigationState) {const current = state.routes[state.index];const params = current?.params as ReactNavigation.RootParamList["Thread"] | undefined;@@ -16,43 +12,14 @@ function androidWorkspaceBackReturnsToThread(state: NavigationState) {);}-export function androidWorkspaceNavigationState(- state: NavigationState,- destination?: AndroidWorkspaceDestination,- reviewers?: ReactNavigation.RootParamList["PullRequestReviewers"],-) {+/** The root stack with only the workspace list. */+export function androidWorkspaceNavigationState(state: NavigationState) {const home = state.routes.find((route) => route.name === "Home") ?? { name: "Home" };- if (!destination) return { ...state, index: 0, routes: [home] };- const identity =- destination.name === "Thread"- ? ["environmentId", "threadId"]- : ["environmentId", "projectId", "repository", "number", "host"];- const params = destination.params as Readonly<Record<string, unknown>>;- const existing = state.routes.findLast((route) => {- if (route.name !== destination.name) return false;- const current = route.params as Readonly<Record<string, unknown>> | undefined;- return identity.every((key) => current?.[key] === params[key]);- });- return {- ...state,- index: reviewers ? 2 : 1,- routes: [- home,- { ...existing, ...destination },- ...(reviewers ? [{ name: "PullRequestReviewers", params: reviewers }] : []),- ],- };+ return { ...state, index: 0, routes: [home] };}-/** Resets the root stack to a workspace list or detail. */-export function resetAndroidWorkspace(- navigation: RootStackNavigation,- destination?: AndroidWorkspaceDestination,- reviewers?: ReactNavigation.RootParamList["PullRequestReviewers"],-) {- resetRootStack(navigation, (state) =>- androidWorkspaceNavigationState(state, destination, reviewers),- );+export function resetAndroidWorkspace(navigation: RootStackNavigation) {+ resetRootStack(navigation, androidWorkspaceNavigationState);}export function parentThreadIsBelow(diff --git a/apps/mobile/src/native/createV5StackNavigator.ios.tsx b/apps/mobile/src/native/createV5StackNavigator.ios.tsxindex 0597e6b0777..a9ad443aa4a 100644--- a/apps/mobile/src/native/createV5StackNavigator.ios.tsx+++ b/apps/mobile/src/native/createV5StackNavigator.ios.tsx@@ -54,12 +54,24 @@ export function modalEnvelopeOptions(options: NativeStackNavigationOptions) {/** Keep outgoing screens until UIKit completes its pop, as required by v5. */export function V5CardStackView(- props: V5StackViewProps & { readonly onRootVisibilityChange?: (visible: boolean) => void },+ props: V5StackViewProps & {+ readonly onRootVisibilityChange?: (visible: boolean) => void;+ /** The card native Back is popping, which the router still shows until the pop finishes. */+ readonly onNativePopChange?: (key: string | null) => void;+ },) {const { preventedRoutes } = usePreventRemoveContext();// Options a screen set inside this workspace tab slot, over its route's.const slot = use(WorkspaceSlotOptionsContext);const nativePopSource = useRef<string | null>(null);+ const { onNativePopChange } = props;+ const setNativePopSource = useCallback(+ (key: string | null) => {+ nativePopSource.current = key;+ onNativePopChange?.(key);+ },+ [onNativePopChange],+ );const [screens, setScreens] = useState({completedNativeDismissals: new Set<string>(),nativeCompletingPops: new Set<string>(),@@ -121,11 +133,11 @@ export function V5CardStackView(descriptors,};});- if (nativePopSource.current === key) nativePopSource.current = null;+ if (nativePopSource.current === key) setNativePopSource(null);const action = nativeStackPopAction(state, key);if (action) props.navigation.dispatch(action);},- [props.navigation, setScreens],+ [props.navigation, setNativePopSource, setScreens],);const removeDismissed = useCallback((key: string) => {@@ -177,7 +189,7 @@ export function V5CardStackView(onDidAppear={() => {const source = nativePopSource.current;if (source === route.key) {- nativePopSource.current = null;+ setNativePopSource(null);} else if (source) {const state = props.navigation.getState();const action = nativeStackPopAction(state, source, route.key);@@ -194,7 +206,7 @@ export function V5CardStackView(...poppedKeys,]),}));- nativePopSource.current = null;+ setNativePopSource(null);props.navigation.dispatch(action);}}@@ -209,7 +221,7 @@ export function V5CardStackView(const state = props.navigation.getState();// Only native Back leaves the disappearing card active; JS navigation already changed history.if (state.index > 0 && state.routes[state.index]?.key === route.key) {- nativePopSource.current = route.key;+ setNativePopSource(route.key);}props.navigation.emit({type: "transitionStart",diff --git a/apps/mobile/src/native/useOpenPullRequest.ts b/apps/mobile/src/native/useOpenPullRequest.tsindex 4e71aa5fde1..4ce5b4e876a 100644--- a/apps/mobile/src/native/useOpenPullRequest.ts+++ b/apps/mobile/src/native/useOpenPullRequest.ts@@ -2,7 +2,7 @@ import { useNavigation, useRoute, StackActions } from "@react-navigation/native"import { nativePullRequestDestination } from "../lib/pullRequestNavigation";import { useCallback } from "react";import { Platform } from "react-native";-import { resetAndroidWorkspace } from "../lib/android-workspace-navigation";+import { useSelectWorkspaceDetail } from "../features/workspace/useSelectWorkspaceDetail";import { EnvironmentId, ThreadId } from "@t3tools/contracts";import { useProjects, useThreadShell } from "../state/entities";import { tryOpenExternalUrl } from "../lib/openExternalUrl";@@ -14,6 +14,7 @@ type PullRequestContext = { readonly environmentId: string; readonly projectId:// Avoid useRoute so layouts without route context can open any thread's pull requests.export function useNavigateToPullRequest(options?: { readonly replace?: boolean }) {const navigation = useNavigation();+ const selectDetail = useSelectWorkspaceDetail();const projects = useProjects();const replace = options?.replace;return useCallback(@@ -27,13 +28,13 @@ export function useNavigateToPullRequest(options?: { readonly replace?: boolean(environmentId) => serverConfigs.get(environmentId)?.environment.capabilities,);if (!params) return tryOpenExternalUrl(url, "pull-request");- if (Platform.OS === "android")- resetAndroidWorkspace(navigation, { name: "PullRequest", params });+ // Android shows one page at a time; iOS opens it over the current page, so Back returns.+ if (Platform.OS === "android") selectDetail({ name: "PullRequest", params });else if (replace) navigation.dispatch(StackActions.replace("PullRequest", params));- else navigation.navigate("PullRequest", params);+ else navigation.dispatch(StackActions.push("PullRequest", params));return true;},- [navigation, projects, replace],+ [navigation, projects, replace, selectDetail],);}diff --git a/docs/internals/mobile-navigation.md b/docs/internals/mobile-navigation.mdindex 2e48739e456..cf4dea31594 100644--- a/docs/internals/mobile-navigation.md+++ b/docs/internals/mobile-navigation.md@@ -5,6 +5,32 @@ so UIKit can animate the header within one navigation controller. The iPad sidebhas its own stack. Splitting Home and threads between controllers loses thatcontinuous transition.+## Selecting versus drilling in++Opening a page has two intents, and each has one action:++- **Select** shows a thread or pull request as the workspace's only page, the+ way a list row does. Everything that selects (rows, the command palette,+ compose, notifications, deep links) uses+ [`selectWorkspaceDetail`](../../apps/mobile/src/features/workspace/workspace-detail-selection.ts),+ which the root stack's router handles. The resulting stack is the same on+ phones, collapsed splits, and expanded splits. Only route keys differ: the+ page already showing keeps its key, so the detail column updates in place+ instead of pushing.+- **Drill in** opens a page over the current one so Back returns, with+ `StackActions.push`.++`navigate` to `Thread` or `PullRequest` is rejected by lint, because it pushes+or updates in place depending on what happens to be on top. Never infer the+choice from transition events: UIKit reports the sidebar column appearing in+split views too. The one native signal the router uses is the card native Back+is popping. The workspace navigator reports it, and a selection never reuses+that card.++Beside the list, Settings pages share one native screen whose content swaps,+like the system Settings app. A route per page would pop and push the column,+and would unmount its header configuration, which hides the navigation bar.+## UIKit constraintsThe [react-native-screens patch](../../patches/[email protected])diff --git a/oxlint-plugin-t3code/index.ts b/oxlint-plugin-t3code/index.tsindex 43c7a93eee8..999808515fc 100644--- a/oxlint-plugin-t3code/index.ts+++ b/oxlint-plugin-t3code/index.ts@@ -12,6 +12,7 @@ import noLowValueComments from "./rules/no-low-value-comments.ts";import noManualMemo from "./rules/no-manual-memo.ts";import noManualEffectRuntimeInTests from "./rules/no-manual-effect-runtime-in-tests.ts";import noMobileUniwindThemeEscapeHatches from "./rules/no-mobile-uniwind-theme-escape-hatches.ts";+import noAmbiguousDetailNavigation from "./rules/no-ambiguous-detail-navigation.ts";import noMobilePullRequestGlyphLiterals from "./rules/no-mobile-pull-request-glyph-literals.ts";import noNativeTitleTooltip from "./rules/no-native-title-tooltip.ts";import noOutsetStateIndicators from "./rules/no-outset-state-indicators.ts";@@ -47,6 +48,7 @@ export default definePlugin({"no-manual-effect-runtime-in-tests": noManualEffectRuntimeInTests,"no-manual-memo": noManualMemo,"no-mobile-uniwind-theme-escape-hatches": noMobileUniwindThemeEscapeHatches,+ "no-ambiguous-detail-navigation": noAmbiguousDetailNavigation,"no-mobile-pull-request-glyph-literals": noMobilePullRequestGlyphLiterals,"no-native-title-tooltip": noNativeTitleTooltip,"no-outset-state-indicators": noOutsetStateIndicators,diff --git a/oxlint-plugin-t3code/rules/no-ambiguous-detail-navigation.test.ts b/oxlint-plugin-t3code/rules/no-ambiguous-detail-navigation.test.tsnew file mode 100644index 00000000000..bfa35ddff5e--- /dev/null+++ b/oxlint-plugin-t3code/rules/no-ambiguous-detail-navigation.test.ts@@ -0,0 +1,25 @@+import { describe } from "@effect/vitest";++import { createOxlintRuleHarness } from "../test/utils.ts";++const rule = createOxlintRuleHarness("t3code/no-ambiguous-detail-navigation", {+ filename: "apps/mobile/src/features/threads/ThreadFeed.tsx",+});++describe("t3code/no-ambiguous-detail-navigation", () => {+ rule.valid(+ "allows selections, explicit pushes, and other routes",+ `+ selectDetail({ name: "Thread", params });+ navigation.dispatch(StackActions.push("PullRequest", params));+ navigation.navigate("ThreadFiles", params);+ `,+ );++ rule.invalid("reports navigating to a thread", `navigation.navigate("Thread", params);`);++ rule.invalid(+ "reports a navigate action to a pull request",+ `navigation.dispatch(CommonActions.navigate("PullRequest", params));`,+ );+});diff --git a/oxlint-plugin-t3code/rules/no-ambiguous-detail-navigation.ts b/oxlint-plugin-t3code/rules/no-ambiguous-detail-navigation.tsnew file mode 100644index 00000000000..f3db23e2b11--- /dev/null+++ b/oxlint-plugin-t3code/rules/no-ambiguous-detail-navigation.ts@@ -0,0 +1,35 @@+import { defineRule, type ESTree } from "@oxlint/plugins";++const DETAIL_ROUTES = new Set(["Thread", "PullRequest"]);++const MESSAGE =+ "`navigate` to a Thread or PullRequest pushes or updates in place depending on what is on top. Use useSelectWorkspaceDetail to show it as the page, or StackActions.push to open it over the current one.";++function calleeName(callee: ESTree.Expression) {+ if (callee.type === "Identifier") return callee.name;+ if (callee.type === "MemberExpression" && callee.property.type === "Identifier") {+ return callee.property.name;+ }+ return null;+}++export default defineRule({+ meta: {+ type: "problem",+ docs: {+ description:+ "Disallow `navigate` to the workspace's detail routes; selections and drill-ins each have one explicit action.",+ },+ },+ create(context) {+ return {+ CallExpression(node) {+ if (calleeName(node.callee as ESTree.Expression) !== "navigate") return;+ const [route] = node.arguments;+ if (route?.type !== "Literal" || typeof route.value !== "string") return;+ if (!DETAIL_ROUTES.has(route.value)) return;+ context.report({ node, message: MESSAGE });+ },+ };+ },+});diff --git a/vite.config.ts b/vite.config.tsindex b8ee4011ca6..8495e43d6dc 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -435,6 +435,11 @@ export default defineConfig({],rules: { "t3code/no-mobile-pull-request-glyph-literals": "error" },},+ {+ files: ["apps/mobile/src/**"],+ excludeFiles: ["**/*.test.{ts,tsx}"],+ rules: { "t3code/no-ambiguous-detail-navigation": "error" },+ },{// Raw ResizeObserver state commits miss the paint; observeResize flushes derived layout together.files: ["apps/web/src/**"],