TypeScript
fix(mobile): unify draft and thread navigation and composer behavior (#23467)
Julius Marminge8d3b061121fe
diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swiftindex 24f653fb7d4..919902b051c 100644--- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift+++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift@@ -467,7 +467,8 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDropublic required init(appContext: AppContext? = nil) {super.init(appContext: appContext)- clipsToBounds = false+ clipsToBounds = true+ textView.clipsToBounds = truetextView.delegate = selftextView.textDropDelegate = selftextView.backgroundColor = .clear@@ -1215,28 +1216,16 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro}private func emitContentSizeIfNeeded() {- // The laid-out text without insets. A one-line draft reports its natural width, so- // JS can tell whether it fits a narrower row than the one it is laid out in; past- // one line only the height matters, so layout stops at the second line. The width- // comes from the line fragment because usedRect spans the container once the view- // scrolls. A trailing newline's empty line only exists as the extra fragment.- let layout = textView.layoutManager- let container = textView.textContainer- var lines = 0- var width: CGFloat = 0- var height: CGFloat = 0- let glyphs = NSRange(location: 0, length: layout.numberOfGlyphs)- layout.enumerateLineFragments(forGlyphRange: glyphs) { _, used, _, _, stop in- lines += 1- width = used.width- height = used.maxY- if lines > 1 { stop.pointee = true }- }- if lines < 2, layout.extraLineFragmentTextContainer === container {- lines += 1- height = max(height, layout.extraLineFragmentUsedRect.maxY)- }- let nextSize = CGSize(width: lines == 1 ? ceil(width) : 0, height: ceil(height))+ guard bounds.width > 0 else { return }+ // Fit independently of the animated viewport: when scrolling is disabled,+ // its current height can clip TextKit's laid-out line fragments.+ let fittedHeight = textView.sizeThatFits(CGSize(width: bounds.width, height: .greatestFiniteMagnitude)).height+ - textView.textContainerInset.top - textView.textContainerInset.bottom+ let measuredHeight = min(lineHeight * 4, fittedHeight)+ let width = fittedHeight <= lineHeight + 0.5+ ? textView.layoutManager.usedRect(for: textView.textContainer).width+ : 0+ let nextSize = CGSize(width: ceil(width), height: ceil(measuredHeight))guard abs(nextSize.width - lastContentSize.width) > 0.5 ||abs(nextSize.height - lastContentSize.height) > 0.5 else {returndiff --git a/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/pull-request.png b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/pull-request.pngnew file mode 100644index 00000000000..7443f8e0096Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/pull-request.png differdiff --git a/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/[email protected] b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/[email protected]new file mode 100644index 00000000000..efc4cb3a093Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/[email protected] differdiff --git a/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/[email protected] b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/[email protected]new file mode 100644index 00000000000..ee63420dba5Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/[email protected] differdiff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec b/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspecindex 29735c301cc..c32f88b0dac 100644--- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec@@ -15,5 +15,6 @@ Pod::Spec.new do |s|s.pod_target_xcconfig = {'DEFINES_MODULE' => 'YES',}+ s.resource_bundles = { 'T3NativeControlIcons' => ['Resources/Icons/pull-request*.png'] }s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}'enddiff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swiftindex 479b5fed0ce..81a892c8bec 100644--- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift@@ -32,6 +32,14 @@ public final class T3NativeControlsModule: Module {Prop("appearance") { (view: T3SegmentedControlView, value: String) in view.appearance = value }}+ View(T3SidebarTabBarView.self) {+ ViewName("SidebarTabBar")+ Events("onSelectionChange")+ Prop("selectedIndex") { (view: T3SidebarTabBarView, value: Int) in view.selectedIndex = value }+ Prop("selectedColor") { (view: T3SidebarTabBarView, value: UIColor) in view.selectedColor = value }+ Prop("appearance") { (view: T3SidebarTabBarView, value: String) in view.appearance = value }+ }+View(T3LayoutMetricsView.self) {ViewName("LayoutMetrics")Events("onMetricsChange")diff --git a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swiftnew file mode 100644index 00000000000..3bfd730facd--- /dev/null+++ b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift@@ -0,0 +1,60 @@+import ExpoModulesCore+import UIKit++final class T3SidebarTabBarView: ExpoView, UITabBarDelegate {+ let onSelectionChange = EventDispatcher()+ private let tabBar = UITabBar()+ var selectedIndex = 0 { didSet { updateSelection() } }+ var selectedColor: UIColor = .systemBlue { didSet { tabBar.tintColor = selectedColor } }+ var appearance = "light" {+ didSet { overrideUserInterfaceStyle = appearance == "dark" ? .dark : .light }+ }++ required init(appContext: AppContext? = nil) {+ super.init(appContext: appContext)+ let iconBundle = Bundle(for: Self.self).url(forResource: "T3NativeControlIcons", withExtension: "bundle").flatMap(Bundle.init(url:))+ let pullRequestIcon = UIImage(named: "pull-request", in: iconBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate)+ tabBar.items = [+ UITabBarItem(title: "Threads", image: tabIcon(UIImage(systemName: "text.bubble")), tag: 0),+ UITabBarItem(title: "Pulls", image: tabIcon(pullRequestIcon), tag: 1),+ ]+ tabBar.items?.last?.accessibilityLabel = "Pull requests"+ tabBar.items?.first?.selectedImage = tabIcon(UIImage(systemName: "text.bubble.fill"))+ tabBar.itemPositioning = .fill+ tabBar.delegate = self+ addSubview(tabBar)+ updateSelection()+ }++ override func layoutSubviews() {+ super.layoutSubviews()+ tabBar.frame = bounds+ updateSelection()+ }++ override func didMoveToWindow() {+ super.didMoveToWindow()+ updateSelection()+ }++ // Give symbols and bitmap assets the same image box; UIKit otherwise scales symbols independently.+ private func tabIcon(_ image: UIImage?) -> UIImage? {+ guard let image else { return nil }+ let canvas = CGSize(width: 28, height: 28)+ let scale = min(24 / image.size.width, 24 / image.size.height)+ let size = CGSize(width: image.size.width * scale, height: image.size.height * scale)+ return UIGraphicsImageRenderer(size: canvas).image { _ in+ image.draw(in: CGRect(x: (canvas.width - size.width) / 2, y: (canvas.height - size.height) / 2, width: size.width, height: size.height))+ }.withRenderingMode(.alwaysTemplate)+ }++ private func updateSelection() {+ guard let items = tabBar.items, items.indices.contains(selectedIndex) else { return }+ guard tabBar.selectedItem !== items[selectedIndex] else { return }+ tabBar.selectedItem = items[selectedIndex]+ }++ func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {+ onSelectionChange(["index": item.tag])+ }+}diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsxindex bfe5d1774a6..819f780ed7d 100644--- a/apps/mobile/src/App.tsx+++ b/apps/mobile/src/App.tsx@@ -6,7 +6,7 @@ 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 } from "@react-navigation/native";+import { createStaticNavigation, getStateFromPath } from "@react-navigation/native";import { RegistryContext } from "@effect/atom-react";import { ThreadArrangementHost } from "./features/threads/ThreadArrangementSheet";@@ -24,7 +24,7 @@ import { subscribeComposerDraftModelReconciliation } from "./state/use-composer-import { environmentThreadShells } from "./state/threads";import { environmentShell } from "./state/shell";import { OverlayPortalHost } from "./components/ui/OverlayPortal";-import { shouldHandleAppLink } from "./lib/appLinking";+import { shouldHandleAppLink, restoreDraftLinkState } from "./lib/appLinking";import { useMobileNavigationTheme } from "./lib/useMobileNavigationTheme";import { useUiRuntimeMemoryWarningGc } from "./lib/useUiRuntimeMemoryWarningGc";import { SubscriptionUsageCoordinator } from "./widgets/SubscriptionUsageCoordinator";@@ -44,6 +44,8 @@ const appLinking = {prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],config: { initialRouteName: "Home" },filter: shouldHandleAppLink,+ getStateFromPath: (path: string, options: Parameters<typeof getStateFromPath>[1]) =>+ restoreDraftLinkState(getStateFromPath(path, options), path),};const Navigation = createStaticNavigation(RootStack);diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsxindex 52866ae626d..d5a8a038fe4 100644--- a/apps/mobile/src/Stack.tsx+++ b/apps/mobile/src/Stack.tsx@@ -1,11 +1,9 @@+import { isDraftThreadRoute } from "./features/threads/thread-route-state";import { ComponentCatalogScreen } from "./features/development/ComponentCatalogScreen";import { PullRequestGuideStopScreen } from "./features/pull-requests/guide/PullRequestGuideScreen";import { PullRequestInlineCommentScreen } from "./features/pull-requests/PullRequestInlineCommentScreen";import { PullRequestDiscussionScreen } from "./features/pull-requests/PullRequestDiscussionScreen";-import {- createV5StackNavigator as createNativeStackNavigator,- createV5SheetStackNavigator,-} from "./native/createV5StackNavigator";+import { createV5SheetStackNavigator } from "./native/createV5StackNavigator";import { createWorkspaceStackNavigator } from "./features/layout/createWorkspaceStackNavigator";import {createPathConfigForStaticNavigation,@@ -19,14 +17,7 @@ import {type NativeStackNavigationOptions,} from "@react-navigation/native-stack";import { useEffect, useRef, type ReactNode } from "react";-import {- Platform,- Pressable,- ScrollView,- StyleSheet,- View,- useWindowDimensions,-} from "react-native";+import { Platform, Pressable, ScrollView, StyleSheet, useWindowDimensions } from "react-native";import { useResolveClassNames } from "uniwind";import { AppText as Text } from "./components/ui/AppText";@@ -82,7 +73,6 @@ import { AddProjectLocalRoute } from "./features/projects/AddProjectLocalRoute";import { AddProjectNewRoute } from "./features/projects/AddProjectNewRoute";import { AddProjectRepositoryRoute } from "./features/projects/AddProjectRepositoryRoute";import { AddProjectSourceRoute } from "./features/projects/AddProjectSourceRoute";-import { NewTaskDraftRouteScreen } from "./features/threads/NewTaskDraftRouteScreen";import {NewTaskBranchPickerRouteScreen,NewTaskEnvironmentPickerRouteScreen,@@ -461,95 +451,6 @@ const SettingsSheetStack = createV5SheetStackNavigator({// across two bars the whole screen slides).const THREAD_LINKING_PREFIX = "threads/:environmentId/:threadId";-const NewTaskSheetStack = createNativeStackNavigator({- initialRouteName: "NewTask",- screenOptions: {- ...SHEET_GLASS_HEADER_OPTIONS,- contentStyle: Platform.OS === "ios" ? { backgroundColor: "transparent" } : undefined,- // UIKit's default push adds a dimming shadow and independently transitions- // the navigation bar. Both read as mismatched sheet backgrounds here.- animation: Platform.OS === "ios" ? "simple_push" : undefined,- animationDuration: Platform.OS === "ios" ? 350 : undefined,- },- screens: {- NewTask: createNativeStackScreen({- screen: NewTaskRouteScreen,- linking: "",- options: {- title: "Choose project",- },- }),- NewTaskDraft: createNativeStackScreen({- screen: NewTaskDraftRouteScreen,- linking: "draft",- options: {- headerBackVisible: false,- title: "",- },- }),- NewTaskEnvironment: createNativeStackScreen({- screen: NewTaskEnvironmentPickerRouteScreen,- linking: "draft/environment",- options: {- title: "Environment",- },- }),- NewTaskBranch: createNativeStackScreen({- screen: NewTaskBranchPickerRouteScreen,- linking: "draft/branch",- options: {- title: "Branch",- },- }),- NewTaskFile: createNativeStackScreen({- screen: ThreadFileScreen,- linking: "draft/files/:path*",- options: SOLID_HEADER_OPTIONS,- }),- NewTaskAttachment: createNativeStackScreen({- screen: AttachmentFileScreen,- linking: "draft/attachments/:attachmentId",- options: SOLID_HEADER_OPTIONS,- }),- ThreadSettings: createNativeStackScreen({- screen: NewTaskThreadSettingsRouteScreen,- linking: "draft/settings",- options: {- gestureEnabled: true,- headerShown: false,- ...(Platform.OS === "android"- ? { presentation: "card" as const }- : {- ...THREAD_SETTINGS_SHEET_OPTIONS,- }),- },- }),- AddProject: createNativeStackScreen({- screen: AddProjectSourceRoute,- linking: "add-project",- options: {- title: "Add Project",- },- }),- AddProjectRepository: createNativeStackScreen({- screen: AddProjectRepositoryRoute,- linking: "add-project/repository",- }),- AddProjectDestination: createNativeStackScreen({- screen: AddProjectDestinationRoute,- linking: "add-project/destination",- }),- AddProjectLocal: createNativeStackScreen({- screen: AddProjectLocalRoute,- linking: "add-project/local",- }),- AddProjectNew: createNativeStackScreen({- screen: AddProjectNewRoute,- linking: "add-project/new",- }),- },-});-const WORKSPACE_OVERLAY_ROUTES = new Set(["PullRequestReview","PullRequestInlineComment",@@ -560,7 +461,18 @@ const WORKSPACE_OVERLAY_ROUTES = new Set(["GitCommit","GitConfirm","GitOverview",- "NewTaskSheet",+ "NewTaskProject",+ "NewTaskFiles",+ "NewTaskFile",+ "NewTaskAttachment",+ "NewTaskThreadSettings",+ "AddProject",+ "AddProjectRepository",+ "AddProjectDestination",+ "AddProjectLocal",+ "AddProjectNew",+ "NewTaskEnvironment",+ "NewTaskBranch","SettingsLegal","SettingsSheet","ThreadAgents",@@ -611,44 +523,58 @@ function RootStackLayout(props: {const path = getPathFromState(props.state, navigationPathConfig);const pathname = path.startsWith("/") ? path : `/${path}`;const workspaceLocation = workspaceLocationFromState(props.state);+ const draftRoute = props.state.routes.findLast((route) => route.name === "Thread");+ const draftParams = (+ draftRoute?.params as+ | { draft?: { draftId?: string | string[]; pendingTaskId?: string | string[] } }+ | undefined+ )?.draft;+ const routeDraftId = Array.isArray(draftParams?.draftId)+ ? draftParams.draftId[0]+ : draftParams?.draftId;+ const routePendingTaskId = Array.isArray(draftParams?.pendingTaskId)+ ? draftParams.pendingTaskId[0]+ : draftParams?.pendingTaskId;useAgentNotificationNavigation(workspaceLocation.pathname);useConnectOnboardingNavigation();useAppShortcuts(props.state);useEffect(() => {- const topRouteName = props.state.routes[props.state.index]?.name;const transition = transitionIncomingSharePresentation(sharePresentationRef.current, {- isShareSheetPresented: topRouteName === "NewTaskSheet",+ isShareSheetPresented: isDraftThreadRoute(props.state.routes[props.state.index]),pendingShareId: pendingShare?.id ?? null,});sharePresentationRef.current = transition.state;if (!transition.shareIdToPresent) {return;}- navigation.navigate("NewTaskSheet", {- screen: "NewTask",- params: { incomingShareId: transition.shareIdToPresent },- });+ navigation.navigate("Thread", { draft: { incomingShareId: transition.shareIdToPresent } });}, [navigation, pendingShare, props.state]);return (- <HardwareKeyboardCommandProvider pathname={pathname}>- <ThreadOutboxDrainWorker />- <ShowcaseCaptureCoordinator pathname={pathname} />- <ExistingThreadSettingsRouteProvider>- <WorkspaceConnectionStatusProvider>- <AndroidWorkspaceTabsProvider state={props.state}>- <AdaptiveWorkspaceLayout- pathname={workspaceLocation.pathname}- workspaceRouteKey={workspaceLocation.routeKey}- selectedPullRequestKey={selectedPullRequestKey(props.state)}- >- {props.children}- <HardwareKeyboardCommandOverlay />- </AdaptiveWorkspaceLayout>- </AndroidWorkspaceTabsProvider>- </WorkspaceConnectionStatusProvider>- </ExistingThreadSettingsRouteProvider>- </HardwareKeyboardCommandProvider>+ <NewTaskFlowProvider+ active={isDraftThreadRoute(draftRoute)}+ routeDraftId={routeDraftId}+ routePendingTaskId={routePendingTaskId}+ >+ <HardwareKeyboardCommandProvider pathname={pathname}>+ <ThreadOutboxDrainWorker />+ <ShowcaseCaptureCoordinator pathname={pathname} />+ <ExistingThreadSettingsRouteProvider>+ <WorkspaceConnectionStatusProvider>+ <AndroidWorkspaceTabsProvider state={props.state}>+ <AdaptiveWorkspaceLayout+ pathname={workspaceLocation.pathname}+ workspaceRouteKey={workspaceLocation.routeKey}+ selectedPullRequestKey={selectedPullRequestKey(props.state)}+ >+ {props.children}+ <HardwareKeyboardCommandOverlay />+ </AdaptiveWorkspaceLayout>+ </AndroidWorkspaceTabsProvider>+ </WorkspaceConnectionStatusProvider>+ </ExistingThreadSettingsRouteProvider>+ </HardwareKeyboardCommandProvider>+ </NewTaskFlowProvider>);}@@ -780,9 +706,79 @@ const RootStackConfig = createWorkspaceStackNavigator({}),Thread: createNativeStackScreen({screen: ThreadRouteScreen,- linking: THREAD_LINKING_PREFIX,+ linking: { path: "threads/:environmentId?/:threadId?", alias: ["new/draft"] },options: DETAIL_HEADER_OPTIONS,}),+ NewTaskProject: createNativeStackScreen({+ screen: NewTaskRouteScreen,+ linking: { path: "new", alias: ["new/project"] },+ options: { ...GLASS_HEADER_OPTIONS, title: "Choose project" },+ }),+ NewTaskEnvironment: createNativeStackScreen({+ linking: "new/draft/environment",+ screen: NewTaskEnvironmentPickerRouteScreen,+ options: { ...GLASS_HEADER_OPTIONS, title: "Environment" },+ }),+ NewTaskBranch: createNativeStackScreen({+ linking: "new/draft/branch",+ screen: NewTaskBranchPickerRouteScreen,+ options: { ...GLASS_HEADER_OPTIONS, title: "Branch" },+ }),+ AddProject: createNativeStackScreen({+ linking: "new/add-project",+ screen: AddProjectSourceRoute,++ options: {+ ...GLASS_HEADER_OPTIONS,+ title: "Add project",+ },+ }),+ AddProjectRepository: createNativeStackScreen({+ linking: "new/add-project/repository",+ screen: AddProjectRepositoryRoute,+ options: GLASS_HEADER_OPTIONS,+ }),+ AddProjectDestination: createNativeStackScreen({+ linking: "new/add-project/destination",+ screen: AddProjectDestinationRoute,+ options: GLASS_HEADER_OPTIONS,+ }),+ AddProjectLocal: createNativeStackScreen({+ linking: "new/add-project/local",+ screen: AddProjectLocalRoute,+ options: GLASS_HEADER_OPTIONS,+ }),+ AddProjectNew: createNativeStackScreen({+ linking: "new/add-project/new",+ screen: AddProjectNewRoute,+ options: GLASS_HEADER_OPTIONS,+ }),+ NewTaskFiles: createNativeStackScreen({+ linking: "new/draft/files",+ screen: ThreadFilesTreeScreen,+ options: SOLID_HEADER_OPTIONS,+ }),+ NewTaskFile: createNativeStackScreen({+ linking: "new/draft/files/:path*",+ screen: ThreadFileScreen,+ options: SOLID_HEADER_OPTIONS,+ }),+ NewTaskAttachment: createNativeStackScreen({+ screen: AttachmentFileScreen,+ linking: "new/draft/attachments/:attachmentId",+ options: SOLID_HEADER_OPTIONS,+ }),+ NewTaskThreadSettings: createNativeStackScreen({+ screen: NewTaskThreadSettingsRouteScreen,+ linking: "new/draft/settings",+ options: {+ gestureEnabled: true,+ headerShown: false,+ ...(Platform.OS === "android"+ ? { presentation: "card" as const }+ : THREAD_SETTINGS_SHEET_OPTIONS),+ },+ }),ThreadTerminal: createNativeStackScreen({screen: ThreadTerminalRouteScreen,linking: `${THREAD_LINKING_PREFIX}/terminal`,@@ -1002,24 +998,6 @@ const RootStackConfig = createWorkspaceStackNavigator({sheetGrabberVisible: true,},}),- NewTaskSheet: createNativeStackScreen({- screen: NewTaskSheetStack,- linking: "new",- // A screen's layout replaces the navigator's screenLayout.- layout: ({ children, route }) => (- <GuardedScreenLayout route={route}>- <NewTaskFlowProvider>- <View className="flex-1 bg-sheet-solid">{children}</View>- </NewTaskFlowProvider>- </GuardedScreenLayout>- ),- options: {- ...NESTED_NAVIGATOR_OPTIONS,- sheetPrefersHorizontalBars: true,- gestureEnabled: true,- headerShown: false,- },- }),NotFound: createNativeStackScreen({screen: NotFoundScreen,linking: "*",@@ -1073,14 +1051,14 @@ export const RootStack = RootStackConfig.with(function AdaptiveRootStack({ Navig},}}screenOptions={({ route }) => {- if (route.name !== "SettingsSheet" && route.name !== "NewTaskSheet") {+ if (route.name !== "SettingsSheet") {return Platform.OS === "android"? { animation: androidWorkspaceDestinationAnimation(route.name, usesSplitView) }: {};}// Moving an open flow between a sheet and a split column remounts its nested- // navigator. Keep its presentation until dismissal so folding preserves the draft.+ // navigator. Keep its presentation until dismissal so folding preserves the settings flow.let usesCard = flowPresentations.current.get(route.key);if (usesCard === undefined) {usesCard = usesWorkspaceFlowScreens;diff --git a/apps/mobile/src/components/ComposerAttachmentStrip.tsx b/apps/mobile/src/components/ComposerAttachmentStrip.tsxindex 9cd2d85cef5..ebbfbe98814 100644--- a/apps/mobile/src/components/ComposerAttachmentStrip.tsx+++ b/apps/mobile/src/components/ComposerAttachmentStrip.tsx@@ -347,6 +347,8 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {onPressDocument={props.onPressDocument}/><Pressable+ accessibilityRole="button"+ accessibilityLabel={`Remove ${attachment.name}`}className="absolute h-[22px] w-[22px] items-center justify-center rounded-[11px] bg-black/55"style={{top: removeButtonPlacement === "gutter" ? 0 : 4,diff --git a/apps/mobile/src/components/ComposerModelControl.tsx b/apps/mobile/src/components/ComposerModelControl.tsxindex d528186406c..431cf61b1ec 100644--- a/apps/mobile/src/components/ComposerModelControl.tsx+++ b/apps/mobile/src/components/ComposerModelControl.tsx@@ -17,8 +17,8 @@ export function ComposerModelControl(props: {readonly prompt: string;readonly surfaceColor: string;readonly disabled?: boolean;+ readonly size?: "regular" | "large";readonly iconOnly?: boolean;- readonly showSummary?: boolean;readonly onPress: () => void;}) {const descriptors = resolveProviderOptionDescriptors({@@ -48,6 +48,7 @@ export function ComposerModelControl(props: {].filter(Boolean).join(", ")}+ size={props.size}disabled={props.disabled}emphasizedrenderIcon={(size) =>@@ -72,8 +73,15 @@ export function ComposerModelControl(props: {label={label}iconOnly={props.iconOnly}suffix={- props.showSummary !== false && summary ? (- <Text className="text-xs text-foreground-muted" numberOfLines={1}>+ summary ? (+ <Text+ className={+ props.size === "large"+ ? "text-sm text-foreground-muted"+ : "text-xs text-foreground-muted"+ }+ numberOfLines={1}+ >{summary}</Text>) : undefineddiff --git a/apps/mobile/src/components/ComposerToolbar.tsx b/apps/mobile/src/components/ComposerToolbar.tsxindex f8e3c1447f0..74708eff8d8 100644--- a/apps/mobile/src/components/ComposerToolbar.tsx+++ b/apps/mobile/src/components/ComposerToolbar.tsx@@ -1,7 +1,6 @@import type { ComponentProps, ReactNode } from "react";import { useCallback, useMemo, useState } from "react";import {- Platform,Pressable,ScrollView,View,@@ -13,7 +12,7 @@ import {type ViewStyle,} from "react-native";-import Animated, { FadeIn, LinearTransition } from "react-native-reanimated";+import Animated, { FadeIn } from "react-native-reanimated";import { cn } from "../lib/cn";import { AppText as Text } from "./ui/AppText";@@ -24,11 +23,8 @@ const COMPOSER_TOOLBAR_GAP = 8;const COMPOSER_TOOLBAR_FADE_WIDTH = 18;const COMPOSER_TOOLBAR_SCROLL_EPSILON = 4;const INLINE_CONTROL_LABEL_ENTERING = FadeIn.duration(160);-// Android runs no composer layout transitions, so the toolbar never trails the dock.-const INLINE_CONTROL_WIDTH_TRANSITION =- Platform.OS === "android" ? undefined : LinearTransition.duration(180);-export function ComposerInlineControl(props: {+ readonly size?: "regular" | "large";readonly accessibilityHint?: string;readonly accessibilityLabel?: string;readonly disabled?: boolean;@@ -47,13 +43,11 @@ export function ComposerInlineControl(props: {readonly showChevron?: boolean;}) {const { scale, smallIconSize } = useAndroidControlSizing();- // The label fades in as the control widens, and leaves at once: an exiting view keeps- // drawing at its old place while the chevron moves into it. The clip keeps content laid out- // at the final width inside the frame while it eases there.+ // Keep the picker anchored to its parent while the editor changes height.const animatesLabel = props.iconOnly !== undefined;+ const iconSize = props.size === "large" ? 20 : smallIconSize;return (<Animated.View- layout={animatesLabel ? INLINE_CONTROL_WIDTH_TRANSITION : undefined}style={{maxWidth: props.maxWidth ?? 190,overflow: animatesLabel ? "hidden" : undefined,@@ -66,7 +60,7 @@ export function ComposerInlineControl(props: {accessibilityState={props.static ? undefined : { disabled: props.disabled, selected: props.selected }}- className="h-11 flex-row items-center gap-2 rounded-xl px-2 active:bg-subtle"+ className="h-[44px] flex-row items-center gap-2 rounded-xl px-2 active:bg-subtle"disabled={props.disabled || props.static}onPress={props.onPress}style={{ opacity: props.disabled ? 0.45 : 1 }}@@ -74,16 +68,14 @@ export function ComposerInlineControl(props: {{props.renderIcon ? (<ViewclassName="size-4 shrink-0 items-center justify-center"- style={- Platform.OS === "android" ? { width: 14 * scale, height: 14 * scale } : undefined- }+ style={{ width: iconSize, height: iconSize }}>- {props.renderIcon(smallIconSize)}+ {props.renderIcon(iconSize)}</View>) : props.icon ? (<SymbolViewname={props.icon}- size={smallIconSize}+ size={iconSize}tintColorClassName={props.emphasized || props.selected ? "accent-icon" : "accent-icon-muted"}@@ -97,7 +89,7 @@ export function ComposerInlineControl(props: {><TextclassName={cn(- "text-sm font-t3-medium",+ props.size === "large" ? "text-base font-t3-medium" : "text-sm font-t3-medium",props.emphasized || props.selected ? "text-foreground" : "text-foreground-muted",)}numberOfLines={1}@@ -112,7 +104,7 @@ export function ComposerInlineControl(props: {{props.showChevron === false ? null : (<SymbolViewname={props.chevronDirection === "right" ? "chevron.right" : "chevron.down"}- size={Math.round(10 * scale)}+ size={Math.round((props.size === "large" ? 12 : 10) * scale)}tintColorClassName={props.emphasized || props.selected ? "accent-icon" : "accent-icon-muted"}@@ -252,6 +244,7 @@ export function ComposerToolbarScroller(props: {}export function ComposerActionButton(props: {+ readonly size?: "regular" | "large";readonly accessibilityLabel: string;readonly disabled?: boolean;readonly icon: ComponentProps<typeof SymbolView>["name"];@@ -263,13 +256,14 @@ export function ComposerActionButton(props: {readonly onTouchStart?: PressableProps["onTouchStart"];}) {const { scale, smallIconSize } = useAndroidControlSizing();- const circleSize = Math.round(30 * scale);+ const circleSize = Math.round((props.size === "large" ? 44 : 30) * scale);return (<PressableaccessibilityLabel={props.accessibilityLabel}accessibilityRole="button"accessibilityState={{ disabled: props.disabled }}className="size-[44px] shrink-0 items-center justify-center active:opacity-70"+ style={props.size === "large" ? { width: 62 } : undefined}disabled={props.disabled}onPress={props.onPress}onLongPress={props.onLongPress}@@ -288,7 +282,7 @@ export function ComposerActionButton(props: {><SymbolViewname={props.icon}- size={smallIconSize}+ size={props.size === "large" ? Math.round(20 * scale) : smallIconSize}weight="semibold"tintColorClassName={props.variant === "danger" ? "accent-danger-foreground" : "accent-primary-foreground"diff --git a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsxindex 82de8974654..9ef668a9fa1 100644--- a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx+++ b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx@@ -337,7 +337,9 @@ function FileContent(props: {type ThreadFilesRouteScreenProps = StaticScreenProps<{readonly environmentId: string;- readonly threadId: string;+ readonly threadId?: string;+ readonly cwd?: string;+ readonly projectName?: string;}>;type ThreadFileRouteScreenProps = StaticScreenProps<{@@ -430,6 +432,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(props.route.params,);+ const hasFileInspector = fileInspector.supported && threadId !== null;const revealedInspectorRef = useRef(false);const fileAccessSession = useEnvironmentQuery(environmentId !== null ? environmentSession.sessionStateAtom(environmentId) : null,@@ -444,7 +447,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {const { canReadFiles } = fileAccess;const entriesQuery = useFileTreeEntries({environmentId,- cwd: !canReadFiles || fileInspector.supported ? null : cwd,+ cwd: !canReadFiles || hasFileInspector ? null : cwd,searchQuery,});const handleReturnToThread = () => {@@ -463,16 +466,20 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {};const handleSelectFile = (path: string) => {- if (environmentId === null || threadId === null) {+ if (environmentId === null || cwd === null) {return;}const params = {environmentId: String(environmentId),- threadId: String(threadId),+ ...(threadId === null ? { cwd, projectName } : { threadId: String(threadId) }),path: path.split("/").filter((segment) => segment.length > 0),};+ if (threadId === null) {+ navigation.navigate("NewTaskFile", params);+ return;+ }const navigationAction = resolveFileSelectionNavigationAction({- hasPersistentFileInspector: fileInspector.supported,+ hasPersistentFileInspector: hasFileInspector,});if (navigationAction === "replace") {navigation.dispatch(StackActions.replace("ThreadFile", params));@@ -503,14 +510,14 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {});};useEffect(() => {- if (fileInspector.supported && cwd !== null && !revealedInspectorRef.current) {+ if (hasFileInspector && cwd !== null && !revealedInspectorRef.current) {revealedInspectorRef.current = true;showAuxiliaryPane("inspector");}- }, [cwd, fileInspector.supported, showAuxiliaryPane]);+ }, [cwd, hasFileInspector, showAuxiliaryPane]);- if (selectedThread === null || environmentId === null || threadId === null) {- if (fileInspector.supported) {+ if (environmentId === null || (threadId !== null && selectedThread === null)) {+ if (hasFileInspector) {return (<ThreadRouteScreenonReturnToThread={handleReturnToThread}@@ -534,7 +541,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {return <FilesUnavailable />;}- if (fileInspector.supported) {+ if (hasFileInspector) {return (<ThreadRouteScreenonReturnToThread={handleReturnToThread}diff --git a/apps/mobile/src/features/home/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsxindex c0e2b8c8f59..494966d886f 100644--- a/apps/mobile/src/features/home/HomeRouteScreen.tsx+++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx@@ -1,3 +1,4 @@+import { uuidv4 } from "../../lib/uuid";import { ThreadUndoNotice } from "./ThreadUndoNotice";import { Toolbar } from "../../components/ui/Toolbar";import { use } from "react";@@ -27,7 +28,7 @@ import { HomeScreen } from "./HomeScreen";import { HomeHeader } from "./HomeHeader";import { useHomeListOptions } from "./home-list-options";import { useAtomValueWhileVisible, useHomeRouteVisible } from "./home-route-visibility";-import { useHomeThreadSelection } from "./home-thread-navigation";+import { useHomeThreadRouteSelection, useHomeThreadSelection } from "./home-thread-navigation";import { buildHomeProjectScopes } from "./homeThreadList";import { usePendingTaskListActions } from "./usePendingTaskListActions";import { useThreadListActions } from "./useThreadListActions";@@ -40,7 +41,7 @@ export function HomeRouteScreen() {const columnMetrics = useNativeColumnLayoutMetrics();const deviceType = useDeviceType();const headerWidth = nativePrimaryColumn ? (columnMetrics?.width ?? windowWidth) : windowWidth;- const { layout, panes, primarySidebarSearchQuery, setPrimarySidebarSearchQuery } =+ const { layout, panes, primarySidebarSearchQuery, setPrimarySidebarSearchQuery, startNewTask } =useAdaptiveWorkspaceLayout();const projects = useProjects();// Streaming turns rewrite thread shells many times a second. While a Thread@@ -65,11 +66,12 @@ export function HomeRouteScreen() {else setLocalSearchQuery(query);};const handleSelectThread = useHomeThreadSelection();+ const selectThreadRoute = useHomeThreadRouteSelection();const handleNewThreadOnBranch = useCallback((thread: EnvironmentThreadShell) => {- navigation.navigate("NewTaskSheet", {- screen: "NewTaskDraft",- params: {+ selectThreadRoute({+ draft: {+ requestId: uuidv4(),environmentId: String(thread.environmentId),projectId: String(thread.projectId),branch: thread.branch,@@ -77,7 +79,7 @@ export function HomeRouteScreen() {},});},- [navigation],+ [selectThreadRoute],);useEffect(() => {@@ -177,7 +179,7 @@ export function HomeRouteScreen() {<Toolbar.ButtonaccessibilityLabel="New task"icon="square.and.pencil"- onPress={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}+ onPress={startNewTask}/></Toolbar>) : null}@@ -193,9 +195,7 @@ export function HomeRouteScreen() {: undefined}onStartNewTask={- Platform.OS === "android" && panes.primarySidebarVisible- ? undefined- : () => navigation.navigate("NewTaskSheet", { screen: "NewTask" })+ Platform.OS === "android" && panes.primarySidebarVisible ? undefined : startNewTask}/></>@@ -205,7 +205,7 @@ export function HomeRouteScreen() {return (<AndroidHomeFabLayoutdisabled={workspace !== null && Platform.OS !== "android"}- onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}+ onStartNewTask={startNewTask}><>{/* Restore the header after leaving split view; screen options are@@ -248,7 +248,7 @@ export function HomeRouteScreen() {})}onSearchQueryChange={setSearchQuery}- onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}+ onStartNewTask={startNewTask}/><HomeScreen@@ -286,16 +286,16 @@ export function HomeRouteScreen() {onDeletePendingTask={confirmDeletePendingTask}onNewThreadOnBranch={handleNewThreadOnBranch}onNewThreadInProject={(project) => {- navigation.navigate("NewTaskSheet", {- screen: "NewTaskDraft",- params: {+ selectThreadRoute({+ draft: {+ requestId: uuidv4(),environmentId: String(project.environmentId),projectId: String(project.id),title: project.title,},});}}- onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}+ onStartNewTask={startNewTask}pendingTasks={pendingTasks}projectGroupingMode={listOptions.projectGroupingMode}projects={projects}diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsxindex e8a9ac35e34..389054aa103 100644--- a/apps/mobile/src/features/home/HomeScreen.tsx+++ b/apps/mobile/src/features/home/HomeScreen.tsx@@ -1,8 +1,11 @@+import { useActiveNewTask } from "../../state/active-new-task";import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";import type { ThreadMoveDestination } from "../threads/threadOrder";import { computeThreadMoveAvailability } from "../threads/threadOrder";-import { LegendList, type LegendListRef } from "@legendapp/list/react-native";+import type { LegendListRef } from "@legendapp/list/react-native";+import { AnimatedLegendList } from "@legendapp/list/reanimated";+import { THREAD_SIDEBAR_ROW_LAYOUT } from "../threads/threadListAnimations";import {type EnvironmentProject,type EnvironmentThreadShell,@@ -262,7 +265,8 @@ export function HomeScreen(props: HomeScreenProps) {Platform.OS === "android" ? "bg-header" : contentBackground,);const columnMetrics = useNativeColumnLayoutMetrics();- const selectedThreadKey = primaryColumn?.selectedThreadKey ?? null;+ const activeNewTask = useActiveNewTask();+ const selectedThreadKey = activeNewTask ? null : (primaryColumn?.selectedThreadKey ?? null);const fullSwipeWidth = primaryColumn && columnMetrics ? columnMetrics.width - 20 : undefined;const queuedThreadKeys = useQueuedThreadKeys();const openSwipeableRef = useRef<SwipeableMethods | null>(null);@@ -579,7 +583,14 @@ export function HomeScreen(props: HomeScreenProps) {);return (<ThreadListV2PendingRow+ pane={primaryColumn ? "sidebar" : "screen"}pendingTask={item.pendingTask}+ selected={+ activeNewTask?.pendingKey === item.pendingTask.key ||+ (item.pendingTask.kind === "pending" &&+ scopedThreadKey(item.pendingTask.environmentId, item.pendingTask.message.threadId) ===+ selectedThreadKey)+ }project={projectByKey.get(pendingScopeKey) ?? null}projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}environmentLabel={@@ -707,6 +718,7 @@ export function HomeScreen(props: HomeScreenProps) {// every HomeScreen render — and the minute clock must stay out of it for// the same reason: the clock text is precomputed per item instead.const v2ExtraData = {+ activeNewTask,projectByKey,projectTitleByProjectKey: v2ProjectTitleByProjectKey,listEnvironments,@@ -844,7 +856,8 @@ export function HomeScreen(props: HomeScreenProps) {><SwipeableScrollGateProvider enabled={swipeEnabled} activation={swipeRowActivation}><GestureDetector gesture={homeScrollGesture}>- <LegendList+ <AnimatedLegendList+ itemLayoutAnimation={primaryColumn ? THREAD_SIDEBAR_ROW_LAYOUT : undefined}ref={listRef}onLoad={() => activateVisibleRows(threadListV2Items)}onTouchStart={(event) => trackListTouches(event, true)}diff --git a/apps/mobile/src/features/home/home-thread-navigation.test.ts b/apps/mobile/src/features/home/home-thread-navigation.test.tsindex 3f2b4a4fee4..820a6666505 100644--- a/apps/mobile/src/features/home/home-thread-navigation.test.ts+++ b/apps/mobile/src/features/home/home-thread-navigation.test.ts@@ -26,7 +26,10 @@ vi.mock("@react-navigation/native", () => {return { CommonActions, StackActions };});-import { createHomeThreadNavigationAction } from "./home-thread-navigation";+import {+ createHomeThreadRouteAction,+ createHomeThreadNavigationAction,+} from "./home-thread-navigation";const { StackActions, StackRouter } = loadRouters();const routeNames = ["Home", "Thread"];@@ -196,3 +199,36 @@ describe("createHomeThreadNavigationAction", () => {});});});++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.tsindex 317b6805915..94948bb8f5a 100644--- a/apps/mobile/src/features/home/home-thread-navigation.ts+++ b/apps/mobile/src/features/home/home-thread-navigation.ts@@ -12,27 +12,44 @@ import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSetype ThreadSelection = Pick<EnvironmentThreadShell, "environmentId" | "id">;-export function createHomeThreadNavigationAction(input: {+export function createHomeThreadRouteAction(input: {readonly state: Pick<NavigationState, "index" | "routes">;readonly dismissingRouteKey: string | null;- readonly thread: ThreadSelection;+ readonly params: ReactNavigation.RootParamList["Thread"];}) {const currentRoute = input.state.routes[input.state.index];- const params = {- environmentId: input.thread.environmentId,- threadId: input.thread.id,- };-- // Native swipe-back pops the outgoing route after its animation. Reusing- // that key would also discard this selection when the dismissal arrives.if (input.dismissingRouteKey !== null && currentRoute?.key === input.dismissingRouteKey) {- return StackActions.push("Thread", params);+ 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);+}- return CommonActions.navigate("Thread", 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 useHomeThreadSelection() {+export function useHomeThreadRouteSelection() {const navigation =useNavigation<NativeStackNavigationProp<ReactNavigation.RootParamList, "Home">>();const dismissingRouteKey = useRef<string | null>(null);@@ -60,22 +77,31 @@ export function useHomeThreadSelection() {}, [navigation]);return useCallback(- (thread: ThreadSelection) => {+ (params: ReactNavigation.RootParamList["Thread"]) => {if (Platform.OS === "android") {selectAndroidWorkspace({name: "Thread",- params: { environmentId: String(thread.environmentId), threadId: String(thread.id) },+ params,});return;}navigation.dispatch((state) =>- createHomeThreadNavigationAction({+ createHomeThreadRouteAction({state,dismissingRouteKey: dismissingRouteKey.current,- thread,+ params,}),);},[navigation, selectAndroidWorkspace],);}++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 ff3572811cc..5e058090a65 100644--- a/apps/mobile/src/features/home/usePendingTaskListActions.ts+++ b/apps/mobile/src/features/home/usePendingTaskListActions.ts@@ -1,5 +1,5 @@import * as Dialog from "../../components/ui/Dialog";-import { useNavigation } from "@react-navigation/native";+import { useHomeThreadRouteSelection } from "./home-thread-navigation";import { useCallback } from "react";import { removeThreadOutboxMessage } from "../../state/thread-outbox-removal";@@ -13,26 +13,33 @@ import {} from "../../state/use-thread-outbox";import { withThreadDismissal } from "./thread-dismissal";-export function usePendingTaskListActions(): {+export function usePendingTaskListActions(+ selectRoute?: (params: ReactNavigation.RootParamList["Thread"]) => void,+): {readonly openPendingTask: (pendingTask: PendingNewTask) => void;readonly confirmDeletePendingTask: (pendingTask: PendingNewTask) => void;} {- const navigation = useNavigation();+ const selectHomeRoute = useHomeThreadRouteSelection();+ const selectThreadRoute = selectRoute ?? selectHomeRoute;const openPendingTask = useCallback((pendingTask: PendingNewTask) => {- navigation.navigate("NewTaskSheet", {- screen: "NewTaskDraft",- params: {- environmentId: String(pendingTask.environmentId),- projectId: String(pendingTask.projectId),- ...(pendingTask.kind === "pending"- ? { pendingTaskId: String(pendingTask.message.messageId) }- : { draftId: pendingTask.draftKey }),- },- });+ selectThreadRoute(+ pendingTask.kind === "pending"+ ? {+ environmentId: String(pendingTask.environmentId),+ threadId: String(pendingTask.message.threadId),+ }+ : {+ draft: {+ environmentId: String(pendingTask.environmentId),+ projectId: String(pendingTask.projectId),+ draftId: pendingTask.draftKey,+ },+ },+ );},- [navigation],+ [selectThreadRoute],);const confirmDeletePendingTask = useCallback((pendingTask: PendingNewTask) => {diff --git a/apps/mobile/src/features/keyboard/CommandPalette.tsx b/apps/mobile/src/features/keyboard/CommandPalette.tsxindex 3c3fd349c20..c70062ab04c 100644--- a/apps/mobile/src/features/keyboard/CommandPalette.tsx+++ b/apps/mobile/src/features/keyboard/CommandPalette.tsx@@ -1,3 +1,4 @@+import { uuidv4 } from "../../lib/uuid";import { useNavigation } from "@react-navigation/native";import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";import { THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts";@@ -142,7 +143,7 @@ export function CommandPalette(props: {}) {const navigation = useNavigation();const { themeVariables } = useAppearancePreferences();- const { selectThread } = useAdaptiveWorkspaceLayout();+ const { selectThread, selectThreadRoute } = useAdaptiveWorkspaceLayout();const runCommand = props.onCommand;const projects = useProjects();const threads = useThreadShells();@@ -190,14 +191,14 @@ export function CommandPalette(props: {kind: "action",title: "New thread in…",searchTerms: ["new task", "chat", "create", "project"],- run: () => navigation.navigate("NewTaskSheet", { screen: "NewTask" }),+ run: () => runCommand("newTask"),},{key: "addProject",kind: "action",title: "Add project",searchTerms: ["folder", "clone", "repository", "git"],- run: () => navigation.navigate("NewTaskSheet", { screen: "AddProject" }),+ run: () => navigation.navigate("AddProject"),},{key: "settings",@@ -279,9 +280,9 @@ export function CommandPalette(props: {title: `New thread in ${activeProject.title}`,searchTerms: ["new task", "chat", "create"],run: () =>- navigation.navigate("NewTaskSheet", {- screen: "NewTaskDraft",- params: {+ selectThreadRoute({+ draft: {+ requestId: uuidv4(),environmentId: activeProject.environmentId,projectId: activeProject.id,title: activeProject.title,@@ -313,9 +314,9 @@ export function CommandPalette(props: {detail: `New thread · ${savedConnectionsById[project.environmentId]?.environmentLabel ?? project.environmentId}`,searchTerms: [project.workspaceRoot, "new thread", "project"],run: () =>- navigation.navigate("NewTaskSheet", {- screen: "NewTaskDraft",- params: {+ selectThreadRoute({+ draft: {+ requestId: uuidv4(),environmentId: project.environmentId,projectId: project.id,title: project.title,@@ -356,6 +357,7 @@ export function CommandPalette(props: {runCommand,savedConnectionsById,selectThread,+ selectThreadRoute,threads,]);const results = useMemo(diff --git a/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx b/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsxindex 8a6aa14dbdd..ada99e15696 100644--- a/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx+++ b/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx@@ -148,7 +148,7 @@ export function HardwareKeyboardCommandProvider({}if (command === "newTask") {- navigation.navigate("NewTaskSheet", { screen: "NewTask" });+ navigation.navigate("Thread", { draft: {} });return;}if (command === "back") {diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsxindex 07e70f448a7..bec83816b58 100644--- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx+++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx@@ -1,3 +1,5 @@+import { createDeferredNavigation } from "./deferred-navigation";+import { uuidv4 } from "../../lib/uuid";import type {EnvironmentProject,EnvironmentThreadShell,@@ -52,6 +54,9 @@ import {} from "../../lib/adaptive-navigation";import { scopedThreadKey } from "../../lib/scopedEntities";import type { ThreadListFilters } from "../../persistence/mobile-preferences";+import { appAtomRegistry } from "../../state/atom-registry";+import { useProjects } from "../../state/entities";+import { environmentThreadShells } from "../../state/threads";import { mobilePreferencesAtom } from "../../state/preferences";import {DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS,@@ -69,6 +74,7 @@ import {import { AndroidWorkspaceSidebar } from "../workspace/AndroidWorkspaceSidebar";import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSelection";import { HomeListOptionsProvider } from "../home/home-list-options";+import { newTaskDestination } from "../threads/new-task-project-selection";import { usePendingTaskListActions } from "../home/usePendingTaskListActions";import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";import { useOpenThreadPullRequests } from "../threads/use-open-thread-pull-requests";@@ -93,7 +99,10 @@ interface AdaptiveWorkspaceContextValue {readonly panes: WorkspacePaneLayout;readonly fileInspector: FileInspectorPaneLayout;readonly primarySidebarSearchQuery: string;+ readonly startNewTask: () => void;+ readonly deferThreadSelectionUntil: (operation: Promise<unknown>) => void;readonly selectThread: (thread: EnvironmentThreadShell) => void;+ readonly selectThreadRoute: (params: ReactNavigation.RootParamList["Thread"]) => void;readonly activateAuxiliaryPaneRole: (role: WorkspaceAuxiliaryPaneRole) => () => void;readonly registerWorkspaceInspector: (render: () => ReactNode) => () => void;readonly setPrimarySidebarSearchQuery: (query: string) => void;@@ -126,7 +135,10 @@ const AdaptiveWorkspaceContext = createContext<AdaptiveWorkspaceContextValue>({panes: compactPanes,fileInspector: compactFileInspector,primarySidebarSearchQuery: "",+ startNewTask: () => undefined,+ deferThreadSelectionUntil: () => undefined,selectThread: () => undefined,+ selectThreadRoute: () => undefined,activateAuxiliaryPaneRole: () => () => undefined,registerWorkspaceInspector: () => () => undefined,setPrimarySidebarSearchQuery: () => undefined,@@ -485,10 +497,94 @@ function AdaptiveWorkspaceLayoutContent(});};+ 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") {+ 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 (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 projects = useProjects();const handleStartNewTask = () => {- navigation.navigate("NewTaskSheet", { screen: "NewTask" });+ 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 =+ currentRoute?.name === "Thread"+ ? (currentRoute.params as ReactNavigation.RootParamList["Thread"])?.draft+ : undefined;+ const first = (value: string | string[] | undefined) =>+ Array.isArray(value) ? value[0] : value;+ const draftEnvironmentId = first(draft?.environmentId);+ const draftProjectId = first(draft?.projectId);+ const currentProject = thread+ ? { environmentId: thread.environmentId, id: thread.projectId }+ : projects.find(+ (project) =>+ project.environmentId === draftEnvironmentId && project.id === draftProjectId,+ );+ handleSelectThreadRoute(+ newTaskDestination(layout.usesSplitView, projects, currentProject, uuidv4()),+ );};+ useHardwareKeyboardCommand("newTask", () => {+ handleStartNewTask();+ return true;+ });+// Minted here (root stack navigation) so the sidebar pane stays free of// navigation hooks — on iOS it renders inside an independent nav tree.const handleOpenEnvironmentSettings = () => {@@ -499,12 +595,13 @@ function AdaptiveWorkspaceLayoutContent(};const handleOpenThreadPullRequests = useOpenThreadPullRequests();- const { openPendingTask: handleOpenPendingTask } = usePendingTaskListActions();+ const { openPendingTask: handleOpenPendingTask } =+ usePendingTaskListActions(handleSelectThreadRoute);const handleNewThreadOnBranch = (thread: EnvironmentThreadShell) => {- navigation.navigate("NewTaskSheet", {- screen: "NewTaskDraft",- params: {+ handleSelectThreadRoute({+ draft: {+ requestId: uuidv4(),environmentId: String(thread.environmentId),projectId: String(thread.projectId),branch: thread.branch,@@ -514,9 +611,9 @@ function AdaptiveWorkspaceLayoutContent(};const handleNewThreadInProject = (project: EnvironmentProject) => {- navigation.navigate("NewTaskSheet", {- screen: "NewTaskDraft",- params: {+ handleSelectThreadRoute({+ draft: {+ requestId: uuidv4(),environmentId: String(project.environmentId),projectId: String(project.id),title: project.title,@@ -684,47 +781,11 @@ function AdaptiveWorkspaceLayoutContent(),);- const selectAndroidWorkspace = useAndroidWorkspaceSelection();const handleSelectThread = (thread: EnvironmentThreadShell) => {- const params = {+ handleSelectThreadRoute({environmentId: String(thread.environmentId),threadId: String(thread.id),- };- if (Platform.OS === "android") {- setFileInspectorPreferredVisible(false);- selectAndroidWorkspace({ name: "Thread", params });- return;- }- const navigationAction = resolveThreadSelectionNavigationAction({- usesSplitView: layout.usesSplitView,- pathname,- });- const overlayState = resolveThreadSelectionOverlayState({- state: navigation.getState(),- workspaceRouteKey: props.workspaceRouteKey,- action: navigationAction,- params,});- if (overlayState !== null) {- setFileInspectorPreferredVisible(false);- navigation.dispatch(CommonActions.reset(overlayState));- return;- }- if (navigationAction === "set-params") {- const nextThreadKey = scopedThreadKey(thread.environmentId, thread.id);- if (nextThreadKey === selectedThreadKey) {- return;- }- setFileInspectorPreferredVisible(false);- navigation.navigate("Thread", params);- return;- }- if (navigationAction === "replace") {- setFileInspectorPreferredVisible(false);- navigation.dispatch(StackActions.replace("Thread", params));- return;- }- navigation.navigate("Thread", params);};const contextValue = {@@ -732,7 +793,10 @@ function AdaptiveWorkspaceLayoutContent(panes,fileInspector,primarySidebarSearchQuery,+ startNewTask: handleStartNewTask,+ deferThreadSelectionUntil: deferredThreadSelection.waitFor,selectThread: handleSelectThread,+ selectThreadRoute: handleSelectThreadRoute,activateAuxiliaryPaneRole,registerWorkspaceInspector,setPrimarySidebarSearchQuery,@@ -881,6 +945,7 @@ function AdaptiveWorkspaceLayoutContent(style={railOverlay ? { right: 0 } : { width: navigationRailWidth }}><AndroidWorkspaceNavigation+ onNewThread={handleStartNewTask}railonSelect={revealPrimarySidebar}onOverlayChange={setRailOverlay}diff --git a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsxindex cea3e66a380..262e0ac7167 100644--- a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx+++ b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx@@ -48,6 +48,7 @@ import {nativeWorkspacePopAction,projectWorkspaceStack,partitionStackPresentations,+ reconcileStackScreens,type CollapsedSplitColumn,} from "../../native/workspace-stack-projection";import {@@ -68,9 +69,10 @@ const isPullRequestRoute = (route: Route) =>function ColumnScreen(props: {readonly descriptor: Descriptor;readonly primary?: boolean;+ readonly attached?: boolean;readonly selectedThreadKey?: string | null;readonly selectedPullRequestKey?: string | null;- readonly onDismiss: (routeKey: string) => void;+ readonly onDismiss: (routeKey: string, native: boolean) => void;readonly onAppearance: (type: "willAppear" | "didAppear" | "willDisappear", key: string) => void;readonly onCompose?: () => void;readonly navigation: ViewProps["navigation"];@@ -90,8 +92,9 @@ function ColumnScreen(props: {return (<Split.ScreenscreenKey={key}+ activityMode={props.attached === false ? "detached" : "attached"}onDismiss={(event) => {- if (event.nativeEvent.isNativeDismiss) props.onDismiss(key);+ props.onDismiss(key, event.nativeEvent.isNativeDismiss);}}onWillAppear={() => {props.onAppearance("willAppear", key);@@ -115,7 +118,13 @@ function ColumnScreen(props: {options={descriptor.options}canGoBack={!props.primary}column={props.primary ? "primary" : "detail"}- onCompose={props.onCompose}+ onCompose={+ descriptor.route.params &&+ "draft" in descriptor.route.params &&+ descriptor.route.params.draft+ ? undefined+ : props.onCompose+ }/><ColumnContentprimary={props.primary}@@ -136,10 +145,39 @@ function ColumnScreen(props: {function WorkspaceColumns(props: ViewProps & { readonly primary: Route; readonly detail: Route[] },) {- const { layout, panes, togglePrimarySidebar, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();+ const { layout, panes, togglePrimarySidebar, toggleAuxiliaryPane, startNewTask } =+ useAdaptiveWorkspaceLayout();const deviceType = useDeviceType();+ // Split screens must remain mounted while UIKit animates a detached route away.+ const [screens, setScreens] = useState({+ routes: props.detail,+ descriptors: props.descriptors,+ observedRoutes: props.detail,+ observedDescriptors: props.descriptors,+ completed: new Set<string>(),+ });+ if (+ 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));+ setScreens({+ routes,+ descriptors: Object.fromEntries(+ Object.entries({ ...screens.descriptors, ...props.descriptors }).filter(([key]) =>+ retained.has(key),+ ),+ ),+ observedRoutes: props.detail,+ observedDescriptors: props.descriptors,+ completed: new Set([...screens.completed].filter((key) => active.has(key))),+ });+ }+const selectedTab = useWorkspaceTabs()?.state.selectedTab;- const openNewTask = () => props.navigation.navigate("NewTaskSheet", { screen: "NewTask" });+ const openNewTask = startNewTask;// The Duo keeps compose in the detail column's bar, which is its vertical bar in landscape// and folded, so it sits with the column's other actions whichever screen is shown. Pull// requests leave it out, including one opened from a thread; their bar is already full of@@ -178,10 +216,17 @@ function WorkspaceColumns(): null;const handleNativeDismiss = useCallback(- (key: string) => {- const state = props.navigation.getState();- const action = nativeWorkspacePopAction(state, key);- if (action) props.navigation.dispatch(action);+ (key: string, native: boolean) => {+ setScreens((current) => ({+ ...current,+ routes: current.routes.filter((route) => route.key !== key),+ completed: new Set([...current.completed, key]),+ }));+ if (native) {+ const state = props.navigation.getState();+ const action = nativeWorkspacePopAction(state, key);+ if (action) props.navigation.dispatch(action);+ }},[props.navigation],);@@ -288,12 +333,13 @@ function WorkspaceColumns(/></ColumnContent></Split.Screen>- {props.detail.map((route) => {- const descriptor = props.descriptors[route.key];+ {screens.routes.map((route) => {+ const descriptor = props.descriptors[route.key] ?? screens.descriptors[route.key];return descriptor ? (<ColumnScreenkey={route.key}descriptor={descriptor}+ attached={props.detail.some((current) => current.key === route.key)}onDismiss={handleNativeDismiss}onAppearance={followCollapsedSplit}onCompose={isPullRequestRoute(route) ? undefined : detailCompose}@@ -316,7 +362,7 @@ function WorkspaceColumns(}function WorkspaceStackView(props: ViewProps & { readonly nativeColumns: boolean }) {- const { layout } = useAdaptiveWorkspaceLayout();+ const { layout, startNewTask } = useAdaptiveWorkspaceLayout();// Native dismiss commits the route pop after the transition. Restore the dock// when the primary screen starts appearing, including interactive back gestures.const [primaryVisible, setPrimaryVisible] = useState(false);@@ -343,7 +389,7 @@ function WorkspaceStackView(props: ViewProps & { readonly nativeColumns: booleanoptions: { headerShown: false },render: () => (<WorkspaceNativeTabs- onNewTask={() => props.navigation.navigate("NewTaskSheet", { screen: "NewTask" })}+ onNewTask={startNewTask}hidden={projection.detail.length > 0 &&!primaryVisible &&diff --git a/apps/mobile/src/features/layout/deferred-navigation.test.ts b/apps/mobile/src/features/layout/deferred-navigation.test.tsnew file mode 100644index 00000000000..4e4c54cdb59--- /dev/null+++ b/apps/mobile/src/features/layout/deferred-navigation.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from "vite-plus/test";+import { createDeferredNavigation } from "./deferred-navigation";++describe("workspace mutation navigation", () => {+ it("keeps only the latest selection until all checkouts settle", async () => {+ const navigation = createDeferredNavigation();+ const first = Promise.withResolvers<void>();+ const second = Promise.withResolvers<void>();+ const selected: string[] = [];+ navigation.waitFor(first.promise);+ navigation.waitFor(second.promise);+ navigation.run(() => selected.push("old draft"));+ navigation.run(() => selected.push("latest draft"));+ first.resolve();+ await first.promise;+ expect(selected).toEqual([]);+ second.resolve();+ await second.promise;+ expect(selected).toEqual(["latest draft"]);+ navigation.run(() => selected.push("thread"));+ expect(selected).toEqual(["latest draft", "thread"]);+ });++ it("waits for the removal guard commit after checkout completes", async () => {+ const navigation = createDeferredNavigation();+ const checkout = Promise.withResolvers<void>();+ const guardCommit = Promise.withResolvers<void>();+ let selected = false;+ const ready = Promise.allSettled([checkout.promise, guardCommit.promise]);+ navigation.waitFor(ready);+ navigation.run(() => {+ selected = true;+ });+ checkout.resolve();+ await checkout.promise;+ expect(selected).toBe(false);+ guardCommit.resolve();+ await ready;+ expect(selected).toBe(true);+ });++ it("releases selection after a failed checkout", async () => {+ const navigation = createDeferredNavigation();+ const checkout = Promise.withResolvers<void>();+ let selected = false;+ navigation.waitFor(checkout.promise);+ navigation.run(() => {+ selected = true;+ });+ checkout.reject(new Error("Checkout failed"));+ await checkout.promise.catch(() => undefined);+ expect(selected).toBe(true);+ });+});diff --git a/apps/mobile/src/features/layout/deferred-navigation.ts b/apps/mobile/src/features/layout/deferred-navigation.tsnew file mode 100644index 00000000000..8da68b10b39--- /dev/null+++ b/apps/mobile/src/features/layout/deferred-navigation.ts@@ -0,0 +1,22 @@+/** Hold in-place route changes while a workspace mutation is still running. */+export function createDeferredNavigation() {+ let pending = 0;+ let latest: (() => void) | null = null;+ return {+ run(action: () => void) {+ if (pending > 0) latest = action;+ else action();+ },+ waitFor(operation: Promise<unknown>) {+ pending += 1;+ const release = () => {+ pending -= 1;+ if (pending !== 0) return;+ const action = latest;+ latest = null;+ action?.();+ };+ void operation.then(release, release);+ },+ };+}diff --git a/apps/mobile/src/features/layout/useWorkspaceSidebarHeaderItem.ts b/apps/mobile/src/features/layout/useWorkspaceSidebarHeaderItem.tsnew file mode 100644index 00000000000..f1304ed2766--- /dev/null+++ b/apps/mobile/src/features/layout/useWorkspaceSidebarHeaderItem.ts@@ -0,0 +1,27 @@+import { useMemo } from "react";+import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns";+import { useAdaptiveWorkspaceLayout } from "./AdaptiveWorkspaceLayout";+import { withNativeGlassHeaderItem } from "./native-glass-header-items";++export function useWorkspaceSidebarHeaderItem() {+ const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();+ const { panes, togglePrimarySidebar } = useAdaptiveWorkspaceLayout();+ return useMemo(+ () =>+ withNativeGlassHeaderItem({+ axisBehavior: usesNativeWorkspaceColumns ? "horizontalOnly" : undefined,+ accessibilityLabel: panes.primarySidebarVisible+ ? "Maximize content"+ : "Show thread sidebar",+ icon: {+ name: panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left",+ type: "sfSymbol" as const,+ },+ identifier: "thread-left-sidebar",+ label: panes.primarySidebarVisible ? "Maximize content" : "Show thread sidebar",+ onPress: togglePrimarySidebar,+ type: "button" as const,+ }),+ [panes.primarySidebarVisible, togglePrimarySidebar, usesNativeWorkspaceColumns],+ );+}diff --git a/apps/mobile/src/features/projects/AddProjectScreen.tsx b/apps/mobile/src/features/projects/AddProjectScreen.tsxindex 8dc8750ab0c..66a68b2ebae 100644--- a/apps/mobile/src/features/projects/AddProjectScreen.tsx+++ b/apps/mobile/src/features/projects/AddProjectScreen.tsx@@ -54,7 +54,13 @@ import {resolveEnvironmentMachineKind,SourceControlProviderKind,} from "@t3tools/contracts";-import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";+import {+ CommonActions,+ StackActions,+ useNavigation,+ type NavigationState,+ type ParamListBase,+} from "@react-navigation/native";import { SymbolView } from "../../components/ui/AppSymbol";import { useEffect, useRef, useState, type ReactNode } from "react";import { Platform, Pressable, View } from "react-native";@@ -648,7 +654,10 @@ export function AddProjectSourceScreen() {}function openNewTaskDraft(- navigation: { dispatch: (action: ReturnType<typeof CommonActions.reset>) => void },+ navigation: {+ dispatch: (action: ReturnType<typeof CommonActions.reset>) => void;+ getState: () => NavigationState<ParamListBase> | undefined;+ },params: {environmentId: EnvironmentId;projectId: ProjectId;@@ -657,9 +666,14 @@ function openNewTaskDraft(draftId?: string;},) {- navigation.dispatch(- CommonActions.reset({ index: 0, routes: [{ name: "NewTaskDraft", params }] }),- );+ const state = navigation.getState();+ if (!state) return;+ const threadIndex = state.routes.findLastIndex((route) => route.name === "Thread");+ const routes = [+ ...state.routes.slice(0, threadIndex < 0 ? state.index : threadIndex),+ { key: uuidv4(), name: "Thread", params: { draft: params } },+ ];+ navigation.dispatch(CommonActions.reset({ ...state, index: routes.length - 1, routes }));}async function draftWithPrompt(@@ -698,21 +712,11 @@ function useCreateProject(environment: EnvironmentOption | null) {});if (existing) {Dialog.alert("Project already exists", existing.title);- navigation.dispatch(- CommonActions.reset({- index: 0,- routes: [- {- name: "NewTaskDraft",- params: {- environmentId: existing.environmentId,- projectId: existing.id,- title: existing.title,- },- },- ],- }),- );+ openNewTaskDraft(navigation, {+ environmentId: existing.environmentId,+ projectId: existing.id,+ title: existing.title,+ });return;}@@ -729,21 +733,11 @@ function useCreateProject(environment: EnvironmentOption | null) {if (AsyncResult.isFailure(result)) {return result;}- navigation.dispatch(- CommonActions.reset({- index: 0,- routes: [- {- name: "NewTaskDraft",- params: {- environmentId: environment.environmentId,- projectId,- title: inferProjectTitleFromPath(workspaceRoot),- },- },- ],- }),- );+ openNewTaskDraft(navigation, {+ environmentId: environment.environmentId,+ projectId,+ title: inferProjectTitleFromPath(workspaceRoot),+ });return result;};}diff --git a/apps/mobile/src/features/prompt-links/usePromptLinkResolver.ts b/apps/mobile/src/features/prompt-links/usePromptLinkResolver.tsindex 4fa783d0be9..2673a6ff208 100644--- a/apps/mobile/src/features/prompt-links/usePromptLinkResolver.ts+++ b/apps/mobile/src/features/prompt-links/usePromptLinkResolver.ts@@ -131,9 +131,11 @@ export function usePromptLinkResolver(params: Readonly<Record<string, unknown>>}const modelUnavailable = writeDraft(draftKey, project.environmentId, request);navigation.dispatch(- StackActions.push("NewTaskDraft", {- draftId: draftKey,- title: request.pullRequest ? `PR #${request.pullRequest.number}` : project.title,+ StackActions.push("Thread", {+ draft: {+ draftId: draftKey,+ title: request.pullRequest ? `PR #${request.pullRequest.number}` : project.title,+ },}),);if (request.prompt || pullRequestUnavailable !== null || modelUnavailable) {diff --git a/apps/mobile/src/features/pull-requests/usePullRequestThreads.ts b/apps/mobile/src/features/pull-requests/usePullRequestThreads.tsindex 225db014749..e845c960e58 100644--- a/apps/mobile/src/features/pull-requests/usePullRequestThreads.ts+++ b/apps/mobile/src/features/pull-requests/usePullRequestThreads.ts@@ -146,9 +146,8 @@ export function usePullRequestThreads(previousPrompts.current.set(draftKey, pullRequestAgentPrompt(task));if (thread) openThread(thread);else- navigation.navigate("NewTaskSheet", {- screen: "NewTaskDraft",- params: { draftId: draftKey, title: `Ask about #${pr.number}` },+ navigation.navigate("Thread", {+ draft: { draftId: draftKey, title: `Ask about #${pr.number}` },});});pending.current = false;diff --git a/apps/mobile/src/features/threads/ComposerAttachmentButton.tsx b/apps/mobile/src/features/threads/ComposerAttachmentButton.tsxindex 9cab6420745..a7e85a1e5c1 100644--- a/apps/mobile/src/features/threads/ComposerAttachmentButton.tsx+++ b/apps/mobile/src/features/threads/ComposerAttachmentButton.tsx@@ -12,6 +12,7 @@ const ATTACHMENT_MENU_ACTIONS: MenuAction[] = [export function ComposerAttachmentButton(props: {readonly disabled?: boolean;+ readonly size?: "regular" | "large";readonly supportsFiles: boolean;readonly onPickMedia: () => Promise<void>;readonly onPickFiles: () => Promise<void>;@@ -28,7 +29,7 @@ export function ComposerAttachmentButton(props: {><SymbolViewname="plus"- size={Math.round(20 * scale)}+ size={Math.round((props.size === "large" ? 26 : 20) * scale)}weight="regular"tintColorClassName="accent-icon"type="monochrome"diff --git a/apps/mobile/src/features/threads/DraftEnvironmentControl.tsx b/apps/mobile/src/features/threads/DraftEnvironmentControl.tsxnew file mode 100644index 00000000000..21bb27a6dc7--- /dev/null+++ b/apps/mobile/src/features/threads/DraftEnvironmentControl.tsx@@ -0,0 +1,38 @@+import { Pressable } from "react-native";+import type { EnvironmentMachineKind } from "@t3tools/contracts";+import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";+import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";+import { AppText as Text } from "../../components/ui/AppText";+import { SymbolView } from "../../components/ui/AppSymbol";++import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";++export function DraftEnvironmentControl(props: {+ readonly label: string;+ readonly connectionState: EnvironmentConnectionPhase;+ readonly machineKind: EnvironmentMachineKind;+ readonly disabled: boolean;+ readonly onChooseEnvironment: () => void;+}) {+ const disconnected = props.connectionState !== "connected";+ return (+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={`Choose environment, ${props.label}, ${disconnected ? "Offline" : "Connected"}`}+ disabled={props.disabled}+ onPress={props.onChooseEnvironment}+ className="flex-row items-center gap-1.5 rounded-xl px-3 py-2 active:opacity-65"+ >+ <EnvironmentMachineSymbol+ kind={props.machineKind}+ size={13}+ tintColorClassName="accent-icon-muted"+ />+ <Text className="shrink text-sm text-foreground-muted" numberOfLines={1}>+ on {props.label}+ </Text>+ <SymbolView name="chevron.right" size={11} tintColorClassName="accent-icon-muted" />+ {disconnected ? <ConnectionStatusDot state="error" pulse={false} size={6} /> : null}+ </Pressable>+ );+}diff --git a/apps/mobile/src/features/threads/DraftThreadHeader.tsx b/apps/mobile/src/features/threads/DraftThreadHeader.tsxnew file mode 100644index 00000000000..509545b58c8--- /dev/null+++ b/apps/mobile/src/features/threads/DraftThreadHeader.tsx@@ -0,0 +1,100 @@+import { uuidv4 } from "../../lib/uuid";+import * as Dialog from "../../components/ui/Dialog";+import { useNavigation } from "@react-navigation/native";+import { AsyncResult } from "effect/reactivity";+import * as Cause from "effect/Cause";+import { AuthFilesystemReadScope, AuthSourceControlWriteScope } from "@t3tools/contracts";+import type {+ EnvironmentProject,+ EnvironmentThreadShell,+} from "@t3tools/client-runtime/state/shell";+import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";+import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";+import { useEnvironmentQuery } from "../../state/query";+import { useEnvironmentScope } from "../../state/session";+import { useAtomCommand } from "../../state/use-atom-command";+import { vcsActionManager, vcsEnvironment } from "../../state/vcs";+import { useVcsActionState } from "../../state/use-vcs-action-state";+import { ThreadHeader } from "./ThreadHeader";++export function DraftThreadHeader(props: {+ readonly thread: EnvironmentThreadShell;+ readonly project: EnvironmentProject;+ readonly cwd: string | null;+}) {+ const navigation = useNavigation();+ const { themeVariables } = useAppearancePreferences();+ const environmentId = props.thread.environmentId;+ const canReadFiles = useEnvironmentScope(environmentId, AuthFilesystemReadScope);+ const canWriteGit = useEnvironmentScope(environmentId, AuthSourceControlWriteScope);+ const status = useEnvironmentQuery(+ props.cwd ? vcsEnvironment.status({ environmentId, input: { cwd: props.cwd } }) : null,+ );+ const target = { environmentId, cwd: props.cwd };+ const progress = useVcsActionState(target);+ const runAction = useAtomCommand(vcsActionManager.runStackedAction(target), {+ reportFailure: false,+ });+ const pull = useAtomCommand(vcsEnvironment.pull, { reportFailure: false });+ const openFiles = () => {+ if (!props.cwd || !canReadFiles) return;+ navigation.navigate("NewTaskFiles", {+ environmentId,+ cwd: props.cwd,+ projectName: props.project.title,+ });+ };+ const requiresThread = () =>+ Dialog.alert("Available after the first message", "This action needs a saved thread.");+ return (+ <ThreadHeader+ draft+ title="New thread"+ subtitle=""+ headerColor={themeVariables["--color-header"]}+ usesNativeHeaderGlass={NATIVE_LIQUID_GLASS_SUPPORTED}+ hasThreadCwd={props.cwd !== null}+ hasWorkspaceRoot={Boolean(props.project.workspaceRoot)}+ fileInspectorSupported={false}+ inspectorMode={null}+ onToggleInspector={openFiles}+ onOpenFilesInspector={openFiles}+ onOpenGitInspector={requiresThread}+ gitControls={{+ environmentId,+ threadId: props.thread.id,+ hasThread: false,+ currentBranch: props.thread.branch,+ gitStatus: status.data,+ gitOperationLabel: progress.currentLabel,+ canOpenTerminal: false,+ canOperateTerminal: false,+ canOpenFiles: canReadFiles && props.cwd !== null,+ projectScripts: [],+ terminalSessions: [],+ onOpenFilesInspector: openFiles,+ onOpenGitInspector: requiresThread,+ onOpenTerminal: requiresThread,+ onOpenNewTerminal: requiresThread,+ onRunProjectScript: async () => {+ requiresThread();+ },+ onPull: async () => {+ if (!canWriteGit || !props.cwd) return;+ const result = await pull({ environmentId, input: { cwd: props.cwd } });+ if (AsyncResult.isFailure(result))+ Dialog.alert("Could not pull", String(Cause.squash(result.cause)));+ },+ onRunAction: async (input) => {+ if (!canWriteGit || !props.cwd) return null;+ const result = await runAction({ ...input, actionId: uuidv4() });+ if (AsyncResult.isFailure(result)) {+ Dialog.alert("Git action failed", String(Cause.squash(result.cause)));+ return null;+ }+ return result.value;+ },+ }}+ />+ );+}diff --git a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsxindex c17434c0ca7..af4e46ef135 100644--- a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx+++ b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx@@ -7,7 +7,11 @@ import { NavigationRow } from "../../components/ui/NavigationRow";import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";import { shouldCheckoutNewTaskBranch } from "./new-task-context-presentation";import type { VcsRef } from "@t3tools/client-runtime/state/vcs";-import { AuthSourceControlWriteScope, resolveEnvironmentMachineKind } from "@t3tools/contracts";+import {+ AuthSourceControlWriteScope,+ resolveEnvironmentMachineKind,+ type EnvironmentId,+} from "@t3tools/contracts";import { LegendList } from "@legendapp/list/react-native";import {isAtomCommandInterrupted,@@ -27,7 +31,6 @@ import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymimport { ThemedSwitch } from "../../components/ui/ThemedSwitch";import { cn } from "../../lib/cn";import { NativeStackScreenOptions } from "../../native/StackHeader";-import { useServerConfigs } from "../../state/entities";import { useEnvironmentScope } from "../../state/session";import { useAtomCommand } from "../../state/use-atom-command";import { vcsEnvironment } from "../../state/vcs";@@ -39,6 +42,100 @@ import { useNativeMailSearchToolbar } from "../../native/use-native-mail-search-import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";import { checkoutNewTaskBranch } from "./checkout-new-task-branch";+import { useEnvironmentPresentation } from "../../state/presentation";+import { useRemoteConnections } from "../../state/use-remote-environment-registry";+import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";+import {+ ConnectionDiagnosisDetails,+ useConnectionDiagnosis,+} from "../connection/ConnectionDiagnosisDetails";+import { environmentStatusText } from "../connection/environmentStatusText";++function EnvironmentPickerRow(props: {+ environmentId: EnvironmentId;+ title: string;+ selected: boolean;+ disabled: boolean;+ isLast: boolean;+ onPress: () => void;+}) {+ const [expanded, setExpanded] = useState(false);+ const { presentation } = useEnvironmentPresentation(props.environmentId);+ const { diagnosis, state } = useConnectionDiagnosis(props.environmentId, presentation);+ const { onReconnectEnvironment } = useRemoteConnections();+ const connection = presentation?.connection;+ const status =+ diagnosis?.headline ??+ (connection ? environmentStatusText({ ...connection, error: null }) : "Offline");+ return (+ <View className={cn("bg-grouped-card", !props.isLast && "border-b border-border-subtle")}>+ <View className="flex-row items-center">+ <Pressable+ accessibilityRole="radio"+ accessibilityLabel={`${props.title}, ${status}`}+ accessibilityState={{ checked: props.selected }}+ disabled={props.disabled}+ onPress={props.onPress}+ className="min-h-16 flex-1 flex-row items-center gap-3 px-4 py-3 active:bg-subtle"+ >+ <EnvironmentMachineSymbol+ kind={resolveEnvironmentMachineKind(presentation?.serverConfig ?? null)}+ size={20}+ tintColorClassName="accent-icon-muted"+ />+ <View className="min-w-0 flex-1 gap-1">+ <Text className="text-base font-t3-medium text-foreground" numberOfLines={1}>+ {props.title}+ </Text>+ <View className="flex-row items-center gap-1.5">+ <ConnectionStatusDot state={connection?.phase ?? "offline"} pulse={false} size={6} />+ <Text className="shrink text-xs text-foreground-muted" numberOfLines={2}>+ {status}+ </Text>+ </View>+ </View>+ {props.selected ? (+ <SymbolView name="checkmark" size={16} tintColorClassName="accent-icon" />+ ) : null}+ </Pressable>+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={`${expanded ? "Hide" : "Show"} connection details for ${props.title}`}+ accessibilityState={{ expanded }}+ onPress={() => setExpanded(!expanded)}+ className="min-h-11 min-w-11 items-center justify-center active:opacity-65"+ >+ <SymbolView+ name={expanded ? "chevron.up" : "chevron.down"}+ size={13}+ tintColorClassName="accent-icon-muted"+ />+ </Pressable>+ </View>+ {expanded ? (+ <View className="gap-3 px-4 pb-4">+ {diagnosis ? (+ <ConnectionDiagnosisDetails hostLabel={props.title} diagnosis={diagnosis} />+ ) : (+ <Text className="text-sm text-foreground-muted">{status}</Text>+ )}+ {state.retryAt ? (+ <Text className="text-sm text-foreground-muted">+ Next reconnect at {new Date(state.retryAt).toLocaleTimeString()}+ </Text>+ ) : null}+ {connection?.phase !== "connected" ? (+ <Button+ label="Reconnect now"+ onPress={() => onReconnectEnvironment(props.environmentId)}+ />+ ) : null}+ </View>+ ) : null}+ </View>+ );+}+function SelectionRow(props: {readonly icon?: "arrow.triangle.branch" | ReactNode;readonly onPress: () => void;@@ -203,7 +300,6 @@ export function NewTaskEnvironmentPickerRouteScreen() {const flow = useNewTaskFlow();const navigation = useNavigation();const insets = useSafeAreaInsets();- const serverConfigs = useServerConfigs();return (<View className="flex-1 bg-sheet" collapsable={false}><NativeStackScreenOptions@@ -231,17 +327,9 @@ export function NewTaskEnvironmentPickerRouteScreen() {><PickerSurface>{flow.environments.map((environment, index) => (- <SelectionRow+ <EnvironmentPickerRowkey={String(environment.environmentId)}- icon={- <EnvironmentMachineSymbol- kind={resolveEnvironmentMachineKind(- serverConfigs.get(environment.environmentId) ?? null,- )}- size={Platform.OS === "android" ? 24 : 17}- tintColorClassName="accent-icon-muted"- />- }+ environmentId={environment.environmentId}isLast={index === flow.environments.length - 1}disabled={flow.switchingToEnvironmentId !== null}onPress={() => {diff --git a/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsxindex 0dc59e1875d..4a13d6b1602 100644--- a/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx+++ b/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx@@ -1,6 +1,14 @@+import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";+import { useNewTaskFlow } from "./new-task-flow-provider";import * as Dialog from "../../components/ui/Dialog";-import { useNavigation, usePreventRemove, type StaticScreenProps } from "@react-navigation/native";-import { useEffect, useMemo, useRef, useState } from "react";+import {+ useNavigation,+ useRoute,+ usePreventRemove,+ usePreventRemoveContext,+ type StaticScreenProps,+} from "@react-navigation/native";+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import { View } from "react-native";import {isAtomCommandInterrupted,@@ -15,22 +23,22 @@ import { checkoutNewTaskBranch } from "./checkout-new-task-branch";import { resolveNewTaskBranchWorktreePath } from "./new-task-context-presentation";import { NativeStackScreenOptions } from "../../native/StackHeader";+import { ThreadScreenFallback } from "./ThreadScreenHost";import { NewTaskDraftScreen } from "./NewTaskDraftScreen";-type NewTaskDraftRouteParams = {- readonly environmentId?: string | string[];- readonly projectId?: string | string[];- readonly branch?: string | null;- readonly worktreePath?: string | null;- readonly title?: string | string[];- readonly cloning?: string | string[];- readonly pendingTaskId?: string | string[];- readonly draftId?: string | string[];- readonly incomingShareId?: string | string[];-};+import type { NewTaskDraftRouteParams } from "./thread-route-state";+export type { NewTaskDraftRouteParams } from "./thread-route-state";export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraftRouteParams>) {+ const currentRoute = useRoute();const params = useMemo(() => route.params ?? {}, [route.params]);+ const { reset } = useNewTaskFlow();+ const { deferThreadSelectionUntil } = useAdaptiveWorkspaceLayout();+ const [initialized, setInitialized] = useState(false);+ useLayoutEffect(() => {+ reset();+ setInitialized(true);+ }, [reset]);const pendingTaskId = Array.isArray(params.pendingTaskId)? params.pendingTaskId[0]: params.pendingTaskId;@@ -70,6 +78,7 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDrafconst [pendingCheckouts, setPendingCheckouts] = useState(0);const checkoutTail = useRef(Promise.resolve());+ const committedCheckoutReleases = useRef(new Set<() => void>());const waitingForProject =!project &&(catalogState.isLoadingConnections ||@@ -103,10 +112,14 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDrafsetPendingCheckouts((count) => count - 1);if (active) setPreparation({ request: initialProjectRef, result, workspaceRoot });});+ const committed = Promise.withResolvers<void>();+ committedCheckoutReleases.current.add(committed.resolve);+ deferThreadSelectionUntil(Promise.allSettled([checkoutTail.current, committed.promise]));return () => {active = false;};}, [+ deferThreadSelectionUntil,environmentId,workspaceRoot,initialProjectRef,@@ -124,6 +137,21 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf// A replaced request must settle too before the shared checkout is left behind.const checkoutPending = pendingCheckouts > 0 || (needsPreparation && result === null);usePreventRemove(checkoutPending, () => undefined);+ const { preventedRoutes } = usePreventRemoveContext();+ const removalBlocked = preventedRoutes[currentRoute.key]?.preventRemove === true;+ useEffect(() => {+ if (checkoutPending || removalBlocked) return;+ // Native-stack reads the provider state, which commits after the hook updates its registry.+ for (const release of committedCheckoutReleases.current) release();+ committedCheckoutReleases.current.clear();+ }, [checkoutPending, removalBlocked]);+ useEffect(() => {+ const releases = committedCheckoutReleases.current;+ return () => {+ for (const release of releases) release();+ releases.clear();+ };+ }, []);useEffect(() => {if (checkoutPending || result?._tag !== "Failure") return;if (!isAtomCommandInterrupted(result)) {@@ -153,17 +181,16 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf);const preparingBranch = checkoutPending || (needsPreparation && result?._tag !== "Success");+ if (!initialized) return null;return (<>- <NativeStackScreenOptions- options={{- title: Array.isArray(params.title) ? params.title[0] : (params.title ?? "New task"),- }}- />{preparingBranch ? (- <View className="flex-1 items-center justify-center bg-screen">- <Text className="text-foreground">Switching branch...</Text>- </View>+ <ThreadScreenFallback>+ <NativeStackScreenOptions options={{ title: "New thread" }} />+ <View className="flex-1 items-center justify-center bg-screen">+ <Text className="text-foreground">Switching branch...</Text>+ </View>+ </ThreadScreenFallback>) : (<NewTaskDraftScreeninitialProjectRef={preparedProjectRef}diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsxindex 319aa12230c..12a451d72d0 100644--- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx@@ -1,110 +1,59 @@-import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader";-import { SheetHeader } from "../../components/ui/SheetHeader";-import { Button } from "../../components/ui/Button";+import { DraftEnvironmentControl } from "./DraftEnvironmentControl";+import { NativeScrollEdgeEffectsContext } from "../../native/NativeScrollViewMarker";+import { DraftThreadHeader } from "./DraftThreadHeader";+import { threadHeaderAppearance } from "./thread-header-appearance";+import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";+import { useComposerAttachmentActions } from "../../state/use-composer-attachment-actions";+import { useWorkspaceBackNavigation } from "../workspace/useAndroidWorkspaceNavigation";+import { submittedThreadParams } from "./thread-route-state";+import { ThreadScreenBinding, ThreadScreenFallback } from "./ThreadScreenHost";+import { draftThreadShell } from "./draft-thread-shell";+import { connectionTone } from "../connection/connectionTone";+import { AppBar } from "../../components/ui/AppBar";+import { ThreadId } from "@t3tools/contracts";+import * as Dialog from "../../components/ui/Dialog";import { useAtomValue } from "@effect/atom-react";import * as Cause from "effect/Cause";import { AsyncResult } from "effect/reactivity";import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";-import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";-import {- nextPastedTextFileName,- pastedTextDisposition,- replaceTextSelection,-} from "@t3tools/client-runtime/text-paste";-import { NativeStackScreenOptions } from "../../native/StackHeader";import {CommonActions,StackActions,- useFocusEffect,useNavigation,usePreventRemove,- type NavigationAction,} from "@react-navigation/native";-import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from "react";+import { useEffect, useEffectEvent, useRef, useState } from "react";import { Platform, Pressable, View } from "react-native";import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";-import {- KeyboardController,- KeyboardStickyView,- useKeyboardState,-} from "react-native-keyboard-controller";-import Animated, { FadeInDown, ReduceMotion } from "react-native-reanimated";-import { useSafeAreaInsets } from "react-native-safe-area-context";-import { useUniwindTheme } from "../../lib/useUniwindTheme";-import { FONT_FAMILIES } from "../../lib/fontFamilies";+import { KeyboardController } from "react-native-keyboard-controller";+import {AuthOrchestrationOperateScope,PROVIDER_SEND_TURN_MAX_ATTACHMENTS,- PROVIDER_SEND_TURN_MAX_INPUT_CHARS,resolveEnvironmentMachineKind,} from "@t3tools/contracts";-import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";-import {- ComposerEditor,- type ComposerEditorHandle,- type ComposerTextPaste,-} from "../../components/ComposerEditor";+import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";import { composerContextImportsAtom } from "../../state/use-composer-drafts";-import {- composerContextSendBlockReason,- type ComposerDocumentAttachment,-} from "../../lib/composerContext";-import {- ComposerActionButton,- ComposerInlineControl,- ComposerToolbarRow,-} from "../../components/ComposerToolbar";-import { ScreenContent } from "../../components/ui/ScreenContent";-import { ComposerAttachmentButton } from "./ComposerAttachmentButton";-import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";-import { composerStripAttachments } from "../../lib/composerImages";-import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";+import { composerContextSendBlockReason } from "../../lib/composerContext";+import { ComposerInlineControl } from "../../components/ComposerToolbar";+import {composerAttachmentUploadBlockReason,composerAttachmentsStillUploading,composerAttachmentUploadsAtom,} from "../../state/composer-attachment-uploads";-import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";-import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";-import { ComposerModelControl } from "../../components/ComposerModelControl";+import { SymbolView } from "../../components/ui/AppSymbol";import { AppText as Text } from "../../components/ui/AppText";-import { hasProviderUsageLimits, isUsageLimitsCommand } from "@t3tools/shared/usageLimits";import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences";-import { COMPOSER_LAYOUT_TRANSITION, ComposerSurface } from "./ThreadComposer";-import { ComposerCommandPopover } from "./ComposerCommandPopover";-import { ComposerPopoverAnchor } from "./ComposerPopoverAnchor";-import { useComposerCommandMenu } from "./use-composer-command-menu";-import {- ComposerDictationCancelAction,- ComposerDictationPrimaryAction,- ComposerDictationStatus,- ComposerDictationToolbar,-} from "../voice-input/ComposerDictationControl";-import { useVoiceInputController } from "../voice-input/useVoiceInputController";-import { resolveVoiceComposerPresentation } from "../voice-input/voiceInputPresentation";-import {- useThreadSettingsSheetPresentation,- type NavigationWithFinishTransitioning,-} from "./use-thread-settings-sheet-presentation";+import { makeTurnCommandMetadata } from "../../lib/commandMetadata";-import {- convertPastedImagesToAttachments,- createPastedTextComposerAttachment,- pickComposerFiles,- pickComposerMedia,- removePersistedComposerAttachmentFile,- type DraftComposerFileAttachment,-} from "../../lib/composerImages";-import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";+import {clearComposerDraftContent,- captureComposerDraftInsertion,- countComposerDraftAttachmentsAfterSelection,getComposerDraftSnapshot,- composerDraftsAtom,mergeComposerDraftContent,restoreComposerDraftSnapshot,updateComposerDraftSettings,@@ -112,7 +61,7 @@ import {type ComposerDraft,waitForComposerDraftsLoaded,} from "../../state/use-composer-drafts";-import { useEnvironmentServerConfig, useProjects, useThreadShells } from "../../state/entities";+import { useEnvironmentServerConfig, useProjects } from "../../state/entities";import { useProjectClone } from "../../state/projectClones";import { projectEnvironment } from "../../state/projects";import { sourceControlEnvironment } from "../../state/sourceControl";@@ -123,9 +72,11 @@ import {isModelSelectionUnavailable,resolveSelectableModelSelection,} from "../../lib/modelOptions";-import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";import { enqueueThreadOutboxMessage } from "../../state/thread-outbox";-import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";+import {+ useRemoteConnections,+ useRemoteEnvironmentRuntime,+} from "../../state/use-remote-environment-registry";import { useNewTaskFlow } from "./new-task-flow-provider";import {nextEnvironmentId,@@ -142,10 +93,8 @@ import { useIncomingShare } from "../sharing/IncomingShareProvider";import { selectIncomingShareAttachmentsForServer } from "../sharing/incoming-share-model";import { appAtomRegistry } from "../../state/atom-registry";import { serverEnvironment } from "../../state/server";-import { fileRoutePathSegments } from "../files/filePath";-import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";-const COMPOSER_POPOVER_ENTERING = FadeInDown.duration(180).reduceMotion(ReduceMotion.System);+import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";function NewTaskWorkspaceIcon(props: {readonly workspaceMode: "local" | "worktree";@@ -204,9 +153,11 @@ export function NewTaskDraftScreen(props: {readonly draftId?: string;readonly incomingShareId?: string;}) {+ const [creationMetadata] = useState(makeTurnCommandMetadata);const projects = useProjects();const flow = useNewTaskFlow();const navigation = useNavigation();+ const goBack = useWorkspaceBackNavigation("threads");const {consumeShare,getShare,@@ -214,10 +165,6 @@ export function NewTaskDraftScreen(props: {releaseShareReservation,reserveShare,} = useIncomingShare();- const insets = useSafeAreaInsets();- const isKeyboardVisible = useKeyboardState((state) => state.isVisible);- const controlsBottomPadding = Math.max(insets.bottom, 10);- const keyboardOpenedOffset = Math.max(0, controlsBottomPadding - 8);const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;const selectedProjectLabel = (() => {if (!selectedProject) return null;@@ -230,22 +177,17 @@ export function NewTaskDraftScreen(props: {);return scope?.title ?? selectedProject.title;})();- const { connectedEnvironments } = useRemoteConnectionStatus();+ const { onReconnectEnvironment } = useRemoteConnections();+ const environmentRuntime = useRemoteEnvironmentRuntime(selectedProject?.environmentId ?? null);+ const connectionState = environmentRuntime?.connectionState ?? "offline";const selectedEnvironmentServerConfig = useEnvironmentServerConfig(selectedProject?.environmentId ?? null,);- const environmentConnected =- selectedProject !== null &&- connectedEnvironments.find(- (environment) => environment.environmentId === selectedProject.environmentId,- )?.connectionState === "connected";+ const environmentConnected = connectionState === "connected";const canOperate = useEnvironmentScope(selectedProject?.environmentId ?? null,AuthOrchestrationOperateScope,);- const taskPermissionReason =- environmentConnected && !canOperate ? "This connection cannot start tasks." : null;- const modelUnavailable = environmentConnected && flow.selectedModelOption?.isUnavailable === true;const projectCloneState = useProjectClone(selectedProject? { environmentId: selectedProject.environmentId, projectId: selectedProject.id }@@ -323,105 +265,22 @@ export function NewTaskDraftScreen(props: {const queuesInsteadOfStarting = !environmentConnected || attachmentsUploading;const promptInputRef = useRef<ComposerEditorHandle>(null);const loadedBranchesProjectKeyRef = useRef<string | null>(null);- const [isComposerFocused, setIsComposerFocused] = useState(false);- const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);- const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);- const wasFocusedBeforePreviewRef = useRef(false);- const openVideoPreview = (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {- wasFocusedBeforePreviewRef.current = isComposerFocused;- setPreviewFile(null);- setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });- };- const openFilePreview = (source: FilePreviewSource) => {- wasFocusedBeforePreviewRef.current = isComposerFocused;- setPreviewVideo(null);- setPreviewFile((current) => current ?? source);- };- const closeMediaPreview = () => {- setPreviewVideo(null);- setPreviewFile(null);- if (wasFocusedBeforePreviewRef.current) {- setTimeout(() => {- if (navigation.isFocused()) promptInputRef.current?.focus();- }, 100);- }- };- const settingsSheetPresentation = useThreadSettingsSheetPresentation({- editorRef: promptInputRef,- isEditorFocused: isComposerFocused,- });- useEffect(() => {- if (Platform.OS !== "ios") {- return;- }-- navigation.getParent()?.setOptions({ gestureEnabled: !isKeyboardVisible });- }, [isKeyboardVisible, navigation]);- useEffect(() => {- return () => {- if (Platform.OS === "ios") {- navigation.getParent()?.setOptions({ gestureEnabled: true });- }- };- }, [navigation]);- const settingsRoutePresentedRef = useRef(false);- useEffect(() => {- if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {- return;- }-- settingsRoutePresentedRef.current = true;- navigation.dispatch(StackActions.push("ThreadSettings"));- }, [navigation, settingsSheetPresentation.isVisible]);- useFocusEffect(() => {- if (!settingsRoutePresentedRef.current) {- return;- }-- settingsRoutePresentedRef.current = false;- settingsSheetPresentation.onDismissed();- });- useEffect(- () =>- // UIKit's completion callback for the sheet dismissal, surfaced by the- // native-stack patch. This is when the queued keyboard restore runs.- (navigation as unknown as NavigationWithFinishTransitioning).addListener(- "finishTransitioning",- settingsSheetPresentation.onStackTransitionsFinished,- ),- [navigation, settingsSheetPresentation.onStackTransitionsFinished],- );const [importingShareKey, setImportingShareKey] = useState<string | null>(null);const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);const [isReturningToProjectPicker, setIsReturningToProjectPicker] = useState(false);- const [submitNavigationAction, setSubmitNavigationAction] = useState<NavigationAction | null>(- null,- );const [shareImportAttempt, setShareImportAttempt] = useState(0);const startedShareImportKeyRef = useRef<string | null>(null);const cancellingShareImportKeyRef = useRef<string | null>(null);const shareImportDraftBackupRef = useRef(new Map<string, ComposerDraft>());const activeShareImportTokenRef = useRef<symbol | null>(null);const shareImportMountedRef = useRef(true);- const pendingPastedTextAttachmentCountRef = useRef(0);- const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0);- const pastedTextFileNamesRef = useRef<{ draftKey: string | null; names: Set<string> }>({- draftKey: null,- names: new Set(),- });// The share import resumes after awaits; this reads the screen's current// draft and share at that point without re-running the import effect.const isCurrentShareImport = useEffectEvent((draftKey: string, shareId: string) =>flow.draftKey === draftKey && props.incomingShareId === shareId,);- // Pasted-text attachments finish in an event handler, where an effect event- // cannot be called and the provider's draft key has no store to read.- const latestDraftKeyRef = useRef(flow.draftKey);- useLayoutEffect(() => {- latestDraftKeyRef.current = flow.draftKey;- });const isImportingShare = importingShareKey !== null;const alertedUnavailableIncomingShareIdRef = useRef<string | null>(null);// The share this screen already moved into its draft. Sending clears the@@ -463,66 +322,15 @@ export function NewTaskDraftScreen(props: {};const cycleEnvironmentCommands = environments.length > 1 ? (["cycleHost"] as const) : [];useHardwareKeyboardCommand(cycleEnvironmentCommands, cycleEnvironment);- const offersUsageLimits =- flow.selectedProviderStatus !== null &&- hasProviderUsageLimits(- flow.selectedProviderStatus.driver,- selectedEnvironmentServerConfig?.providers ?? [],- selectedEnvironmentServerConfig?.usageLimitSources ?? [],- );const composerWorkspaceCwd =(flow.workspaceMode === "worktree"? selectedProject?.workspaceRoot: (flow.selectedWorktreePath ?? selectedProject?.workspaceRoot)) || null;- const stripAttachments = composerStripAttachments(flow.attachments);- const composerMenu = useComposerCommandMenu({- draftMessage: flow.prompt,- ownerKey: flow.draftKey,- environmentId: selectedProject?.environmentId ?? null,- threadShells: useThreadShells(),- pullRequestProjectId: selectedEnvironmentServerConfig?.environment.capabilities.pullRequests- ? (selectedProject?.id ?? null)- : null,- pullRequestRepository: selectedProject?.repositoryIdentity?.displayName ?? null,- projectCwd: composerWorkspaceCwd,- selectedProviderStatus: flow.selectedProviderStatus,- hasThread: false,- hasCompactableConversation: false,- offersUsageLimits: offersUsageLimits,- enabled: isComposerFocused && !isComposerInteractionLocked,- onChangeDraftMessage: flow.setPrompt,- onUpdateInteractionMode: flow.planModeEnabled ? flow.setInteractionMode : undefined,- });- const voiceInput = useVoiceInputController({- ownerKey: flow.draftKey,- label: selectedProjectLabel ? `New task in ${selectedProjectLabel}` : "New task",- readDraftMessage: () => (flow.draftKey ? getComposerDraftSnapshot(flow.draftKey).text : null),- subscribeToDraftChanges: (onChange) => appAtomRegistry.subscribe(composerDraftsAtom, onChange),- selection: composerMenu.selection,- disabled: isIncomingShareTransferPending || isImportingShare || flow.submitting,- onChangeDraftMessage: flow.setPrompt,- onChangeSelection: composerMenu.onSelectionChange,- });- const voicePresentation = resolveVoiceComposerPresentation(- voiceInput.state,- voiceInput.elapsedSeconds,- );- const isVoiceInputPresented = voicePresentation.statusLabel !== null;const preventRemove =(isIncomingShareTransferPending && !isProjectPickerReturnActive) ||isCancellingShareImport ||flow.submitting;usePreventRemove(preventRemove, () => undefined);- useEffect(() => {- if (preventRemove || submitNavigationAction === null) {- return;- }- const frame = requestAnimationFrame(() => {- setSubmitNavigationAction(null);- (navigation.getParent() ?? navigation).dispatch(submitNavigationAction);- });- return () => cancelAnimationFrame(frame);- }, [navigation, preventRemove, submitNavigationAction]);const hasImportedIncomingShare = Boolean(props.incomingShareId &&(consumedIncomingShareId === props.incomingShareId ||@@ -557,7 +365,7 @@ export function NewTaskDraftScreen(props: {// route, otherwise the transfer guard can swallow the fallback action.const frame = requestAnimationFrame(() => {navigation.dispatch(- StackActions.replace("NewTask", { incomingShareId: props.incomingShareId }),+ StackActions.replace("NewTaskProject", { incomingShareId: props.incomingShareId }),);});return () => cancelAnimationFrame(frame);@@ -606,7 +414,7 @@ export function NewTaskDraftScreen(props: {return;}attemptedDraftIdRef.current = draftId;- navigation.dispatch(StackActions.replace("NewTask"));+ navigation.dispatch(CommonActions.navigate("NewTaskProject"));});return () => {cancelled = true;@@ -623,7 +431,7 @@ export function NewTaskDraftScreen(props: {}attemptedPendingTaskIdRef.current = props.pendingTaskId;if (!beginEditingPendingTask(props.pendingTaskId)) {- navigation.dispatch(StackActions.replace("NewTask"));+ navigation.dispatch(CommonActions.navigate("NewTaskProject"));}}, [beginEditingPendingTask, editingPendingTask?.messageId, navigation, props.pendingTaskId]);@@ -635,11 +443,6 @@ export function NewTaskDraftScreen(props: {};}, [props.pendingTaskId, cancelEditingPendingTask]);- const theme = useUniwindTheme();- const foregroundColor = theme["--color-foreground"];- const regularFontFamily = FONT_FAMILIES.regular;- const bodyText = useScaledTextRole("body");-const lastInitialProjectRefRef = useRef(props.initialProjectRef);useEffect(() => {@@ -712,7 +515,7 @@ export function NewTaskDraftScreen(props: {return;}- navigation.dispatch(StackActions.replace("NewTask"));+ navigation.dispatch(CommonActions.navigate("NewTaskProject"));}, [projectScopes,projects,@@ -999,196 +802,41 @@ export function NewTaskDraftScreen(props: {workspaceMode: flow.workspaceMode,worktreePath: flow.selectedWorktreePath,});- const showBranchLoading = flow.branchesLoading && flow.availableBranches.length === 0;+ const showBranchLoading =+ environmentConnected && flow.branchesLoading && flow.availableBranches.length === 0;- async function handlePickMedia(): Promise<void> {- if (isComposerInteractionLocked || voiceInput.isBusy) {- return;- }- const capabilities = selectedEnvironmentServerConfig?.environment.capabilities;- const insertion = flow.draftKey ? captureComposerDraftInsertion(flow.draftKey) : undefined;- const result = await pickComposerMedia({- existingCount:- flow.draftKey && insertion- ? countComposerDraftAttachmentsAfterSelection(flow.draftKey, insertion)- : flow.attachments.length,- maxVideoBytes:- capabilities?.attachmentUploads === true- ? capabilities.fileAttachments?.maxUploadBytes- : undefined,- });- const rejectedCount =- result.attachments.length > 0 ? flow.appendAttachments(result.attachments, insertion) : 0;- const problems = [- ...(result.error ? [result.error] : []),- ...(rejectedCount > 0- ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`]- : []),- ];- if (problems.length > 0) {- Dialog.alert("Could not attach photo or video", problems.join("\n\n"));- }- }-- async function handlePickFiles(): Promise<void> {- if (isComposerInteractionLocked || voiceInput.isBusy) {- return;- }- const maxBytes =- selectedEnvironmentServerConfig?.environment.capabilities.fileAttachments?.maxUploadBytes;- if (maxBytes === undefined) {- Dialog.alert("File attachments are not available on this server.");- return;- }- const insertion = flow.draftKey ? captureComposerDraftInsertion(flow.draftKey) : undefined;- const result = await pickComposerFiles({- existingCount:- flow.draftKey && insertion- ? countComposerDraftAttachmentsAfterSelection(flow.draftKey, insertion)- : flow.attachments.length,- maxBytes,- });- const rejectedCount =- result.files.length > 0 ? flow.appendAttachments(result.files, insertion) : 0;- const problems = [- ...(result.error ? [result.error] : []),- ...(rejectedCount > 0- ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`]- : []),- ];- if (problems.length > 0) {- Dialog.alert("Could not attach file", problems.join("\n\n"));- }- }-- const handleNativePasteImages = async (uris: ReadonlyArray<string>) => {- const insertion = flow.draftKey ? captureComposerDraftInsertion(flow.draftKey) : undefined;- const existingCount =- flow.draftKey && insertion- ? countComposerDraftAttachmentsAfterSelection(flow.draftKey, insertion)- : flow.attachments.length;- const converted = await settlePromise(() =>- convertPastedImagesToAttachments({ uris, existingCount }),- );- if (AsyncResult.isFailure(converted)) {- console.error("[native paste] error converting images", squashAtomCommandFailure(converted));- return;- }- if (converted.value.length > 0) flow.appendAttachments(converted.value, insertion);- };+ const {+ onPickDraftMedia: handlePickMedia,+ onPickDraftFiles: handlePickFiles,+ onNativePasteImages: handleNativePasteImages,+ onNativePasteText: handleNativePasteText,+ } = useComposerAttachmentActions({+ draftKey: flow.draftKey,+ serverConfig: selectedEnvironmentServerConfig,+ locked: isComposerInteractionLocked,+ });- const handleNativePasteText = async (paste: ComposerTextPaste) => {+ async function handleStart(): Promise<import("@t3tools/contracts").MessageId | null> {+ const selectedProject = flow.selectedProject;const draftKey = flow.draftKey;- if (!draftKey) return;- const insertion = { text: paste.value, ...paste.selection };- const insertPaste = () => {- const insertion = replaceTextSelection({- value: paste.value,- selection: paste.selection,- text: paste.text,- });- const selection = { start: insertion.cursor, end: insertion.cursor };- flow.setPrompt(insertion.value);- composerMenu.onSelectionChange(selection);- };- const capabilities = selectedEnvironmentServerConfig?.environment.capabilities;- const advertisedMax =- capabilities?.attachmentUploads === true- ? capabilities.fileAttachments?.maxUploadBytes- : undefined;- const maxBytes =- advertisedMax === undefined ? null : clampFileAttachmentUploadBytes(advertisedMax);- const wouldExceedInputLimit =- paste.value.length -- Math.max(0, paste.selection.end - paste.selection.start) +- paste.text.length >- PROVIDER_SEND_TURN_MAX_INPUT_CHARS;- const canAttach =- maxBytes !== null &&- countComposerDraftAttachmentsAfterSelection(draftKey, insertion) <- PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&- new TextEncoder().encode(paste.text).byteLength <= maxBytes;if (- pastedTextDisposition({- text: paste.text,- wouldExceedInputLimit,- canAttach: true,- }) === "attachment"+ !selectedProject ||+ !draftKey ||+ cloneBlocksStart ||+ !isIncomingShareReady ||+ isImportingShare ||+ isComposerInteractionLocked) {- if (canAttach && maxBytes !== null) {- pendingPastedTextAttachmentCountRef.current += 1;- setPendingPastedTextAttachmentCount(pendingPastedTextAttachmentCountRef.current);- const attached = await settlePromise(async () => {- if (pastedTextFileNamesRef.current.draftKey !== draftKey) {- pastedTextFileNamesRef.current = { draftKey, names: new Set() };- }- const reservedNames = pastedTextFileNamesRef.current.names;- for (const attachment of flow.attachments) reservedNames.add(attachment.name);- const name = nextPastedTextFileName([...reservedNames]);- reservedNames.add(name);- const attachment = await createPastedTextComposerAttachment({- text: paste.text,- name,- maxBytes,- });- if (latestDraftKeyRef.current !== draftKey) {- await removePersistedComposerAttachmentFile(attachment.fileUri);- return;- }- if (flow.appendAttachments([attachment], insertion) > 0) {- await removePersistedComposerAttachmentFile(attachment.fileUri);- Dialog.alert(- "Could not attach pasted text",- `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,- );- }- });- pendingPastedTextAttachmentCountRef.current = Math.max(- 0,- pendingPastedTextAttachmentCountRef.current - 1,- );- setPendingPastedTextAttachmentCount(pendingPastedTextAttachmentCountRef.current);- if (AsyncResult.isFailure(attached)) {- const error = squashAtomCommandFailure(attached);- Dialog.alert(- "Could not attach pasted text",- error instanceof Error ? error.message : "Try again.",- );- }- return;- } else if (!wouldExceedInputLimit) {- insertPaste();- } else {- Dialog.alert(- wouldExceedInputLimit- ? "Pasted text is too large for this message"- : "Could not attach pasted text",- wouldExceedInputLimit- ? "Remove some text or an attachment, then paste again."- : "Remove an attachment or use a smaller paste, then try again.",- );- }- return;- }-- insertPaste();- };-- async function handleStart(): Promise<void> {- if (voiceInput.blocksSubmission || pendingPastedTextAttachmentCountRef.current > 0) return;- const selectedProject = flow.selectedProject;- const draftKey = flow.draftKey;- if (!selectedProject || !draftKey) {- return;+ return null;}if (environmentConnected &&!readEnvironmentScope(selectedProject.environmentId, AuthOrchestrationOperateScope)) {- return;+ return null;}const draft = getComposerDraftSnapshot(draftKey);- if (appAtomRegistry.get(composerContextImportsAtom)[draftKey]) return;+ if (appAtomRegistry.get(composerContextImportsAtom)[draftKey]) return null;const modelSelection =resolveSelectableModelSelection(selectedEnvironmentServerConfig,@@ -1215,7 +863,7 @@ export function NewTaskDraftScreen(props: {flow.submitting ||(workspaceMode === "worktree" && !selectedBranchName)) {- return;+ return null;}if (environmentConnected &&@@ -1231,21 +879,7 @@ export function NewTaskDraftScreen(props: {selectedProject.id,);Dialog.alert(title, detail);- return;- }- // T3's own limits command is answered by the thread composer; a new task would- // send it to the agent. A provider's same-named command, or a prompt carrying- // attachments, goes through as usual.- if (- offersUsageLimits &&- isUsageLimitsCommand(initialMessageText) &&- draft.attachments.length === 0- ) {- Dialog.alert(- "Usage limits",- "Send /usage-limits inside a thread, or open Settings → Usage → Limits.",- );- return;+ return null;}// A failed-send restore can leave the draft over the cap on purpose (it// never drops the user's files); starting anyway would upload everything@@ -1255,13 +889,13 @@ export function NewTaskDraftScreen(props: {"Too many attachments",`Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,);- return;+ return null;}const contextBlockReason = composerContextSendBlockReason(draft.context);if (contextBlockReason) {Dialog.alert("Too much context", contextBlockReason);- return;+ return null;}const strandedThread = threadContextsOutsideEnvironment({text: draft.text,@@ -1277,7 +911,7 @@ export function NewTaskDraftScreen(props: {"Attached thread unavailable",`"${strandedThread.title}" is on another machine. Switch back to ${owner} or remove it from the draft.`,);- return;+ return null;}const editingPendingTask = flow.editingPendingTask;@@ -1289,26 +923,12 @@ export function NewTaskDraftScreen(props: {messageId: editingPendingTask.messageId,createdAt: editingPendingTask.createdAt,}- : makeTurnCommandMetadata();+ : creationMetadata;const message = flow.buildPendingTaskMessage(metadata, {currentCheckoutBranch: queuesInsteadOfStarting ? null : flow.currentCheckoutBranchName,});if (!message) {- return;- }- if (!queuesInsteadOfStarting) {- // Arm the lock-screen card before the async thread creation: backgrounding- // the app right after tapping submit would otherwise reject the foreground- // -only Activity start. If creation fails, the token registration's replay- // finds no work and ends the card within seconds.- armAgentAwarenessLiveActivityForLocalWork({- environmentId: selectedProject.environmentId,- threadTitle: deriveThreadTitleSeed({- text: initialMessageText,- attachments: draft.attachments,- }),- projectTitle: selectedProject.title,- });+ return null;}// Persist before clearing the draft or leaving its editor. This only waits// for the local outbox write; server and worktree setup run on the thread.@@ -1321,8 +941,14 @@ export function NewTaskDraftScreen(props: {"Could not queue task",error instanceof Error ? error.message : "The task could not be saved to the outbox.",);- return;+ return null;}+ promptInputRef.current?.blur();+ navigation.dispatch(+ CommonActions.setParams(+ submittedThreadParams(String(message.environmentId), String(message.threadId)),+ ),+ );const draftSnapshot = getComposerDraftSnapshot(draftKey);if (editingPendingTask) {flow.finishEditingPendingTask();@@ -1335,137 +961,31 @@ export function NewTaskDraftScreen(props: {deferAttachmentCleanup: true,});}- setSubmitNavigationAction(- queuesInsteadOfStarting- ? CommonActions.goBack()- : StackActions.replace("Thread", {- environmentId: String(message.environmentId),- threadId: String(message.threadId),- }),- );scheduleUnusedComposerAttachmentCleanup(draftSnapshot.attachments);+ return message.messageId;}- if (!selectedProject) {- return (- <View className="flex-1 bg-sheet" collapsable={false}>- {Platform.OS === "android" ? (- <>- <NativeStackScreenOptions options={{ headerShown: false }} />- <AndroidScreenHeader- title="New thread"- hideBottomBorder- onBack={() => navigation.goBack()}- />- </>- ) : (- <NativeStackScreenOptions options={{ title: "Loading task" }} />- )}- </View>- );- }-- const isAndroid = Platform.OS === "android";- const canStart =- !isImportingContext &&- !cloneBlocksStart &&- taskPermissionReason === null &&- attachmentBlockReason === null &&- !modelUnavailable &&- Boolean(flow.selectedProject) &&- Boolean(flow.selectedModel) &&- (flow.prompt.trim().length > 0 || flow.attachments.length > 0) &&- isIncomingShareReady &&- !isImportingShare &&- !flow.submitting &&- pendingPastedTextAttachmentCount === 0 &&- !voiceInput.blocksSubmission &&- // Until the repository check answers, a saved worktree selection may belong to a non-git folder.- !(flow.workspaceMode === "worktree" && (!flow.selectedBranchName || !flow.isGitRepoKnown));- const openDraftDocument = (attachment: ComposerDocumentAttachment) => {- // A draft attachment lives only in the draft. Without its key the screen would fall through- // to a remote lookup for bytes the server has never seen.- const draftKey = flow.draftKey;- if (!draftKey) return;- promptInputRef.current?.blur();- void KeyboardController.dismiss({ animated: true });- navigation.dispatch(- StackActions.push("NewTaskAttachment", {- environmentId: String(selectedProject.environmentId),- attachmentId: attachment.attachmentId,- name: attachment.name,- mimeType: attachment.mimeType,- sizeBytes: String(attachment.sizeBytes),- draftKey,- }),- );- };- const promptEditor = (- <>- <ComposerEditor- draftKey={flow.draftKey}- environmentId={selectedProject.environmentId}- onOpenAttachment={openDraftDocument}- onOpenMention={(path) => {- if (!composerWorkspaceCwd) return;- promptInputRef.current?.blur();- void KeyboardController.dismiss({ animated: true });- navigation.dispatch(- StackActions.push("NewTaskFile", {- environmentId: String(selectedProject.environmentId),- cwd: composerWorkspaceCwd,- projectName: selectedProject.title,- path: fileRoutePathSegments(path),- }),- );- }}- ref={promptInputRef}- autoFocus={false}- editable={!isIncomingShareTransferPending && !flow.submitting}- readOnly={voiceInput.freezesEditor}- multiline- scrollEnabled- value={flow.prompt}- skills={composerMenu.skills}- selection={composerMenu.selection}- onChangeText={flow.setPrompt}- onSubmit={() => {- if (canStart) void handleStart();- }}- onSelectionChange={composerMenu.onSelectionChange}- onFocus={() => setIsComposerFocused(true)}- onBlur={() => setIsComposerFocused(false)}- onPasteImages={(uris) => void handleNativePasteImages(uris)}- onPasteText={(paste) => void handleNativePasteText(paste)}- placeholder="Ask anything…"- singleLineCentered={false}- contentInsetVertical={0}- style={{- minHeight: 72,- maxHeight: 160,- paddingVertical: 4,- }}- textStyle={{ ...bodyText, color: foregroundColor, fontFamily: regularFontFamily }}- />- </>- );+ // Keep the current surface until the local draft selection is ready. Publishing+ // an empty loading surface here flashes between two already-cached threads.+ if (!selectedProject) return null;- const closeNewTask = () => {- void KeyboardController.dismiss({ animated: true });- const parentNavigation = navigation.getParent();- if (parentNavigation) {- parentNavigation.goBack();- return;- }- navigation.goBack();- };+ const setupBlockReason =+ isIncomingShareReady && !isImportingShare+ ? cloneBlocksStart+ ? "Wait for the project clone to finish."+ : flow.submitting+ ? "Starting the thread…"+ : flow.workspaceMode === "worktree" && (!flow.selectedBranchName || !flow.isGitRepoKnown)+ ? "Choose a base branch before creating a worktree."+ : null+ : "Wait for shared content to finish importing.";const chooseProject = () => {if (isComposerInteractionLocked) {return;}promptInputRef.current?.blur();void KeyboardController.dismiss({ animated: true });- navigation.dispatch(StackActions.push("NewTask", { incomingShareId: props.incomingShareId }));+ navigation.navigate("NewTaskProject", { incomingShareId: props.incomingShareId });};const openContextPicker = (routeName: "NewTaskBranch" | "NewTaskEnvironment") => {if (isComposerInteractionLocked) {@@ -1473,28 +993,16 @@ export function NewTaskDraftScreen(props: {}promptInputRef.current?.blur();void KeyboardController.dismiss({ animated: true });- navigation.dispatch(StackActions.push(routeName));+ navigation.navigate(routeName);};const environmentControl = (- <ComposerInlineControl- accessibilityLabel={`Environment: ${selectedEnvironmentLabel}`}- chevronDirection="right"- disabled={isComposerInteractionLocked || voiceInput.isBusy}- renderIcon={(size) => (- <EnvironmentMachineSymbol- kind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}- size={size}- tintColorClassName="accent-icon-muted"- />- )}- label={`on ${selectedEnvironmentLabel}`}- maxWidth={flow.isScratchDraft ? 170 : 260}- onPress={- flow.environments.length > 1 ? () => openContextPicker("NewTaskEnvironment") : undefined- }- showChevron={flow.environments.length > 1}- static={flow.environments.length <= 1}+ <DraftEnvironmentControl+ connectionState={connectionState}+ label={selectedEnvironmentLabel}+ machineKind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}+ disabled={isComposerInteractionLocked}+ onChooseEnvironment={() => openContextPicker("NewTaskEnvironment")}/>);const hero = flow.isScratchDraft ? (@@ -1545,30 +1053,49 @@ export function NewTaskDraftScreen(props: {{environmentControl}</View>);- const heroViewport = (- <View className="flex-1" collapsable={false}>- <ScrollView- alwaysBounceVertical={isKeyboardVisible}- className="flex-1"- contentInsetAdjustmentBehavior="automatic"- contentContainerClassName="grow items-center pb-[236px] pt-12"- keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}- keyboardShouldPersistTaps="handled"- showsVerticalScrollIndicator={false}- style={{ flex: 1 }}- testID="new-task-hero-scroll"+ // The nested hero scroll view does not receive UIKit's automatic navigation inset in split columns.+ const heroViewport = (headerInset: number, bottomInset: number, availableHeight: number) =>+ availableHeight < 180 ? null : (+ <NativeScrollEdgeEffectsContext+ value={{ top: "hidden", bottom: "hidden", left: "hidden", right: "hidden" }}>- {hero}- </ScrollView>- </View>- );+ <View+ collapsable={false}+ style={{+ position: "absolute",+ top: headerInset,+ bottom: bottomInset,+ left: 0,+ right: 0,+ overflow: "hidden",+ }}+ >+ <ScrollView+ alwaysBounceVertical={false}+ className="flex-1"+ contentInsetAdjustmentBehavior="never"+ contentContainerClassName="grow items-center"+ contentContainerStyle={{ paddingVertical: 24 }}+ keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}+ keyboardShouldPersistTaps="handled"+ showsVerticalScrollIndicator={false}+ style={{ flex: 1 }}+ testID="new-task-hero-scroll"+ >+ <View style={{ flexGrow: 1 }} />+ {hero}+ <View style={{ flexGrow: 2 }} />+ </ScrollView>+ </View>+ </NativeScrollEdgeEffectsContext>+ );const workspaceControls = (<View className="flex-row items-center gap-1 px-2"><ComposerInlineControlaccessibilityHint={`Switches to ${flow.workspaceMode === "local" ? "a new worktree" : "the current checkout"}`}accessibilityLabel={workspaceLabel}- disabled={isComposerInteractionLocked || voiceInput.isBusy || !flow.isGitRepo}+ disabled={isComposerInteractionLocked || !flow.isGitRepo}renderIcon={(size) => (<NewTaskWorkspaceIconworkspaceMode={flow.workspaceMode}@@ -1594,280 +1121,151 @@ export function NewTaskDraftScreen(props: {</View>);- const composerPopover = composerMenu.trigger ? (- <ComposerCommandPopover- items={composerMenu.items}- triggerKind={composerMenu.trigger.kind}- isLoading={composerMenu.isLoading}- error={composerMenu.error}- onSelect={composerMenu.onSelect}- />- ) : null;- const composerDock = (- <View- className={- Platform.OS === "android" ? "bg-sheet-solid px-[12px] pt-1" : "bg-sheet px-[12px] pt-1"- }- style={{ paddingBottom: controlsBottomPadding }}- >- {!voiceInput.isBusy &&- composerMenu.trigger &&- (composerMenu.items.length > 0 || composerMenu.trigger.kind === "pull-request") ? (- Platform.OS === "ios" ? (- <View>- <ComposerPopoverAnchor>- <Animated.View entering={COMPOSER_POPOVER_ENTERING}>{composerPopover}</Animated.View>- </ComposerPopoverAnchor>- </View>- ) : (- <View className="mb-2">{composerPopover}</View>- )- ) : null}- {projectClone && projectClone.phase !== "done" && selectedProject ? (- <View className="px-1 pb-2">- <ProjectCloneBanner- clone={projectClone}- onCancel={() =>- void runCloneAction("Failed to cancel clone", () =>- cancelProjectClone({- environmentId: selectedProject.environmentId,- input: { projectId: selectedProject.id },- }),- )- }- onRetry={() =>- void runCloneAction("Failed to retry clone", () =>- retryProjectClone({- environmentId: selectedProject.environmentId,- input: { projectId: selectedProject.id },- }),- )- }- onRemove={() => void removeClonedProject()}- />- </View>- ) : null}- {flow.canChooseWorkspace ? <View className="pb-1">{workspaceControls}</View> : null}-- {taskPermissionReason ? (- <Text className="px-3 py-2 text-xs text-muted-foreground">{taskPermissionReason}</Text>- ) : null}-- {modelUnavailable ? (- <Button- label="Model unavailable. Open model settings."- tone="text"- disabled={isComposerInteractionLocked}- onPress={settingsSheetPresentation.open}- />- ) : null}-- <ComposerSurface- style={{- borderRadius: 26,- minHeight: 140,- overflow: "hidden",- paddingBottom: 6,- paddingTop: 14,- }}- >- {stripAttachments.length > 0 ? (- <View className="px-[14px] pb-2.5">- <ComposerAttachmentStrip- environmentId={selectedProject.environmentId}- attachments={stripAttachments}- imageBorderRadius={16}- imageSize={72}- onRemove={- isComposerInteractionLocked || voiceInput.isBusy- ? () => undefined- : flow.removeAttachment- }- onPressPreview={- isComposerInteractionLocked || voiceInput.isBusy ? undefined : openFilePreview- }- onPressVideo={- isComposerInteractionLocked || voiceInput.isBusy ? undefined : openVideoPreview- }- onPressDocument={- isComposerInteractionLocked || voiceInput.isBusy- ? undefined- : (attachment) =>- openDraftDocument({- attachmentId: attachment.id,- name: attachment.name,- mimeType: attachment.mimeType,- sizeBytes: attachment.sizeBytes,- })- }- />- </View>- ) : null}-- <View className="px-[14px]">{promptEditor}</View>- <View className="h-1" />-- <Animated.View layout={COMPOSER_LAYOUT_TRANSITION} collapsable={false}>- <ComposerDictationToolbar showsDictation={isVoiceInputPresented}>- <ComposerToolbarRow- paddingBottom={0}- paddingHorizontal={0}- paddingTop={0}- style={{ gap: 0 }}- >- <ComposerDictationCancelAction- presentation={voicePresentation}- onCancel={voiceInput.cancel}- />- {isVoiceInputPresented ? (- <ComposerDictationStatus- audioLevels={voiceInput.audioLevels}- elapsedSeconds={voiceInput.elapsedSeconds}- phase={voiceInput.state.phase}- presentation={voicePresentation}- onDismissError={voiceInput.cancel}- />- ) : (- <>- <ComposerAttachmentButton- disabled={isComposerInteractionLocked}- supportsFiles={Boolean(- selectedEnvironmentServerConfig?.environment.capabilities.fileAttachments,- )}- onPickMedia={handlePickMedia}- onPickFiles={handlePickFiles}- />- <View className="min-w-0 flex-1 flex-row items-center justify-end gap-2">- <View className="min-w-0 shrink">- <ComposerModelControl- modelOption={flow.selectedModelOption}- selection={flow.selectedModel}- provider={flow.selectedProviderStatus?.driver}- prompt={flow.prompt}- surfaceColor={theme["--color-composer-panel"]}- disabled={isComposerInteractionLocked}- onPress={settingsSheetPresentation.open}- />- </View>- {flow.planModeEnabled ? (- <ComposerInlineControl- accessibilityHint={`Switches to ${flow.interactionMode === "plan" ? "Build" : "Plan"} mode`}- accessibilityLabel={`Interaction mode: ${flow.interactionMode === "plan" ? "Plan" : "Build"}`}- disabled={isComposerInteractionLocked}- emphasized- icon={- flow.interactionMode === "plan"- ? { ios: "list.bullet.clipboard", android: "auto_awesome" }- : { ios: "hammer", android: "construction" }- }- label={flow.interactionMode === "plan" ? "Plan" : "Build"}- onPress={() =>- flow.setInteractionMode(- flow.interactionMode === "plan" ? "default" : "plan",- )- }- showChevron={false}- />- ) : null}- </View>- </>- )}- <ComposerDictationPrimaryAction- state={voiceInput.state}- presentation={voicePresentation}- isAvailable={voiceInput.isAvailable}- disabled={isIncomingShareTransferPending || isImportingShare || flow.submitting}- onStart={voiceInput.start}- onConfirm={voiceInput.stop}- onCancel={voiceInput.cancel}- />- {voicePresentation.showsSend ? (- <ComposerActionButton- accessibilityLabel={- taskPermissionReason ??- attachmentBlockReason ??- (cloneBlocksStart- ? projectClone === null || projectClone.phase === "running"- ? "Cloning repository"- : "Repository not cloned"- : pendingPastedTextAttachmentCount > 0- ? "Attaching pasted text"- : flow.submitting- ? "Starting task"- : attachmentsUploading- ? "Queue task, sends when uploads finish"- : environmentConnected- ? "Start task"- : "Queue task")- }- disabled={!canStart}- icon={queuesInsteadOfStarting ? "tray.and.arrow.up" : "arrow.up"}- onPress={() => void handleStart()}- variant="primary"- />- ) : null}- </ComposerToolbarRow>- </ComposerDictationToolbar>- </Animated.View>- </ComposerSurface>- <VideoPreviewModal source={previewVideo} onRequestClose={closeMediaPreview} />- <FilePreviewModal source={previewFile} onRequestClose={closeMediaPreview} />- </View>- );-- if (isAndroid) {+ if (!flow.selectedModel) {return (- <View className="flex-1 bg-sheet" collapsable={false}>- <NativeStackScreenOptions options={{ headerShown: false }} />- <SheetHeader+ <ThreadScreenFallback>+ <AppBartitle="New thread"- onCancel={closeNewTask}- accessibilityLabel="Cancel new task"+ sidebar={false}+ onBack={goBack}+ options={{+ ...threadHeaderAppearance(NATIVE_LIQUID_GLASS_SUPPORTED),+ unstable_headerSubtitle: undefined,+ unstable_headerRightItems: () => [],+ unstable_headerToolbarItems: () => [],+ }}/>- <ScreenContent>- {heroViewport}-- <KeyboardStickyView- style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}- offset={{ closed: 0, opened: keyboardOpenedOffset }}- >- {composerDock}- </KeyboardStickyView>- </ScreenContent>- </View>+ <View className="flex-1 justify-end gap-3 p-4">+ {environmentControl}+ <Text className="text-foreground-muted">+ Your draft is saved on this device. Connect to an environment to choose its first model.+ </Text>+ <ComposerEditor+ draftKey={flow.draftKey}+ value={flow.prompt}+ onChangeText={flow.setPrompt}+ placeholder="Ask the repo agent, or run a command…"+ multiline+ style={{ minHeight: 64 }}+ />+ </View>+ </ThreadScreenFallback>);}-+ const thread = draftThreadShell({+ environmentId: selectedProject.environmentId,+ projectId: selectedProject.id,+ threadId: ThreadId.make(flow.editingPendingTask?.threadId ?? creationMetadata.threadId),+ modelSelection: flow.selectedModel,+ runtimeMode: flow.runtimeMode,+ interactionMode: flow.interactionMode,+ branch: flow.selectedBranchName,+ worktreePath: flow.selectedWorktreePath,+ createdAt: creationMetadata.createdAt,+ });return (- <View className="flex-1 bg-sheet" collapsable={false}>- <NativeStackScreenOptions- options={{- headerBackVisible: false,- headerShadowVisible: false,- title: "New thread",- unstable_navigationItemStyle: "editor",+ <>+ <ThreadScreenBinding+ environmentId={selectedProject.environmentId}+ header={+ <DraftThreadHeader thread={thread} project={selectedProject} cwd={composerWorkspaceCwd} />+ }+ draftMode={{+ content: heroViewport,+ controls: (+ <View className="px-3 pb-1">+ {projectClone && projectClone.phase !== "done" && selectedProject ? (+ <View className="px-1 pb-2">+ <ProjectCloneBanner+ clone={projectClone}+ onCancel={() =>+ void runCloneAction("Failed to cancel clone", () =>+ cancelProjectClone({+ environmentId: selectedProject.environmentId,+ input: { projectId: selectedProject.id },+ }),+ )+ }+ onRetry={() =>+ void runCloneAction("Failed to retry clone", () =>+ retryProjectClone({+ environmentId: selectedProject.environmentId,+ input: { projectId: selectedProject.id },+ }),+ )+ }+ onRemove={() => void removeClonedProject()}+ />+ </View>+ ) : null}+ {flow.canChooseWorkspace ? workspaceControls : null}+ </View>+ ),+ editorRef: promptInputRef,+ sendBlockedReason: setupBlockReason,+ interactionLocked: isComposerInteractionLocked,}}+ canOperateThread={canOperate}+ selectedThread={thread}+ selectedThreadDetailRef={null}+ contentPresentation={{ kind: "ready" }}+ screenTone={connectionTone(connectionState)}+ connectionError={environmentRuntime?.connectionError ?? null}+ environmentLabel={selectedEnvironmentLabel}+ feedbackSubmissions={[]}+ onDismissFeedback={() => {}}+ selectedThreadFeed={[]}+ activityRun={null}+ activeWorkStartedAt={null}+ isCompacting={false}+ creationState={null}+ activePendingApproval={null}+ activePendingApprovals={[]}+ respondingApprovalId={null}+ activePendingUserInput={null}+ activePendingUserInputDrafts={{}}+ activePendingUserInputAnswers={null}+ respondingUserInputId={null}+ connectionStateLabel={connectionState}+ activeThreadBusy={false}+ canStopThread={false}+ queuedRunEdit={null}+ composerDraftKey={flow.draftKey}+ followUpBehavior="queue"+ canSteerActiveTurn={false}+ isSavingQueuedEdit={false}+ onCancelQueuedRunEdit={() => {}}+ onRemoveQueuedEditAttachment={() => {}}+ projectWorkspaceRoot={selectedProject.workspaceRoot}+ threadCwd={composerWorkspaceCwd}+ selectedThreadQueueCount={0}+ queuedMessages={[]}+ dispatchingMessageId={null}+ serverConfig={selectedEnvironmentServerConfig}+ usesAutomaticContentInsets+ onOpenConnectionEditor={() => navigation.navigate("Connections")}+ onChangeDraftMessage={flow.setPrompt}+ onPickDraftMedia={handlePickMedia}+ onPickDraftFiles={handlePickFiles}+ onNativePasteImages={handleNativePasteImages}+ onNativePasteText={handleNativePasteText}+ onRemoveDraftImage={flow.removeAttachment}+ onStopThread={() => {}}+ onResumeQueue={null}+ onSendMessage={handleStart}+ onReconnectEnvironment={() => onReconnectEnvironment(selectedProject.environmentId)}+ canSwitchThreadProvider+ onUpdateThreadModelSelection={(selection) =>+ flow.setSelectedModelKey(`${selection.instanceId}:${selection.model}`, selection.options)+ }+ onUpdateThreadRuntimeMode={flow.setRuntimeMode}+ onUpdateThreadInteractionMode={flow.planModeEnabled ? flow.setInteractionMode : undefined}+ onRespondToApproval={async () => {}}+ onSelectUserInputOption={() => {}}+ onChangeUserInputCustomAnswer={() => {}}+ onSubmitUserInput={async () => {}}+ onDismissUserInput={async () => {}}/>- <SheetHeader- title="New thread"- onCancel={closeNewTask}- accessibilityLabel="Cancel new task"- />-- {heroViewport}- <KeyboardStickyView- pointerEvents="box-none"- style={{ position: "absolute", top: 0, bottom: 0, left: 0, right: 0 }}- offset={{ closed: 0, opened: keyboardOpenedOffset }}- >- <Animated.View- layout={COMPOSER_LAYOUT_TRANSITION}- pointerEvents="box-none"- style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}- >- {composerDock}- </Animated.View>- </KeyboardStickyView>- </View>+ </>);}diff --git a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsxindex 701d641b79f..2ecfdd44a0e 100644--- a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx+++ b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx@@ -1,3 +1,4 @@+import { isDraftThreadRoute } from "./thread-route-state";import * as Dialog from "../../components/ui/Dialog";import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";import { NavigationRow } from "../../components/ui/NavigationRow";@@ -31,7 +32,7 @@ import { useAtomCommand } from "../../state/use-atom-command";import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";import type { WorkspaceState } from "../../state/workspaceModel";import { useWorkspaceState } from "../../state/workspace";-import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";+import { usePromptLinkResolver } from "../prompt-links/usePromptLinkResolver";import { useIncomingShare } from "../sharing/IncomingShareProvider";import { useNewTaskFlow } from "./new-task-flow-provider";@@ -113,36 +114,37 @@ function NewTaskHeader(props: {readonly onSearchTextChange: (text: string) => void;}) {const navigation = useNavigation();- const { layout } = useAdaptiveWorkspaceLayout();+ const goBack = () => {+ if (navigation.canGoBack()) navigation.goBack();+ else navigation.getParent()?.goBack();+ };return (- <AppBar- title={props.title}- subtitle={props.subtitle ?? undefined}- sidebar={false}- backInSplitView={{- accessibilityLabel: "Go back",- icon: "chevron.left",- }}- options={{ headerBackVisible: !layout.usesSplitView }}- hideBottomBorder- onBack={() => navigation.goBack()}- actions={- props.canAddProject- ? [- {- accessibilityLabel: "Add project",- icon: "plus",- onPress: () => navigation.dispatch(StackActions.push("AddProject")),- },- ]- : []- }- search={{- value: props.searchText,- onChangeText: props.onSearchTextChange,- placeholder: "Search projects",- }}- />+ <>+ <AppBar+ title={props.title}+ subtitle={props.subtitle ?? undefined}+ sidebar={false}+ options={{ headerBackVisible: true }}+ hideBottomBorder+ onBack={goBack}+ actions={+ props.canAddProject+ ? [+ {+ accessibilityLabel: "Add project",+ icon: "plus",+ onPress: () => navigation.dispatch(StackActions.push("AddProject")),+ },+ ]+ : []+ }+ search={{+ value: props.searchText,+ onChangeText: props.onSearchTextChange,+ placeholder: "Search projects",+ }}+ />+ </>);}@@ -219,22 +221,23 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParareturn;}}- const state = navigation.getState();- const previousRoute = state?.routes[state.index - 1];- if (previousRoute?.name === "NewTaskDraft") {+ const root = navigation.getState()?.routeNames.includes("NewTaskProject")+ ? navigation+ : navigation.getParent();+ const rootState = root?.getState();+ const threadRoute = rootState?.routes[rootState.index - 1];+ if (isDraftThreadRoute(threadRoute)) {setProject(project);- navigation.goBack();+ root?.goBack();return;}-- navigation.dispatch(- StackActions.push("NewTaskDraft", {- environmentId: project.environmentId,- projectId: project.id,- title: project.title,+ root?.navigate("Thread", {+ draft: {+ environmentId: String(project.environmentId),+ projectId: String(project.id),incomingShareId: incomingShare?.id,- }),- );+ },+ });}async function startScratch(): Promise<void> {@@ -280,14 +283,17 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParareturn;}resumedDestinationKeyRef.current = destinationKey;- navigation.dispatch(- StackActions.push("NewTaskDraft", {+ (navigation.getState()?.routeNames.includes("NewTaskProject")+ ? navigation+ : navigation.getParent()+ )?.navigate("Thread", {+ draft: {environmentId: reservedDestinationProject.environmentId,projectId: reservedDestinationProject.id,title: reservedDestinationProject.title,incomingShareId: incomingShare.id,- }),- );+ },+ });}, [incomingShare, isFocused, navigation, reservedDestinationProject]);return (diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsxindex a55498552b4..08ae70f3009 100644--- a/apps/mobile/src/features/threads/ThreadComposer.tsx+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx@@ -1,3 +1,4 @@+import { useSidebarWorkspaceTabs } from "../workspace/useSystemWorkspaceTabBar";import { Button } from "../../components/ui/Button";import * as Dialog from "../../components/ui/Dialog";import type { ComposerTextPaste } from "../../native/T3ComposerEditor.types";@@ -139,9 +140,95 @@ function collapsedEditorInset(text: ScaledTextRole): number {return Math.max(0, Math.round(COLLAPSED_EDITOR_DEFAULT_INSET - shift));}-export const COMPOSER_EXPANDED_CHROME = 156;+export function useCompactComposerEditor(text: ScaledTextRole, value: string) {+ const [contentSize, setContentSize] = useState({ width: 0, height: 0 });+ const [compactWidth, setCompactWidth] = useState(0);+ const contentHeight = contentSize.height;+ const rowWidth = useSharedValue(0);+ const editorX = useSharedValue(0);+ const editorWidth = useSharedValue(0);+ const inset = Platform.OS === "android" ? 0 : collapsedEditorInset(text);+ const minimum = Math.max(INLINE_EDITOR_HEIGHT, Math.ceil(text.lineHeight) + 2 * inset);+ const height = Math.max(+ minimum,+ Math.min(text.lineHeight * 4 + 2 * inset, contentHeight + 2 * inset),+ );+ // A line that fits the expanded editor may still overflow its compact slot.+ // Compare its measured width too so widening cannot trigger a collapse loop.+ const isExpanded =+ value.length > 0 &&+ (contentHeight > text.lineHeight * 1.5 ||+ (compactWidth > 0 && contentSize.width > compactWidth));+ const compactRowHeight = Math.max(44, minimum);+ const animatedHeight = useSharedValue(height);+ const surfaceHeight = useSharedValue(compactRowHeight);+ const targetSurfaceHeight = isExpanded ? height + 52 : compactRowHeight;+ const expansion = useSharedValue(0);+ useLayoutEffect(() => {+ const config = { duration: 180, reduceMotion: ReduceMotion.System };+ if (Platform.OS === "android") {+ animatedHeight.set(height);+ surfaceHeight.set(targetSurfaceHeight);+ expansion.set(Number(isExpanded));+ return;+ }+ // Resolve wrapping at the destination width before animating vertically.+ // Intermediate widths otherwise produce taller measurements mid-transition.+ let nextFrame: number | undefined;+ const frame = requestAnimationFrame(() => {+ nextFrame = requestAnimationFrame(() => {+ animatedHeight.set(withTiming(height, config));+ surfaceHeight.set(withTiming(targetSurfaceHeight, config));+ expansion.set(withTiming(Number(isExpanded), config));+ });+ });+ return () => {+ cancelAnimationFrame(frame);+ if (nextFrame !== undefined) cancelAnimationFrame(nextFrame);+ };+ }, [animatedHeight, expansion, height, isExpanded, surfaceHeight, targetSurfaceHeight]);+ const containerStyle = useAnimatedStyle(() => ({+ height: surfaceHeight.value,+ }));+ const editorStyle = useAnimatedStyle(() => ({+ position: "absolute",+ overflow: "hidden",+ height: animatedHeight.value,+ left: isExpanded ? 14 : editorX.value + 4,+ right: isExpanded ? 14 : rowWidth.value - editorX.value - editorWidth.value + 4,+ bottom:+ (compactRowHeight - minimum) / 2 + expansion.value * (52 - (compactRowHeight - minimum) / 2),+ }));+ return {+ isExpanded,+ containerStyle,+ editorStyle,+ onRowLayout: (event: { nativeEvent: { layout: { width: number } } }) => {+ rowWidth.set(event.nativeEvent.layout.width);+ },+ onEditorLayout: (event: { nativeEvent: { layout: { x: number; width: number } } }) => {+ // The expanded toolbar gives this slot to the model control. Keep the+ // compact geometry for the return transition, rather than recording zero.+ if (!isExpanded) {+ editorX.set(event.nativeEvent.layout.x);+ editorWidth.set(event.nativeEvent.layout.width);+ setCompactWidth(Math.max(0, event.nativeEvent.layout.width - 8));+ }+ },+ editorProps: {+ singleLineCentered: false,+ scrollEnabled: Platform.OS === "android" || contentHeight >= text.lineHeight * 4,+ contentInsetVertical: inset,+ onContentSizeChange: (size: { width: number; height: number }) => {+ setContentSize(size);+ },+ style: { flex: 1 },+ },+ };+}export interface ThreadComposerProps {+ readonly isDraft?: boolean;readonly canOperateThread: boolean;readonly placeholder: string;readonly contentMaxWidth?: number;@@ -159,6 +246,7 @@ export interface ThreadComposerProps {readonly environmentId: EnvironmentId;readonly projectCwd: string | null;readonly sendBlockedReason?: string | null;+ readonly interactionLocked?: boolean;readonly draftKey?: string;readonly queuedEdit?: {readonly existingAttachments: ReadonlyArray<ChatAttachment>;@@ -187,9 +275,8 @@ export interface ThreadComposerProps {readonly canSwitchProvider: boolean;readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;- readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;- /** True while the draft is stacked above the controls rather than in the one-row capsule. */- readonly onExpandedChange?: (expanded: boolean) => void;+ readonly onUpdateInteractionMode?: (interactionMode: ProviderInteractionMode) => void;+ readonly onHeightChange?: (height: number) => void;readonly onEditorFocusChange?: (focused: boolean) => void;}@@ -224,8 +311,6 @@ export const COMPOSER_LAYOUT_TRANSITION =Platform.OS === "android" ? undefined : composerHeightTransition;// Share of the one-row composer the draft keeps; a long model name truncates first.const INLINE_EDITOR_MIN_WIDTH = "40%";-// The one-row editor's horizontal padding plus room for the caret.-const INLINE_EDITOR_TEXT_SLACK = 10;const INLINE_EDITOR_HEIGHT = 36;const COMPOSER_ATTACHMENT_ENTERING =@@ -248,6 +333,7 @@ const FOLLOW_UP_ACTION_SUBTITLE = {} as const;function SendActionButton(props: {+ readonly size?: "regular" | "large";readonly accessibilityLabel: string;readonly presentation: ComposerSendPresentation;readonly disabled: boolean;@@ -257,6 +343,7 @@ function SendActionButton(props: {const button = (<ComposerActionButtonaccessibilityLabel={props.accessibilityLabel}+ size={props.size}icon={presentation.icon}variant="primary"disabled={props.disabled}@@ -306,8 +393,10 @@ export function ComposerSurface(props: {}): targetBorderRadius;}, [animatedBorderRadius, shouldAnimate, targetBorderRadius]);+ const borderCurve = props.style.borderCurve;const animatedShapeStyle = useAnimatedStyle(() => ({borderRadius: animatedBorderRadius.value,+ ...(borderCurve ? { borderCurve } : {}),}));const layoutTransition = shouldAnimate ? COMPOSER_LAYOUT_TRANSITION : undefined;@@ -373,7 +462,6 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerPropsconst settingsRoutePresentedRef = useRef(false);const wasExpandedBeforePreviewRef = useRef(false);const inFlightThreadIdsRef = useRef(new Set<string>());- const { onExpandedChange } = props;const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);@@ -480,7 +568,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerPropspullRequestRepository: project?.repositoryIdentity?.displayName ?? null,threadPullRequests: props.selectedThread.pullRequests,selectedProviderStatus,- hasThread: true,+ hasThread: !props.isDraft,hasCompactableConversation: props.hasCompactableConversation,onChangeDraftMessage: props.onChangeDraftMessage,onUpdateInteractionMode:@@ -500,7 +588,8 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerPropsonChangeDraftMessage: (text) => setComposerDraftText(composerDraftKey, text),onChangeSelection: composerMenu.onSelectionChange,});- const isSubmissionLocked = queuedEdit?.saving === true || voiceInput.blocksSubmission;+ const isSubmissionLocked =+ props.interactionLocked === true || queuedEdit?.saving === true || voiceInput.blocksSubmission;const voicePresentation = resolveVoiceComposerPresentation(voiceInput.state,voiceInput.elapsedSeconds,@@ -508,35 +597,12 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerPropsconst isVoiceInputPresented = voicePresentation.statusLabel !== null;const isExpanded = isFocused || settingsSheetPresentation.keepsComposerExpanded;const { setComposerEditing } = useAdaptiveWorkspaceLayout();- // The composer stays one row, with the model picker in it, until the draft would- // wrap. Then the draft stacks above the controls and returns to the row once it- // fits again. The native editor reports its laid-out text size: more than one- // line means the draft wrapped where it is, and the widest line is a one-line- // draft's natural width, which is compared with the row's text area so a draft- // laid out in the wider card still returns to the row when it fits, including- // when the pane widens. The measurements live in refs and only the verdict is- // state, so a keystroke that keeps the verdict costs no extra render.- const draftSizeRef = useRef({ width: 0, height: 0 });- const rowGeometryRef = useRef({ surfaceWidth: 0, leadingWidth: 0, trailingWidth: 0 });- const [draftOverflowsRow, setDraftOverflowsRow] = useState(false);- const lineHeight = bodyText.lineHeight;- const updateDraftOverflow = () => {- const { width, height } = draftSizeRef.current;- const row = rowGeometryRef.current;- const rowTextWidth =- row.surfaceWidth - row.leadingWidth - row.trailingWidth - INLINE_EDITOR_TEXT_SLACK;- setDraftOverflowsRow(- height > lineHeight * 1.5 || (row.surfaceWidth > 0 && width > rowTextWidth),- );- };- const measureRow = (key: keyof typeof rowGeometryRef.current, value: number) => {- if (rowGeometryRef.current[key] === value) return;- rowGeometryRef.current = { ...rowGeometryRef.current, [key]: value };- updateDraftOverflow();- };- const usesCard = isExpanded && draftMessage.length > 0 && draftOverflowsRow;- const showsCompactDictation = isVoiceInputPresented && !usesCard;- const isToolbarVisible = usesCard || isVoiceInputPresented;+ const hasSidebarTabBar = useSidebarWorkspaceTabs() === "picker";+ const [compactRowWidth, setCompactRowWidth] = useState(0);+ const compactAttachmentLimit = compactRowWidth >= 500 ? 3 : 1;+ const compactEditor = useCompactComposerEditor(bodyText, draftMessage);+ const showsCompactDictation = isVoiceInputPresented;+ const isToolbarVisible = isVoiceInputPresented;const hasEditingAttachments =(queuedEdit !== null && queuedEdit.existingAttachments.length > 0) ||stripAttachments.length > 0;@@ -561,9 +627,6 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerPropssendBlockedReason === null &&!modelUnavailable;- useEffect(() => {- onExpandedChange?.(usesCard);- }, [usesCard, onExpandedChange]);useEffect(() => () => setComposerEditing(false), [setComposerEditing]);const onPressPreview = (source: FilePreviewSource) => {@@ -609,6 +672,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerPropsconst handleSend = async (followUp?: ActiveTurnComposerAction) => {if (isSubmissionLocked ||+ sendBlockedReason !== null ||pendingPastedTextAttachmentCountRef.current > 0 ||pendingNativeImagePasteCountRef.current > 0)@@ -743,7 +807,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps<>{queuedEdit !== null && queuedEdit.existingAttachments.length > 0 ? (<Animated.View- className="px-[14px] pb-2.5"+ className="px-[14px] pb-2.5 pt-2"entering={COMPOSER_ATTACHMENT_ENTERING}exiting={FadeOut.duration(120)}>@@ -757,7 +821,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps) : null}{stripAttachments.length > 0 ? (<Animated.View- className="px-[14px] pb-2.5"+ className="px-[14px] pb-2.5 pt-2"entering={COMPOSER_ATTACHMENT_ENTERING}exiting={FadeOut.duration(120)}>@@ -789,14 +853,16 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerPropsconst modelControl = (<View className="min-w-0 shrink"><ComposerModelControl+ size={hasSidebarTabBar ? "large" : "regular"}modelOption={currentModelOption}selection={currentModelSelection}provider={selectedProviderStatus?.driver}reportedSelection={props.reportedModelSelection}prompt={draftMessage}surfaceColor={composerPanel}- iconOnly={!usesCard && draftMessage.length > 0}- showSummary={usesCard}+ iconOnly={+ (draftMessage.length > 0 || stripAttachments.length > 0) && !compactEditor.isExpanded+ }onPress={openSettings}/></View>@@ -804,10 +870,11 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerPropsreturn (<Animated.View+ onLayout={(event) => props.onHeightChange?.(event.nativeEvent.layout.height)}className="px-[12px]"style={{- paddingTop: usesCard ? 8 : 6,- paddingBottom: (props.bottomInset ?? 0) + (usesCard ? 8 : THREAD_COMPOSER_BOTTOM_GUTTER),+ paddingTop: 6,+ paddingBottom: (props.bottomInset ?? 0) + THREAD_COMPOSER_BOTTOM_GUTTER,backgroundColor:Platform.OS === "android" ? themeColorWithAlpha(composerPanel, 1) : undefined,}}@@ -826,7 +893,6 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps<Animated.ViewclassName="relative w-full self-center"style={{ maxWidth: props.contentMaxWidth }}- onLayout={(event) => measureRow("surfaceWidth", event.nativeEvent.layout.width)}>{!isSubmissionLocked &&composerMenu.trigger &&@@ -872,29 +938,28 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps) : null}<ComposerSurface- style={- usesCard- ? {- borderRadius: 26,- overflow: "hidden" as const,- paddingBottom: 6,- paddingTop: 14,- }- : {- borderRadius: 27,- overflow: "hidden" as const,- paddingVertical: 2,- }- }+ animateLayout={false}+ style={{+ borderRadius: hasSidebarTabBar ? 31 : 27,+ borderCurve: "circular",+ overflow: "hidden",+ paddingVertical: hasSidebarTabBar ? 9 : 2,+ }}>- {isExpanded && !usesCard ? editingAttachments : null}- <ComposerDictationDraftContent- className={usesCard ? undefined : "flex-row items-center"}- compact={!usesCard}- hidden={showsCompactDictation}+ {isExpanded ? editingAttachments : null}+ <View+ onLayout={(event) => {+ compactEditor.onRowLayout(event);+ setCompactRowWidth(event.nativeEvent.layout.width);+ }}>- {!usesCard ? (+ <ComposerDictationDraftContent+ className="flex-row items-end"+ compact+ hidden={showsCompactDictation}+ ><ComposerAttachmentButton+ size={hasSidebarTabBar ? "large" : "regular"}disabled={isSubmissionLocked}supportsFiles={Boolean(props.serverConfig?.environment.capabilities.fileAttachments,@@ -902,17 +967,91 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerPropsonPickMedia={props.onPickDraftMedia}onPickFiles={props.onPickDraftFiles}/>- ) : null}- {usesCard ? editingAttachments : null}+ <Animated.View+ className="min-w-0 flex-1"+ onLayout={compactEditor.onEditorLayout}+ style={[+ {+ minWidth:+ compactEditor.isExpanded || stripAttachments.length > 0+ ? 0+ : INLINE_EDITOR_MIN_WIDTH,+ },+ compactEditor.containerStyle,+ compactEditor.isExpanded ? { flex: 0, width: 0 } : undefined,+ ]}+ ></Animated.View>+ {!isExpanded && stripAttachments.length > 0 ? (+ <View className="h-[44px] shrink-0 flex-row items-center gap-1 pl-1">+ {stripAttachments.slice(0, compactAttachmentLimit).map((attachment) => (+ <ComposerAttachmentThumbnail+ environmentId={props.environmentId}+ key={attachment.id}+ attachment={attachment}+ size={30}+ borderRadius={8}+ compact+ onPressPreview={isSubmissionLocked ? undefined : onPressPreview}+ onPressVideo={isSubmissionLocked ? undefined : onPressVideo}+ />+ ))}+ {stripAttachments.length > compactAttachmentLimit ? (+ <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">+ <Text className="text-foreground-muted text-2xs font-t3-bold">+ +{stripAttachments.length - compactAttachmentLimit}+ </Text>+ </View>+ ) : null}+ </View>+ ) : null}+ <View+ className="min-w-0 shrink flex-row items-center"+ style={+ compactEditor.isExpanded ? { flex: 1, justifyContent: "flex-end" } : undefined+ }+ >+ {modelControl}+ <ComposerDictationStartAction+ size={hasSidebarTabBar ? "large" : "regular"}+ state={voiceInput.state}+ isAvailable={voiceInput.isAvailable}+ disabled={isSubmissionLocked}+ onStart={voiceInput.start}+ onCancel={voiceInput.cancel}+ />+ {showStopAction ? (+ <ComposerActionButton+ size={hasSidebarTabBar ? "large" : "regular"}+ accessibilityLabel="Stop agent"+ icon="stop.fill"+ variant="danger"+ disabled={!props.canOperateThread}+ onPress={props.onStopThread}+ />+ ) : showResumeAction ? (+ <ComposerActionButton+ size={hasSidebarTabBar ? "large" : "regular"}+ accessibilityLabel="Resume queue"+ icon="play"+ disabled={!props.canOperateThread || resumingQueue}+ onPress={() => void handleResumeQueue()}+ />+ ) : (+ <SendActionButton+ size={hasSidebarTabBar ? "large" : "regular"}+ accessibilityLabel={sendBlockedReason ?? sendLabel}+ presentation={sendPresentation}+ disabled={!canSend}+ onSend={handleSend}+ />+ )}+ </View>+ </ComposerDictationDraftContent><Animated.View- className={usesCard ? "px-[14px]" : "min-w-0 flex-1 px-[4px]"}- style={usesCard ? undefined : { minWidth: INLINE_EDITOR_MIN_WIDTH }}- layout={COMPOSER_LAYOUT_TRANSITION}- onLayout={- usesCard- ? undefined- : (event) => measureRow("leadingWidth", event.nativeEvent.layout.x)- }+ style={[+ compactEditor.editorStyle,+ showsCompactDictation ? { display: "none" } : undefined,+ ]}><ComposerEditorhidden={props.hidden}@@ -920,11 +1059,19 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerPropsenvironmentId={props.environmentId}onOpenMention={(path) => {Keyboard.dismiss();- navigation.navigate("ThreadFile", {- environmentId: String(props.environmentId),- threadId: String(props.selectedThread.id),- path: fileRoutePathSegments(path),- });+ if (props.isDraft) {+ navigation.navigate("NewTaskFile", {+ environmentId: String(props.environmentId),+ cwd: props.projectCwd ?? undefined,+ path: fileRoutePathSegments(path),+ });+ } else {+ navigation.navigate("ThreadFile", {+ environmentId: String(props.environmentId),+ threadId: String(props.selectedThread.id),+ path: fileRoutePathSegments(path),+ });+ }}}onOpenAttachment={openDraftDocument}chipsInert={!isExpanded}@@ -1034,117 +1181,20 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps? sendPresentation.label: FOLLOW_UP_ACTION_LABEL[sendPresentation.alternate]}- scrollEnabled={isExpanded}- singleLineCentered={!usesCard}- contentInsetVertical={- usesCard || Platform.OS === "android" ? 0 : collapsedEditorInset(bodyText)- }- onContentSizeChange={(size) => {- draftSizeRef.current = size;- updateDraftOverflow();- }}- style={- usesCard- ? {- // A stacked draft shows two to four lines, then scrolls.- minHeight: lineHeight * 2 + 8,- maxHeight: lineHeight * 4 + 8,- paddingVertical: 4,- }- : {- // Large text sizes need room for one full line plus the iOS inset.- height: Math.max(- INLINE_EDITOR_HEIGHT,- Math.ceil(lineHeight) +- (Platform.OS === "android" ? 0 : 2 * collapsedEditorInset(bodyText)),- ),- }- }+ {...compactEditor.editorProps}textStyle={{...bodyText,color: foregroundColor,}}/></Animated.View>- {!isExpanded && stripAttachments.length > 0 ? (- <View className="flex-row gap-1 pl-1">- {stripAttachments.slice(0, 3).map((attachment) => (- <ComposerAttachmentThumbnail- environmentId={props.environmentId}- key={attachment.id}- attachment={attachment}- size={30}- borderRadius={8}- compact- onPressPreview={isSubmissionLocked ? undefined : onPressPreview}- onPressVideo={isSubmissionLocked ? undefined : onPressVideo}- />- ))}- {stripAttachments.length > 3 ? (- <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">- <Text className="text-foreground-muted text-2xs font-t3-bold">- +{stripAttachments.length - 3}- </Text>- </View>- ) : null}- </View>- ) : null}- {!usesCard ? (- <View- className="min-w-0 shrink flex-row items-center"- onLayout={(event) => measureRow("trailingWidth", event.nativeEvent.layout.width)}- >- {modelControl}- <ComposerDictationStartAction- state={voiceInput.state}- isAvailable={voiceInput.isAvailable}- disabled={isSubmissionLocked}- onStart={voiceInput.start}- onCancel={voiceInput.cancel}- />- {showStopAction ? (- <ComposerActionButton- accessibilityLabel="Stop agent"- icon="stop.fill"- variant="danger"- disabled={!props.canOperateThread}- onPress={props.onStopThread}- />- ) : showResumeAction ? (- <ComposerActionButton- accessibilityLabel="Resume queue"- icon="play"- disabled={!props.canOperateThread || resumingQueue}- onPress={() => void handleResumeQueue()}- />- ) : (- <SendActionButton- accessibilityLabel={sendBlockedReason ?? sendLabel}- presentation={sendPresentation}- disabled={!canSend}- onSend={handleSend}- />- )}- </View>- ) : null}- {usesCard ? <View className="h-1" /> : null}- </ComposerDictationDraftContent>+ </View><Animated.ViewaccessibilityElementsHidden={!isToolbarVisible}collapsable={false}importantForAccessibility={isToolbarVisible ? "auto" : "no-hide-descendants"}- layout={COMPOSER_LAYOUT_TRANSITION}pointerEvents={isToolbarVisible ? "auto" : "none"}- style={- usesCard- ? undefined- : {- position: "absolute",- bottom: 2,- left: 0,- right: 0,- }- }+ style={{ position: "absolute", bottom: hasSidebarTabBar ? 9 : 2, left: 0, right: 0 }}><ComposerDictationToolbarshowsDictation={isVoiceInputPresented}@@ -1157,6 +1207,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerPropsstyle={{ gap: 0 }}><ComposerDictationCancelAction+ size={hasSidebarTabBar ? "large" : "regular"}presentation={voicePresentation}onCancel={voiceInput.cancel}/>@@ -1171,6 +1222,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps) : (<View className="min-w-0 flex-1 flex-row items-center justify-between"><ComposerAttachmentButton+ size={hasSidebarTabBar ? "large" : "regular"}disabled={isSubmissionLocked}supportsFiles={Boolean(props.serverConfig?.environment.capabilities.fileAttachments,@@ -1183,6 +1235,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps)}<View className="shrink-0 flex-row items-center"><ComposerDictationPrimaryAction+ size={hasSidebarTabBar ? "large" : "regular"}state={voiceInput.state}presentation={voicePresentation}isAvailable={voiceInput.isAvailable}diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsxindex ad6489b1b63..e8f99bf4e64 100644--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx@@ -1,3 +1,4 @@+import { useSidebarWorkspaceTabs } from "../workspace/useSystemWorkspaceTabBar";import {isAtomCommandInterrupted,settlePromise,@@ -106,6 +107,7 @@ import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceimport {useDuoBottomBarInset,useNativeColumnLayoutMetrics,+ useNativeLayoutMetrics,} from "../../native/native-layout-metrics";import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";import { collectProviderUsageLimits } from "@t3tools/shared/usageLimits";@@ -160,9 +162,6 @@ import {} from "./pendingUserInputLayout";import {COMPOSER_COLLAPSED_CHROME,- COMPOSER_EXPANDED_CHROME,- COMPOSER_LAYOUT_TRANSITION,- COMPOSER_TRANSITION_DURATION_MS,THREAD_COMPOSER_BOTTOM_GUTTER,ThreadComposer,} from "./ThreadComposer";@@ -176,6 +175,18 @@ import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow";import { useGlobalVoiceInput } from "../voice-input/VoiceInputProvider";export interface ThreadDetailScreenProps {+ readonly header?: React.ReactNode;+ readonly draftMode?: {+ readonly content: (+ headerInset: number,+ bottomInset: number,+ availableHeight: number,+ ) => React.ReactNode;+ readonly controls: React.ReactNode;+ readonly editorRef: React.RefObject<ComposerEditorHandle | null>;+ readonly sendBlockedReason: string | null;+ readonly interactionLocked: boolean;+ };readonly worktreeSetup?: WorktreeSetupCardProps | null;readonly setupWorkingStartedAt?: string | null;readonly canOperateThread: boolean;@@ -253,7 +264,7 @@ export interface ThreadDetailScreenProps {readonly canSwitchThreadProvider: boolean;readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;- readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;+ readonly onUpdateThreadInteractionMode?: (interactionMode: ProviderInteractionMode) => void;readonly onRespondToApproval: ApprovalResponder;readonly onSelectUserInputOption: (requestId: RuntimeRequestId,@@ -457,7 +468,8 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetaiconst browserTabs = useThreadServerBrowserTabs({environmentId: props.environmentId,threadId: props.selectedThread.id,- enabled: props.serverConfig?.environment.capabilities.serverBrowser === true,+ enabled:+ !props.draftMode && props.serverConfig?.environment.capabilities.serverBrowser === true,});const openBrowserPreview = (tabId?: string) => {Keyboard.dismiss();@@ -505,6 +517,7 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetaiconst navigationHeaderHeight = useContext(HeaderHeightContext) ?? insets.top + 44;const [screenMetrics, setScreenMetrics] = useState<NativeLayoutMetrics | null>(null);const columnMetrics = useNativeColumnLayoutMetrics();+ const windowMetrics = useNativeLayoutMetrics();const nativeMetrics = usesNativeWorkspaceColumns ? columnMetrics : screenMetrics;const controlInsets = deriveBottomControlInsets(nativeMetrics);const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;@@ -517,38 +530,43 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetaiconst queuedCount = useThreadQueuedCount(props.selectedThreadDetailRef);const turnSubagents = useThreadTurnSubagents(props.selectedThreadDetailRef);const agentsSegment = resolveSubagentPillSegment(turnSubagents);- const composerEditorRef = useRef<ComposerEditorHandle>(null);+ const defaultComposerEditorRef = useRef<ComposerEditorHandle>(null);+ const composerEditorRef = props.draftMode?.editorRef ?? defaultComposerEditorRef;const isProviderSubagent = isProviderNativeSubagentThread(props.selectedThread.source);const editingRunId = props.queuedRunEdit?.runId ?? null;useEffect(() => {if (editingRunId === null) return;const frame = requestAnimationFrame(() => composerEditorRef.current?.focus());return () => cancelAnimationFrame(frame);- }, [editingRunId]);+ }, [editingRunId, composerEditorRef]);const composerOverlayRef = useRef<ViewInstance>(null);const listRef = useRef<LegendListRef>(null);const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);const selectedThreadKeyRef = useRef(selectedThreadKey);const lastScrolledSubmittedMessageIdRef = useRef<MessageId | null>(null);- const [composerExpanded, setComposerExpanded] = useState(false);+ const [composerHeight, setComposerHeight] = useState<number | null>(null);const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);const [submittedMessageId, setSubmittedMessageId] = useState<MessageId | null>(null);const [endFollowEnabled, setEndFollowEnabled] = useState(true);- // Android Back hides the keyboard without blurring. Keep its safe-area padding- // fixed through the animation and cancel it with matching composer/list offsets.+ // Keep the bottom padding fixed while the keyboard animates. Changing it at+ // keyboardDidHide makes the composer land low, then jump back above the safe area.const bottomBarInset = useDuoBottomBarInset();+ const hasSidebarTabBar = useSidebarWorkspaceTabs() === "picker";+ // A pushed screen temporarily inherits the outgoing tab bar's safe area.+ // Use the window edge so hiding that bar cannot move the composer mid-push.+ const bottomSafeArea =+ Platform.OS === "ios" ? (windowMetrics?.safeArea.bottom ?? insets.bottom) : insets.bottom;// The pill already adds its own gutter; iPad and Duo align its edge with the native bar.const alignedBottomInset =bottomBarInset ??- (Platform.OS === "ios" && Platform.isPad ? Math.max(insets.bottom, 12) : undefined);- // A hardware keyboard can focus the editor without occupying any screen height.+ (Platform.OS === "ios" && Platform.isPad+ ? Math.max(bottomSafeArea, 12) - (hasSidebarTabBar ? 5 : 0)+ : undefined);const composerBottomInset =- Platform.OS === "ios" && (composerExpanded || liveKeyboardHeight > 0)- ? 0- : alignedBottomInset !== undefined- ? Math.max(0, alignedBottomInset - THREAD_COMPOSER_BOTTOM_GUTTER)- : Math.max(insets.bottom, 12);- const composerKeyboardOffset = Platform.OS === "android" ? composerBottomInset : 0;+ alignedBottomInset !== undefined+ ? Math.max(0, alignedBottomInset - THREAD_COMPOSER_BOTTOM_GUTTER)+ : Math.max(bottomSafeArea, 12);+ const composerKeyboardOffset = composerBottomInset;const contentPresentationKind = props.contentPresentation.kind;const realThreadSyncLabel = (() => {switch (props.threadSyncStatus) {@@ -664,7 +682,7 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetaienvironmentLabel: props.environmentLabel,onReconnect: props.onReconnectEnvironment,});- if (connectionStatus !== null) {+ if (connectionStatus !== null && !props.draftMode) {return connectionStatus;}if (props.activePendingApproval !== null || props.activePendingUserInput !== null) {@@ -789,8 +807,8 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai) ||(props.historyControls?.hasMoreHistory === true &&props.selectedThread.latestUserMessageAt !== null);- const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;- const composerOverlapHeight = composerChrome + composerBottomInset;+ const composerOverlapHeight =+ composerHeight ?? COMPOSER_COLLAPSED_CHROME + (hasSidebarTabBar ? 14 : 0) + composerBottomInset;const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =useState<RuntimeRequestId | null>(null);const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;@@ -873,7 +891,9 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetaicomposerOverlayRef,Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),-nativeInsetOvercount,- Platform.OS === "ios" ? COMPOSER_TRANSITION_DURATION_MS : 0,+ // The composer already reports its animated height on each layout.+ // Easing these samples again makes the feed trail behind it.+ 0,);// Android lays the screen out below its opaque header and reports a zero// header height, so the window height overstates the room by the header.@@ -1207,6 +1227,7 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetaihasStartedTurn: props.selectedThread.latestRun !== null,hasUserMessage,queuedMessageCount: props.selectedThreadQueueCount,+ deliveryDeferred: props.connectionStateLabel !== "connected",}),);composerEditorRef.current?.blur();@@ -1253,7 +1274,8 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai});};- const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;+ const showScrollToEndButton =+ !props.draftMode && contentPresentationKind === "ready" && !endFollowEnabled;const { themeAppearance } = useAppearancePreferences();const isDarkMode = themeAppearance === "dark";@@ -1293,9 +1315,19 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai<ThreadVisitWatermarkenvironmentId={props.environmentId}selectedThread={props.selectedThread}- showContent={showContent}+ showContent={showContent && !props.draftMode}/>- {showContent ? (+ {props.draftMode ? (+ props.draftMode.content(+ navigationHeaderHeight,+ liveKeyboardHeight + estimatedOverlayHeight + 24,+ screenAreaHeight -+ navigationHeaderHeight -+ liveKeyboardHeight -+ estimatedOverlayHeight -+ 24,+ )+ ) : showContent ? (<Viewstyle={{ flex: 1 }}onTouchStart={handleFeedTouchStart}@@ -1393,7 +1425,6 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetaicoordinate space. Its top and height can then animate togetherinstead of the auto-sized host jumping to Yoga's destination. */}<Animated.View- layout={COMPOSER_LAYOUT_TRANSITION}pointerEvents="box-none"style={[{@@ -1603,7 +1634,9 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai</View>) : (<>+ {props.draftMode?.controls}<ThreadComposer+ isDraft={Boolean(props.draftMode)}canOperateThread={props.canOperateThread}reportedModelSelection={reportedModelSelection}editorRef={composerEditorRef}@@ -1629,11 +1662,14 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai// the draft: queueing them against a thread id the server may// still reject would strand them in the outbox.sendBlockedReason={- props.creationState?.kind === "preparing" &&- !props.creationState.serverOwned- ? "Starting the task…"- : null+ props.draftMode+ ? props.draftMode.sendBlockedReason+ : props.creationState?.kind === "preparing" &&+ !props.creationState.serverOwned+ ? "Starting the task…"+ : null}+ interactionLocked={props.draftMode?.interactionLocked}draftKey={props.composerDraftKey ?? undefined}followUpBehavior={props.activePendingApprovals.length > 0 &&@@ -1667,7 +1703,7 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetaionUpdateModelSelection={props.onUpdateThreadModelSelection}onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}onUpdateInteractionMode={props.onUpdateThreadInteractionMode}- onExpandedChange={setComposerExpanded}+ onHeightChange={setComposerHeight}onEditorFocusChange={handleOwnedInputFocusChange}/></>diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsxindex c7cf8a61e30..e49f4caadf8 100644--- a/apps/mobile/src/features/threads/ThreadGitControls.tsx+++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx@@ -86,6 +86,7 @@ export type ThreadGitMenuProps = {readonly environmentId: EnvironmentId | string;readonly threadId: ThreadId | string;readonly currentBranch: string | null;+ readonly hasThread?: boolean;readonly gitStatus: VcsStatusResult | null;readonly gitOperationLabel: string | null;readonly onOpenFilesInspector?: () => void;@@ -190,6 +191,13 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {!input.featureBranch &&requiresDefaultBranchConfirmation(input.action, isDefaultRef)) {+ if (props.hasThread === false) {+ Dialog.alert(+ "Choose a feature branch",+ "Switch branches before publishing changes from this draft.",+ );+ return;+ }navigation.navigate("GitConfirm", {environmentId: String(environmentId),threadId: String(threadId),@@ -360,8 +368,11 @@ function useThreadGitHeaderActionItems(props: ThreadGitControlsProps): ThreadGittype: "action",},{- description: "Turn diffs and worktree changes",- disabled: !model.isRepo,+ description:+ props.hasThread === false+ ? "Available after the first message"+ : "Turn diffs and worktree changes",+ disabled: !model.isRepo || props.hasThread === false,icon: { name: "text.bubble", type: "sfSymbol" },label: "Review changes",onPress: model.openReview,@@ -379,7 +390,11 @@ function useThreadGitHeaderActionItems(props: ThreadGitControlsProps): ThreadGit]: []),{- description: "Commit, files, branches",+ description:+ props.hasThread === false+ ? "Available after the first message"+ : "Commit, files, branches",+ disabled: props.hasThread === false,icon: { name: "ellipsis", type: "sfSymbol" },label: "More",onPress: model.openGitInspector,@@ -540,15 +555,22 @@ function threadGitMenuDefinition(id: "git-review",title: "Review changes",icon: "text.bubble",- disabled: !model.isRepo,- subtitle: "Turn diffs and worktree changes",+ disabled: !model.isRepo || props.hasThread === false,+ subtitle:+ props.hasThread === false+ ? "Available after the first message"+ : "Turn diffs and worktree changes",onPress: model.openReview,},{id: "git-more",title: "More",icon: "ellipsis",- subtitle: "Commit, files, branches",+ disabled: props.hasThread === false,+ subtitle:+ props.hasThread === false+ ? "Available after the first message"+ : "Commit, files, branches",onPress: model.openGitInspector,},],diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsxindex 96e80c44a72..6697548d81d 100644--- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx+++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx@@ -1,3 +1,4 @@+import { useActiveNewTask } from "../../state/active-new-task";import { ThreadUndoNotice } from "../home/ThreadUndoNotice";import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";import { resolveScratchProjectScopeKey } from "@t3tools/client-runtime/state/project-grouping";@@ -11,7 +12,8 @@ import {threadSearchMatchKey,type EnvironmentThreadSearchMatch,} from "@t3tools/client-runtime/state/thread-search";-import { LegendList } from "@legendapp/list/react-native";+import { AnimatedLegendList } from "@legendapp/list/reanimated";+import { THREAD_SIDEBAR_ROW_LAYOUT } from "./threadListAnimations";import type { MenuAction } from "@react-native-menu/menu";import { useAtomValue } from "@effect/atom-react";import { useEffect, useMemo, useRef, useState } from "react";@@ -156,6 +158,7 @@ function ThreadNavigationSidebarPane(regenerateThreadTitle,} = useThreadListActions();const pendingTasks = usePendingNewTasks();+ const activeNewTask = useActiveNewTask();const queuedThreadKeys = useQueuedThreadKeys();const { confirmDeletePendingTask } = usePendingTaskListActions();const environments = Object.values(savedConnectionsById)@@ -527,6 +530,7 @@ function ThreadNavigationSidebarPane(// clock deliberately stays out: its per-row text lives on the items, so a// tick only re-renders rows whose displayed text actually moved.const listExtraData = {+ activeNewTask,selectedThreadKey: props.selectedThreadKey ?? "",projectByKey,projectTitleByProjectKey,@@ -573,6 +577,14 @@ function ThreadNavigationSidebarPane(return (<ThreadListV2PendingRowpendingTask={item.pendingTask}+ selected={+ activeNewTask?.pendingKey === item.pendingTask.key ||+ (item.pendingTask.kind === "pending" &&+ scopedThreadKey(+ item.pendingTask.environmentId,+ item.pendingTask.message.threadId,+ ) === props.selectedThreadKey)+ }project={projectByKey.get(pendingScopeKey) ?? null}projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}environmentLabel={@@ -625,7 +637,10 @@ function ThreadNavigationSidebarPane()}searchQuery={props.searchQuery}pane="sidebar"- selected={scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey}+ selected={+ !activeNewTask &&+ scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey+ }fullSwipeWidth={props.width - 20}onSelectThread={handleSelectThread}onOpenThreadPullRequests={handleOpenThreadPullRequests}@@ -771,7 +786,8 @@ function ThreadNavigationSidebarPane(<View className="flex-1"><SwipeableScrollGateProvider enabled={swipeEnabled}><GestureDetector gesture={sidebarScrollGesture}>- <LegendList+ <AnimatedLegendList+ itemLayoutAnimation={THREAD_SIDEBAR_ROW_LAYOUT}data={listItems}drawDistance={500}estimatedItemSize={64}@@ -839,7 +855,8 @@ function ThreadNavigationSidebarPane() : (<SwipeableScrollGateProvider enabled={swipeEnabled}><GestureDetector gesture={sidebarScrollGesture}>- <LegendList+ <AnimatedLegendList+ itemLayoutAnimation={THREAD_SIDEBAR_ROW_LAYOUT}data={listItems}drawDistance={500}estimatedItemSize={64}diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsxindex e134283ae54..eedfa6e1d82 100644--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx@@ -28,7 +28,7 @@ import {projectScriptTerminalInput,resolveProjectScripts,} from "@t3tools/shared/projectScripts";-import { Platform, ScrollView, View } from "react-native";+import { Platform, ScrollView } from "react-native";import { useSafeAreaInsets } from "react-native-safe-area-context";import { useConnectionsReady } from "../../state/workspace";import { useEnvironmentShellReadiness } from "../../state/shell";@@ -64,7 +64,10 @@ import {stagePendingTerminalLaunch,} from "../terminal/terminalLaunchContext";import { terminalDebugLog } from "../terminal/terminalDebugLog";-import { ThreadDetailScreen, type ThreadDetailScreenProps } from "./ThreadDetailScreen";+import type { ThreadDetailScreenProps } from "./ThreadDetailScreen";+import { ThreadScreenBinding, ThreadScreenFallback, ThreadScreenHost } from "./ThreadScreenHost";+import { draftRouteIdentity } from "./thread-route-state";+import { NewTaskDraftRouteScreen, type NewTaskDraftRouteParams } from "./NewTaskDraftRouteScreen";import { GitOverviewSheet } from "./git/GitOverviewSheet";import { useAtomCommand } from "../../state/use-atom-command";import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";@@ -110,19 +113,12 @@ function firstRouteParam(value: string | string[] | undefined): string | null {return first === undefined || first.trim().length === 0 ? null : first;}-function ThreadPane(props: { readonly children: ReactNode }) {- return (- <View className="flex-1 bg-screen android:overflow-hidden android:rounded-t-[28px] android:bg-thread-canvas">- {props.children}- </View>- );-}-function ThreadRouteFallbackLayout(props: { readonly children: ReactNode }) {const goBack = useWorkspaceBackNavigation("threads");const { layout } = useAdaptiveWorkspaceLayout();const { themeVariables } = useAppearancePreferences();- if (Platform.OS !== "android") return props.children;+ if (Platform.OS !== "android")+ return <ThreadScreenFallback>{props.children}</ThreadScreenFallback>;return (<>@@ -132,7 +128,7 @@ function ThreadRouteFallbackLayout(props: { readonly children: ReactNode }) {onBack={layout.usesSplitView ? undefined : goBack}hideBottomBorder/>- <ThreadPane>{props.children}</ThreadPane>+ <ThreadScreenFallback>{props.children}</ThreadScreenFallback></>);}@@ -150,8 +146,9 @@ function OpeningThreadLoadingScreen() {}type ThreadRouteScreenRouteProps = StaticScreenProps<{- readonly environmentId: string;- readonly threadId: string;+ readonly environmentId?: string;+ readonly threadId?: string;+ readonly draft?: NewTaskDraftRouteParams;readonly prompt?: string | string[];}>;@@ -188,11 +185,26 @@ function ThreadUnavailableScreen(props: {}export function ThreadRouteScreen(props: ThreadRouteScreenProps) {+ return (+ <ThreadScreenHost>+ {props.route.params?.draft ? (+ <NewTaskDraftRouteScreen+ key={draftRouteIdentity(props.route.params.draft)}+ route={{ ...props.route, params: props.route.params.draft }}+ />+ ) : (+ <LiveThreadRouteController {...props} />+ )}+ </ThreadScreenHost>+ );+}++function LiveThreadRouteController(props: ThreadRouteScreenProps) {useAndroidWorkspaceBack("threads");const connectionsReady = useConnectionsReady();const { connectionState } = useRemoteConnectionStatus();const { selectedThread } = useThreadSelection();- const params = props.route.params;+ const params = props.route.params ?? {};const environmentIdRaw = firstRouteParam(params.environmentId);const threadIdRaw = firstRouteParam(params.threadId);const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;@@ -349,7 +361,7 @@ function ThreadRouteContent(threadId: mergeBackTargetThreadId,});};- const params = props.route.params;+ const params = props.route.params ?? {};const environmentIdRaw = firstRouteParam(params.environmentId);const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;const threadId = firstRouteParam(params.threadId);@@ -517,7 +529,7 @@ function ThreadRouteContent(<GitOverviewSheetheaderInset={inspectorHeaderInset}presentation="inspector"- route={{ params: props.route.params }}+ route={{ params: { environmentId: environmentId!, threadId: threadId! } }}/>);const FilesInspector = () =>@@ -750,9 +762,8 @@ function ThreadRouteContent(}clearPendingThreadCreationOutcome(routeThreadIdentity);navigation.dispatch(- StackActions.replace("NewTaskSheet", {- screen: "NewTaskDraft",- params: {+ StackActions.replace("Thread", {+ draft: {draftId: restoredNewTaskDraftKey(creation.messageId),environmentId: String(creation.environmentId),projectId: String(creation.creation.projectId),@@ -886,8 +897,25 @@ function ThreadRouteContent(onOpenPullRequest={openPullRequest}/>- <ThreadPane>- <ThreadDetailScreen+ <>+ <ThreadScreenBinding+ header={+ <ThreadHeader+ title={selectedThread.title}+ subtitle={headerSubtitle}+ headerColor={headerColor}+ usesNativeHeaderGlass={usesNativeHeaderGlass}+ gitControls={threadGitControlProps}+ hasThreadCwd={selectedThreadCwd !== null}+ hasWorkspaceRoot={Boolean(selectedThreadProject?.workspaceRoot)}+ fileInspectorSupported={fileInspector.supported}+ inspectorMode={inspectorMode}+ onToggleInspector={handleToggleInspector}+ onOpenGitInspector={handleOpenGitInspector}+ onOpenFilesInspector={handleOpenFilesInspector}+ onReturnToThread={props.onReturnToThread}+ />+ }canOperateThread={canOperateThread}selectedThread={selectedThreadWithDraftSettings ?? selectedThread}selectedThreadDetailRef={selectedThreadDetailRef}@@ -954,7 +982,11 @@ function ThreadRouteContent(projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}threadCwd={selectedThreadCwd}selectedThreadQueueCount={composer.selectedThreadQueueCount}- queuedMessages={composer.selectedThreadQueuedMessages}+ queuedMessages={+ selectedThreadCreation && selectedThreadCreation.outcome?.kind !== "delivered"+ ? [selectedThreadCreation.message, ...composer.selectedThreadQueuedMessages]+ : composer.selectedThreadQueuedMessages+ }dispatchingMessageId={composer.dispatchingQueuedMessageId}layoutVariant={layout.variant}usesAutomaticContentInsets={usesNativeHeaderGlass}@@ -980,28 +1012,13 @@ function ThreadRouteContent(onSubmitUserInput={requests.onSubmitUserInput}onDismissUserInput={requests.onDismissUserInput}/>- </ThreadPane>+ </></>);return (<>{activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}- <ThreadHeader- title={selectedThread.title}- subtitle={headerSubtitle}- headerColor={headerColor}- usesNativeHeaderGlass={usesNativeHeaderGlass}- gitControls={threadGitControlProps}- hasThreadCwd={selectedThreadCwd !== null}- hasWorkspaceRoot={Boolean(selectedThreadProject?.workspaceRoot)}- fileInspectorSupported={fileInspector.supported}- inspectorMode={inspectorMode}- onToggleInspector={handleToggleInspector}- onOpenGitInspector={handleOpenGitInspector}- onOpenFilesInspector={handleOpenFilesInspector}- onReturnToThread={props.onReturnToThread}- />{renderThreadRouteBody()}</>diff --git a/apps/mobile/src/features/threads/ThreadScreenHost.tsx b/apps/mobile/src/features/threads/ThreadScreenHost.tsxnew file mode 100644index 00000000000..7e1126f8faa--- /dev/null+++ b/apps/mobile/src/features/threads/ThreadScreenHost.tsx@@ -0,0 +1,77 @@+import {+ createContext,+ useContext,+ useLayoutEffect,+ useState,+ useSyncExternalStore,+ type ReactNode,+} from "react";+import { View } from "react-native";+import { ThreadDetailScreen, type ThreadDetailScreenProps } from "./ThreadDetailScreen";++type ThreadScreenContent =+ | { readonly props: ThreadDetailScreenProps }+ | { readonly fallback: ReactNode };++function createThreadScreenStore() {+ let current: ThreadScreenContent | null = null;+ const listeners = new Set<() => void>();+ return {+ getSnapshot: () => current,+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ publish: (content: ThreadScreenContent) => {+ current = content;+ for (const listener of listeners) listener();+ },+ };+}+const ThreadScreenContext = createContext<ReturnType<typeof createThreadScreenStore> | null>(null);++function ThreadScreenOutlet() {+ const store = useContext(ThreadScreenContext)!;+ const content = useSyncExternalStore(store.subscribe, store.getSnapshot);+ if (content === null) return null;+ return "props" in content ? (+ <>+ {content.props.header}+ <ThreadDetailScreen {...content.props} />+ </>+ ) : (+ content.fallback+ );+}++// Controllers can change from draft to live without replacing the native screen,+// the keyboard host, or the editor. Publish before paint to avoid an intermediate frame.+export function ThreadScreenHost({ children }: { readonly children: ReactNode }) {+ const [store] = useState(createThreadScreenStore);+ return (+ <ThreadScreenContext.Provider value={store}>+ {children}+ <View className="flex-1 bg-screen android:overflow-hidden android:rounded-t-[28px] android:bg-thread-canvas">+ <ThreadScreenOutlet />+ </View>+ </ThreadScreenContext.Provider>+ );+}++export function ThreadScreenBinding(props: ThreadDetailScreenProps) {+ const store = useContext(ThreadScreenContext)!;+ useLayoutEffect(() => {+ store.publish({ props });+ });+ return null;+}++export function ThreadScreenFallback({ children }: { readonly children: ReactNode }) {+ const store = useContext(ThreadScreenContext)!;+ useLayoutEffect(() => {+ store.publish({ fallback: children });+ });+ return null;+}diff --git a/apps/mobile/src/features/threads/composerSendPresentation.test.ts b/apps/mobile/src/features/threads/composerSendPresentation.test.tsindex 85f45baee8e..458b0078102 100644--- a/apps/mobile/src/features/threads/composerSendPresentation.test.ts+++ b/apps/mobile/src/features/threads/composerSendPresentation.test.ts@@ -11,6 +11,13 @@ const idle = {} as const;describe("resolveComposerSendPresentation", () => {+ it("shows the outbox action when delivery is deferred", () => {+ const presentation = resolveComposerSendPresentation({ ...idle, deliveryDeferred: true });+ expect(presentation.label).toBe("Queue");+ expect(presentation.icon).toBe("tray.and.arrow.up");+ expect(resolveComposerSendPresentation(idle).icon).toBe("arrow.up");+ });+it("never promises steering the provider cannot do", () => {const presentation = resolveComposerSendPresentation({...idle,diff --git a/apps/mobile/src/features/threads/composerSendPresentation.ts b/apps/mobile/src/features/threads/composerSendPresentation.tsindex 4ac2afc72f8..cafe6b5ed29 100644--- a/apps/mobile/src/features/threads/composerSendPresentation.ts+++ b/apps/mobile/src/features/threads/composerSendPresentation.ts@@ -7,7 +7,12 @@ import type { FollowUpBehavior } from "../../lib/followUpBehavior";export interface ComposerSendPresentation {readonly label: string;- readonly icon: "arrow.up" | "checkmark" | "list.number" | "arrow.turn.left.up";+ readonly icon:+ | "arrow.up"+ | "tray.and.arrow.up"+ | "checkmark"+ | "list.number"+ | "arrow.turn.left.up";readonly action: ActiveTurnComposerAction | null;readonly alternate: ActiveTurnComposerAction | null;readonly offersFollowUpChoice: boolean;@@ -38,7 +43,7 @@ export function resolveComposerSendPresentation(input: {if (!input.running) {return {label: input.deliveryDeferred ? "Queue" : "Send",- icon: "arrow.up",+ icon: input.deliveryDeferred ? "tray.and.arrow.up" : "arrow.up",action: null,alternate: null,offersFollowUpChoice: false,diff --git a/apps/mobile/src/features/threads/draft-thread-shell.ts b/apps/mobile/src/features/threads/draft-thread-shell.tsnew file mode 100644index 00000000000..343fbe02b8c--- /dev/null+++ b/apps/mobile/src/features/threads/draft-thread-shell.ts@@ -0,0 +1,64 @@+import { presentThreadShell } from "@t3tools/client-runtime/state/shell";+import type {+ EnvironmentId,+ ThreadId,+ ProjectId,+ ModelSelection,+ RuntimeMode,+ ProviderInteractionMode,+} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";++export function draftThreadShell(input: {+ readonly environmentId: EnvironmentId;+ readonly threadId: ThreadId;+ readonly projectId: ProjectId;+ readonly modelSelection: ModelSelection;+ readonly runtimeMode: RuntimeMode;+ readonly interactionMode: ProviderInteractionMode;+ readonly branch: string | null;+ readonly worktreePath: string | null;+ readonly createdAt: string;+}) {+ const timestamp = DateTime.makeUnsafe(input.createdAt);+ return presentThreadShell(input.environmentId, {+ id: input.threadId,+ projectId: input.projectId,+ title: "New thread",+ providerInstanceId: input.modelSelection.instanceId,+ modelSelection: input.modelSelection,+ runtimeMode: input.runtimeMode,+ interactionMode: input.interactionMode,+ branch: input.branch,+ pullRequests: [],+ worktreePath: input.worktreePath,+ linkedPullRequest: null,+ branchPullRequest: null,+ lineage: { rootThreadId: input.threadId, parentThreadId: null, relationshipToParent: null },+ forkedFrom: null,+ createdBy: "user",+ creationSource: "mobile",+ activeProviderThreadId: null,+ latestRunId: null,+ activeRunId: null,+ status: "idle",+ pendingRuntimeRequest: null,+ latestVisibleMessage: null,+ latestUserMessageAt: timestamp,+ hasActionableProposedPlan: false,+ itemCount: 0,+ visibleItemCount: 0,+ createdAt: timestamp,+ updatedAt: timestamp,+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ unsettledAt: null,+ snoozedUntil: null,+ snoozedAt: null,+ pinnedAt: null,+ pinOrderKey: null,+ activeOrderKey: null,+ deletedAt: null,+ });+}diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsxindex 23618df9c8e..af20d81146a 100644--- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx+++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx@@ -1,8 +1,9 @@+import { ActiveNewTaskContext } from "../../state/active-new-task";import * as Dialog from "../../components/ui/Dialog";import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";import { useEnvironmentPresentation } from "../../state/presentation";import { environmentSession } from "../../state/session";-import React, { useEffect, useRef, useState } from "react";+import React, { useCallback, useEffect, useRef, useState } from "react";import type {EnvironmentId,@@ -165,6 +166,7 @@ export function branchBadgeLabel(input: {}type NewTaskFlowContextValue = {+ readonly activeNewTask: { readonly pendingKey: string | null } | null;readonly projectScopes: ReadonlyArray<HomeProjectScope>;readonly selectedEnvironmentId: EnvironmentId | null;readonly selectedProjectKey: string | null;@@ -255,7 +257,13 @@ type NewTaskFlowContextValue = {const NewTaskFlowContext = React.createContext<NewTaskFlowContextValue | null>(null);-export function NewTaskFlowProvider(props: React.PropsWithChildren) {+export function NewTaskFlowProvider(+ props: React.PropsWithChildren<{+ active?: boolean;+ routeDraftId?: string;+ routePendingTaskId?: string;+ }>,+) {const projects = useProjects();const threads = useThreadShells();const { savedConnectionsById } = useSavedRemoteConnections();@@ -294,7 +302,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {const editingPendingTaskRef = useRef<QueuedThreadMessage | null>(null);const editingRevisionRef = useRef(Promise.resolve(0));- const reset = () => {+ const reset = useCallback(() => {setSelectedEnvironmentId(null);setSelectedProjectKey(null);setActiveDraftKey(null);@@ -311,7 +319,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {}releaseEditingQueuedMessage(editing.messageId);}- };+ }, []);const projectsForEnvironment = pipe(projects,@@ -425,7 +433,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {? activeDraftKey: null;useEffect(() => {- if (activeDraftKey !== null || editingPendingTask !== null || selectedProject === null) {+ if (+ props.active === false ||+ activeDraftKey !== null ||+ editingPendingTask !== null ||+ selectedProject === null+ ) {return;}setActiveDraftKey(@@ -434,7 +447,23 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {projectId: selectedProject.id,}),);- }, [activeDraftKey, editingPendingTask, selectedProject]);+ }, [activeDraftKey, editingPendingTask, selectedProject, props.active]);+ const activePendingKey =+ props.active === false+ ? null+ : props.routePendingTaskId+ ? `pending-task:${props.routePendingTaskId}`+ : props.routeDraftId+ ? `draft-task:${props.routeDraftId}`+ : editingPendingTask+ ? `pending-task:${editingPendingTask.messageId}`+ : selectedProjectDraftKey+ ? `draft-task:${selectedProjectDraftKey}`+ : null;+ const activeNewTask = React.useMemo(+ () => (props.active === false ? null : { pendingKey: activePendingKey }),+ [props.active, activePendingKey],+ );const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);const prompt = selectedProjectDraft.text;const attachments = selectedProjectDraft.attachments;@@ -1143,6 +1172,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {);const value = {+ activeNewTask,projectScopes,selectedEnvironmentId,selectedProjectKey,@@ -1209,7 +1239,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {setExpandedProvider,} satisfies NewTaskFlowContextValue;- return <NewTaskFlowContext.Provider value={value}>{props.children}</NewTaskFlowContext.Provider>;+ return (+ <ActiveNewTaskContext value={activeNewTask}>+ <NewTaskFlowContext.Provider value={value}>{props.children}</NewTaskFlowContext.Provider>+ </ActiveNewTaskContext>+ );}export function useNewTaskFlow() {diff --git a/apps/mobile/src/features/threads/new-task-project-selection.test.ts b/apps/mobile/src/features/threads/new-task-project-selection.test.tsindex a5289259fe4..3d0c2658fe3 100644--- a/apps/mobile/src/features/threads/new-task-project-selection.test.ts+++ b/apps/mobile/src/features/threads/new-task-project-selection.test.ts@@ -4,6 +4,7 @@ import { describe, expect, it } from "vite-plus/test";import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";import type { HomeProjectScope } from "../home/homeThreadList";import {+ newTaskDestination,resolveDraftProjectSelection,resolveEnvironmentProjectMatch,} from "./new-task-project-selection";@@ -112,3 +113,28 @@ describe("resolveDraftProjectSelection", () => {});});});++describe("newTaskDestination", () => {+ it("opens the current thread's project directly in split view", () => {+ const projects = [makeProject("first"), makeProject("current", "other-environment")];+ expect(newTaskDestination(true, projects, projects[1], "request")).toEqual({+ draft: { requestId: "request", environmentId: "other-environment", projectId: "current" },+ });+ });+ it("uses an available project when split view has no current project", () => {+ expect(newTaskDestination(true, [makeProject("first")], undefined, "request")).toEqual({+ draft: { requestId: "request", environmentId: "environment", projectId: "first" },+ });+ });+ it("keeps the picker when there are no projects", () => {+ expect(newTaskDestination(true, [], undefined, "request")).toEqual({+ draft: { requestId: "request" },+ });+ });+ it("opens the same draft route in compact view", () => {+ const project = makeProject("current");+ expect(newTaskDestination(false, [project], project, "request")).toEqual({+ draft: { requestId: "request", environmentId: "environment", projectId: "current" },+ });+ });+});diff --git a/apps/mobile/src/features/threads/new-task-project-selection.ts b/apps/mobile/src/features/threads/new-task-project-selection.tsindex 0676621994d..59d35f0e02c 100644--- a/apps/mobile/src/features/threads/new-task-project-selection.ts+++ b/apps/mobile/src/features/threads/new-task-project-selection.ts@@ -105,3 +105,26 @@ export function resolveDraftProjectSelection(const onlyProject = getOnlySelectableProject(projectScopes);return onlyProject ? { kind: "select", project: onlyProject } : { kind: "pick" };}++export function newTaskDestination(+ _usesSplitView: boolean,+ projects: ReadonlyArray<EnvironmentProject>,+ currentProject: Pick<EnvironmentProject, "environmentId" | "id"> | undefined,+ requestId: string,+) {+ const project =+ projects.find(+ (candidate) =>+ candidate.environmentId === currentProject?.environmentId &&+ candidate.id === currentProject.id,+ ) ?? projects[0];+ return project+ ? {+ draft: {+ requestId,+ environmentId: String(project.environmentId),+ projectId: String(project.id),+ },+ }+ : { draft: { requestId } };+}diff --git a/apps/mobile/src/features/threads/pending-thread-feed.test.ts b/apps/mobile/src/features/threads/pending-thread-feed.test.tsindex 109439778c7..92c39ab1b82 100644--- a/apps/mobile/src/features/threads/pending-thread-feed.test.ts+++ b/apps/mobile/src/features/threads/pending-thread-feed.test.ts@@ -4,6 +4,7 @@ import {ComposerContextId,EnvironmentId,MessageId,+ ProjectId,ThreadId,} from "@t3tools/contracts";import type { QueuedThreadMessage } from "../../state/thread-outbox-model";@@ -20,6 +21,24 @@ const pending = (id: string): QueuedThreadMessage => ({});describe("pending timeline messages", () => {+ it("marks the synthetic creation prompt pending without duplicating it", () => {+ const queued = {+ ...pending("creation"),+ creation: {+ projectId: ProjectId.make("project"),+ workspaceMode: "local" as const,+ branch: "main",+ worktreePath: null,+ },+ };+ const prompt = appendPendingThreadMessages([], [], [queued])[0]!;+ const synthetic = { ...prompt, pendingMessage: undefined };+ const result = appendPendingThreadMessages([synthetic], [synthetic], [queued]);+ expect(result).toHaveLength(1);+ expect(result[0]?.pendingMessage).toEqual(queued);+ expect(result[0]?.acknowledged).toBe(false);+ });+it("retains context records while a message is waiting for delivery", () => {const record = {version: 1 as const,diff --git a/apps/mobile/src/features/threads/pending-thread-feed.ts b/apps/mobile/src/features/threads/pending-thread-feed.tsindex 80d2aa2f48d..6df93566286 100644--- a/apps/mobile/src/features/threads/pending-thread-feed.ts+++ b/apps/mobile/src/features/threads/pending-thread-feed.ts@@ -16,7 +16,12 @@ export function appendPendingThreadMessages(feed.flatMap((entry) => (entry.type === "message" ? [entry.message.id] : [])),);return [- ...presentedFeed,+ ...presentedFeed.map((entry): PendingThreadFeedEntry => {+ const pendingMessage = queuedMessages.find(+ (message) => message.creation !== undefined && message.messageId === entry.id,+ );+ return pendingMessage ? { ...entry, pendingMessage, acknowledged: false } : entry;+ }),...queuedMessages.filter((message) => !deliveredIds.has(message.messageId)).map((pendingMessage): PendingThreadFeedEntry => ({diff --git a/apps/mobile/src/features/threads/thread-feed-live-follow.test.ts b/apps/mobile/src/features/threads/thread-feed-live-follow.test.tsindex 93cddab7dc0..728b24419b9 100644--- a/apps/mobile/src/features/threads/thread-feed-live-follow.test.ts+++ b/apps/mobile/src/features/threads/thread-feed-live-follow.test.ts@@ -77,6 +77,19 @@ describe("tool-group append following", () => {});describe("resolveThreadFeedSubmissionAnchor", () => {+ it("keeps an offline first message at the end", () => {+ expect(+ resolveThreadFeedSubmissionAnchor({+ currentAnchorMessageId: null,+ submittedMessageId: "offline-first",+ hasStartedTurn: false,+ hasUserMessage: false,+ queuedMessageCount: 0,+ deliveryDeferred: true,+ }),+ ).toBeNull();+ });+it("anchors the first user message in a thread", () => {expect(resolveThreadFeedSubmissionAnchor({@@ -84,6 +97,7 @@ describe("resolveThreadFeedSubmissionAnchor", () => {submittedMessageId: "first-message",hasStartedTurn: false,hasUserMessage: false,+ deliveryDeferred: false,queuedMessageCount: 0,}),).toBe("first-message");@@ -96,6 +110,7 @@ describe("resolveThreadFeedSubmissionAnchor", () => {submittedMessageId: "second-message",hasStartedTurn: false,hasUserMessage: false,+ deliveryDeferred: false,queuedMessageCount: 1,}),).toBe("first-message");@@ -108,6 +123,7 @@ describe("resolveThreadFeedSubmissionAnchor", () => {submittedMessageId: "second-message",hasStartedTurn: false,hasUserMessage: true,+ deliveryDeferred: false,queuedMessageCount: 0,}),).toBeNull();@@ -121,6 +137,7 @@ describe("resolveThreadFeedSubmissionAnchor", () => {submittedMessageId: "second-message",hasStartedTurn: true,hasUserMessage: false,+ deliveryDeferred: false,queuedMessageCount: 0,}),).toBeNull();diff --git a/apps/mobile/src/features/threads/thread-feed-live-follow.ts b/apps/mobile/src/features/threads/thread-feed-live-follow.tsindex d0cfe299999..11865e648e2 100644--- a/apps/mobile/src/features/threads/thread-feed-live-follow.ts+++ b/apps/mobile/src/features/threads/thread-feed-live-follow.ts@@ -55,8 +55,9 @@ export function resolveThreadFeedSubmissionAnchor<AnchorId>(input: {readonly hasStartedTurn: boolean;readonly hasUserMessage: boolean;readonly queuedMessageCount: number;+ readonly deliveryDeferred: boolean;}): AnchorId | null {- if (input.hasStartedTurn || input.hasUserMessage) {+ if (input.deliveryDeferred || input.hasStartedTurn || input.hasUserMessage) {return null;}diff --git a/apps/mobile/src/features/threads/thread-header-appearance.ts b/apps/mobile/src/features/threads/thread-header-appearance.tsnew file mode 100644index 00000000000..9cbbf01c799--- /dev/null+++ b/apps/mobile/src/features/threads/thread-header-appearance.ts@@ -0,0 +1,21 @@+import { Platform } from "react-native";+import {+ nativeHeaderScrollEdgeEffects,+ type AppNativeStackNavigationOptions,+} from "../../native/StackHeader";++export function threadHeaderAppearance(+ usesNativeHeaderGlass: boolean,+): AppNativeStackNavigationOptions {+ return {+ headerShown: true,+ headerTransparent: usesNativeHeaderGlass,+ headerStyle: usesNativeHeaderGlass ? { backgroundColor: "transparent" } : undefined,+ headerShadowVisible: false,+ scrollEdgeEffects: usesNativeHeaderGlass+ ? nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version)+ : undefined,+ headerTitleStyle: usesNativeHeaderGlass ? { fontSize: 17, fontWeight: "800" } : undefined,+ contentStyle: undefined,+ };+}diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsxindex 4fb1275b895..32cf4b72994 100644--- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx+++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx@@ -146,8 +146,6 @@ const LEGACY_MENU_ACTIONS: MenuAction[] = [{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },];-const SIDEBAR_V2_ROW_RADIUS = 12;-function ThreadListV2Section(props: {readonly label: string;readonly pane?: "screen" | "sidebar";@@ -316,6 +314,7 @@ const DRAFT_TASK_MENU_ACTIONS: MenuAction[] = [export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props: {readonly pendingTask: PendingNewTask;+ readonly selected?: boolean;readonly project: EnvironmentProject | null;readonly projectTitle?: string;readonly environmentLabel: string | null;@@ -336,7 +335,7 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(propsconst dormant = useSwipeRowDormant(props.activationKey);const theme = useUniwindTheme();const sidebarPane = props.pane === "sidebar";- const rowAppearance = getThreadListV2RowAppearance(theme, sidebarPane, false);+ const rowAppearance = getThreadListV2RowAppearance(theme, sidebarPane, props.selected ?? false);const isDraft = pendingTask.kind === "draft";const deleteLabel = isDraft ? "Discard" : "Delete";const handleDelete = useCallback(@@ -497,19 +496,13 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props}accessibilityLabel={pendingTask.title}accessibilityRole="button"+ accessibilityState={{ selected: props.selected ?? false }}key={pendingTask.key}- className={sidebarPane ? "bg-drawer" : "bg-screen"}- interactionClassName={sidebarPane ? "bg-thread-hover" : "bg-row-hover"}+ className={rowAppearance.className}+ interactionClassName={rowAppearance.interactionClassName}+ interactionOpacity={rowAppearance.interactionOpacity}onPress={() => onSelectPendingTask(pendingTask)}- style={- sidebarPane- ? {- borderRadius: SIDEBAR_V2_ROW_RADIUS,- paddingHorizontal: 12,- paddingVertical: 10,- }- : undefined- }+ style={rowAppearance.cardStyle}>{sidebarPane ? (rowContentdiff --git a/apps/mobile/src/features/threads/thread-route-state.test.ts b/apps/mobile/src/features/threads/thread-route-state.test.tsnew file mode 100644index 00000000000..31b684bfaec--- /dev/null+++ b/apps/mobile/src/features/threads/thread-route-state.test.ts@@ -0,0 +1,116 @@+import * as NodeModule from "node:module";+import { describe, expect, it } from "vite-plus/test";+import {+ draftRouteIdentity,+ isDraftThreadRoute,+ submittedThreadParams,+} from "./thread-route-state";++const requireNavigation = NodeModule.createRequire(+ NodeModule.createRequire(import.meta.url).resolve("@react-navigation/native/package.json"),+);+const { StackRouter, CommonActions, StackActions } = requireNavigation(+ "@react-navigation/routers",+) as {+ StackRouter: typeof import("@react-navigation/native").StackRouter;+ CommonActions: typeof import("@react-navigation/native").CommonActions;+ StackActions: typeof import("@react-navigation/native").StackActions;+};++describe("draft thread handoff", () => {+ it("submits in the existing route and stops suppressing the live thread selection", () => {+ const router = StackRouter({});+ const options = { routeNames: ["Home", "Thread"], routeParamList: {}, routeGetIdList: {} };+ const initial = router.getInitialState(options);+ const draft = router.getStateForAction(+ initial,+ CommonActions.navigate("Thread", { draft: { projectId: "project" } }),+ options,+ )!;+ if (!draft || draft.stale !== false) throw new Error("Draft route was not initialized");+ expect(isDraftThreadRoute(draft.routes.at(-1))).toBe(true);+ const submitted = router.getStateForAction(+ draft,+ CommonActions.setParams(submittedThreadParams("environment", "thread")),+ options,+ )!;+ expect(submitted.routes.map((route) => route.key)).toEqual(+ draft.routes.map((route) => route.key),+ );+ expect(submitted.index).toBe(draft.index);+ expect(submitted.routes.at(-1)?.params).toEqual({+ draft: undefined,+ environmentId: "environment",+ threadId: "thread",+ });+ expect(isDraftThreadRoute(submitted.routes.at(-1))).toBe(false);+ });+});++describe("missing shared-content project recovery", () => {+ it("replaces the stale draft before selecting the replacement project", () => {+ const router = StackRouter({});+ const options = {+ routeNames: ["Home", "Thread", "NewTaskProject"],+ routeParamList: {},+ routeGetIdList: {},+ };+ const initial = router.getInitialState(options);+ const staleDraft = router.getStateForAction(+ initial,+ CommonActions.navigate("Thread", {+ draft: { environmentId: "environment", projectId: "deleted", incomingShareId: "share" },+ }),+ options,+ )!;+ if (staleDraft.stale !== false) throw new Error("Draft route was not initialized");+ const picker = router.getStateForAction(+ staleDraft,+ StackActions.replace("NewTaskProject", { incomingShareId: "share" }),+ options,+ )!;+ if (picker.stale !== false) throw new Error("Project picker was not initialized");+ expect(picker.routes.some(isDraftThreadRoute)).toBe(false);+ expect(picker.routes.at(-1)?.params).toEqual({ incomingShareId: "share" });+ const recovered = router.getStateForAction(+ picker,+ CommonActions.navigate("Thread", {+ draft: { environmentId: "environment", projectId: "replacement", incomingShareId: "share" },+ }),+ options,+ )!;+ expect(recovered.routes.filter(isDraftThreadRoute)).toHaveLength(1);+ expect(recovered.routes.at(-1)?.params).toEqual({+ draft: { environmentId: "environment", projectId: "replacement", incomingShareId: "share" },+ });+ });+});++describe("draft route identity", () => {+ it("changes when a reused Thread route selects another draft or starts a new one", () => {+ const draft = { environmentId: "env", projectId: "project", draftId: "a" };+ expect(draftRouteIdentity(draft)).not.toBe(draftRouteIdentity({ ...draft, draftId: "b" }));+ expect(draftRouteIdentity(draft)).not.toBe(+ draftRouteIdentity({ ...draft, draftId: undefined }),+ );+ expect(draftRouteIdentity(draft)).not.toBe(+ draftRouteIdentity({ ...draft, projectId: "other" }),+ );+ expect(draftRouteIdentity(draft)).not.toBe(+ draftRouteIdentity({ ...draft, incomingShareId: "share" }),+ );+ });++ it("normalizes link parameters without resetting for display metadata", () => {+ expect(+ draftRouteIdentity({ environmentId: ["env"], projectId: ["project"], title: "Old" }),+ ).toBe(draftRouteIdentity({ environmentId: "env", projectId: "project", title: "New" }));+ });+});++it("starts a fresh controller for repeated new-task requests in the same project", () => {+ const project = { environmentId: "env", projectId: "project" };+ expect(draftRouteIdentity({ ...project, requestId: "first" })).not.toBe(+ draftRouteIdentity({ ...project, requestId: "second" }),+ );+});diff --git a/apps/mobile/src/features/threads/thread-route-state.ts b/apps/mobile/src/features/threads/thread-route-state.tsnew file mode 100644index 00000000000..c9a6ab6a3dd--- /dev/null+++ b/apps/mobile/src/features/threads/thread-route-state.ts@@ -0,0 +1,43 @@+export type NewTaskDraftRouteParams = {+ readonly requestId?: string;+ readonly environmentId?: string | string[];+ readonly projectId?: string | string[];+ readonly branch?: string | null;+ readonly worktreePath?: string | null;+ readonly title?: string | string[];+ readonly cloning?: string | string[];+ readonly pendingTaskId?: string | string[];+ readonly draftId?: string | string[];+ readonly incomingShareId?: string | string[];+};++export function isDraftThreadRoute(+ route:+ | {+ readonly name: string;+ readonly params?: object;+ }+ | undefined,+) {+ return (+ route?.name === "Thread" && Boolean((route.params as { draft?: unknown } | undefined)?.draft)+ );+}++export function submittedThreadParams(environmentId: string, threadId: string) {+ return { draft: undefined, environmentId, threadId };+}++export function draftRouteIdentity(draft: NewTaskDraftRouteParams): string {+ const first = (value: string | string[] | undefined) => (Array.isArray(value) ? value[0] : value);+ return JSON.stringify([+ draft.requestId,+ first(draft.pendingTaskId),+ first(draft.draftId),+ first(draft.environmentId),+ first(draft.projectId),+ draft.branch ?? null,+ draft.worktreePath ?? null,+ first(draft.incomingShareId),+ ]);+}diff --git a/apps/mobile/src/features/threads/threadListAnimations.ts b/apps/mobile/src/features/threads/threadListAnimations.tsnew file mode 100644index 00000000000..b4e3a2691e1--- /dev/null+++ b/apps/mobile/src/features/threads/threadListAnimations.ts@@ -0,0 +1,5 @@+import { LinearTransition, ReduceMotion } from "react-native-reanimated";++export const THREAD_SIDEBAR_ROW_LAYOUT = LinearTransition.duration(180).reduceMotion(+ ReduceMotion.System,+);diff --git a/apps/mobile/src/features/threads/useThreadHeaderOptions.tsx b/apps/mobile/src/features/threads/useThreadHeaderOptions.tsxindex 2153918ab06..48bc7ad4e48 100644--- a/apps/mobile/src/features/threads/useThreadHeaderOptions.tsx+++ b/apps/mobile/src/features/threads/useThreadHeaderOptions.tsx@@ -1,5 +1,7 @@+import { useWorkspaceSidebarHeaderItem } from "../layout/useWorkspaceSidebarHeaderItem";import { StackActions, useNavigation } from "@react-navigation/native";import { useMemo } from "react";+import { threadHeaderAppearance } from "./thread-header-appearance";import { isDuoDevice } from "../../lib/device-type";import type { AppNativeStackNavigationOptions } from "../../native/StackHeader";import { useDeviceType } from "../../native/native-layout-metrics";@@ -21,12 +23,14 @@ export function useThreadHeaderOptions(props: {readonly usesNativeHeaderGlass: boolean;readonly gitControls: Parameters<typeof ThreadGitControls>[0];readonly onReturnToThread?: () => void;+ readonly draft?: boolean;}) {const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();const deviceType = useDeviceType();const usesDuoHeader = usesNativeWorkspaceColumns && isDuoDevice(deviceType);const navigation = useNavigation();- const { layout, panes, togglePrimarySidebar } = useAdaptiveWorkspaceLayout();+ const { layout, startNewTask } = useAdaptiveWorkspaceLayout();+ const sidebarHeaderItem = useWorkspaceSidebarHeaderItem();const threadCenterHeaderItems = useThreadGitCenterHeaderItems(props.gitControls);const compactRightHeaderItems = useThreadGitRightHeaderItems(props.gitControls);const splitLeftHeaderItems = useMemo<NativeHeaderItems>(@@ -50,41 +54,21 @@ export function useThreadHeaderOptions(props: {}),]: []),- withNativeGlassHeaderItem({- axisBehavior: usesNativeWorkspaceColumns ? "horizontalOnly" : undefined,- accessibilityLabel: panes.primarySidebarVisible- ? "Maximize content"- : "Show thread sidebar",- icon: {- name: panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left",- type: "sfSymbol" as const,- },- identifier: "thread-left-sidebar",- label: panes.primarySidebarVisible ? "Maximize content" : "Show thread sidebar",- onPress: togglePrimarySidebar,- type: "button" as const,- }),- ...(!usesDuoHeader+ sidebarHeaderItem,+ ...(!usesDuoHeader && !props.draft? [withNativeGlassHeaderItem({accessibilityLabel: "New task",icon: { name: "square.and.pencil", type: "sfSymbol" as const },identifier: "thread-left-new-task",label: "New task",- onPress: () => navigation.navigate("NewTaskSheet", { screen: "NewTask" }),+ onPress: startNewTask,type: "button" as const,}),]: []),],- [- panes.primarySidebarVisible,- props.onReturnToThread,- navigation,- togglePrimarySidebar,- usesDuoHeader,- usesNativeWorkspaceColumns,- ],+ [sidebarHeaderItem, props.onReturnToThread, props.draft, startNewTask, usesDuoHeader],);const canGoBack = navigation.canGoBack();const compactHomeHeaderItems = useMemo<NativeHeaderItems>(@@ -101,14 +85,8 @@ export function useThreadHeaderOptions(props: {);const options: AppNativeStackNavigationOptions = {- headerShown: true,+ ...threadHeaderAppearance(props.usesNativeHeaderGlass),headerTitle: props.title,- headerTitleStyle: props.usesNativeHeaderGlass- ? {- fontSize: 17,- fontWeight: "800",- }- : undefined,title: props.title,headerBackVisible: !layout.usesSplitView,unstable_headerLeftItems: layout.usesSplitViewdiff --git a/apps/mobile/src/features/voice-input/ComposerDictationControl.tsx b/apps/mobile/src/features/voice-input/ComposerDictationControl.tsxindex 3e7d852be75..c2fc3700441 100644--- a/apps/mobile/src/features/voice-input/ComposerDictationControl.tsx+++ b/apps/mobile/src/features/voice-input/ComposerDictationControl.tsx@@ -1,16 +1,8 @@import type { VoiceInputPhase, VoiceInputState } from "@t3tools/client-runtime/voice-input";import { memo, useCallback, useLayoutEffect, useState, type ReactNode } from "react";-import {- Linking,- Platform,- Pressable,- Text as SystemText,- View,- type LayoutChangeEvent,-} from "react-native";+import { Linking, Pressable, Text as SystemText, View, type LayoutChangeEvent } from "react-native";import Animated, {Easing,- LinearTransition,ReduceMotion,useAnimatedStyle,useReducedMotion,@@ -32,10 +24,6 @@ const DICTATION_TIMING = {easing: Easing.out(Easing.cubic),reduceMotion: ReduceMotion.System,} as const;-const DICTATION_LAYOUT =- Platform.OS === "android"- ? undefined- : LinearTransition.duration(DICTATION_TIMING.duration).reduceMotion(ReduceMotion.System);const TOOLBAR_FLIP_TIMING = {duration: 260,easing: Easing.inOut(Easing.cubic),@@ -122,7 +110,6 @@ export function ComposerDictationDraftContent(props: {importantForAccessibility={props.hidden ? "no-hide-descendants" : "auto"}collapsable={false}className={props.className}- layout={DICTATION_LAYOUT}pointerEvents={props.hidden ? "none" : "auto"}style={[animatedStyle, { backfaceVisibility: "hidden" }]}>@@ -268,6 +255,7 @@ export function DictationElapsedTime(props: {}function VoiceActionButton(props: {+ readonly size?: "regular" | "large";readonly accessibilityLabel: string;readonly disabled?: boolean;readonly icon: AppSymbolName;@@ -295,7 +283,11 @@ function VoiceActionButton(props: {<ViewclassName={cn("items-center justify-center",- variant === "primary" ? "size-[30px] rounded-full bg-subtle" : "size-[44px]",+ variant === "primary"+ ? props.size === "large"+ ? "size-[44px] rounded-full bg-subtle"+ : "size-[30px] rounded-full bg-subtle"+ : "size-[44px]",)}>{variant === "primary" ? (@@ -310,7 +302,7 @@ function VoiceActionButton(props: {) : (<SymbolViewname={props.icon}- size={variant === "primary" ? 16 : 20}+ size={props.size === "large" ? 24 : variant === "primary" ? 16 : 20}weight={variant === "primary" ? "semibold" : "regular"}tintColorClassName={variant === "primary" ? "accent-primary-foreground" : "accent-icon"@@ -395,12 +387,14 @@ export function ComposerDictationStatus(props: {}export function ComposerDictationCancelAction(props: {+ readonly size?: "regular" | "large";readonly presentation: VoiceComposerPresentation;readonly onCancel: () => void;}) {if (props.presentation.leadingAction !== "cancel") return null;return (<VoiceActionButton+ size={props.size}accessibilityLabel="Cancel dictation"icon="xmark"onPress={props.onCancel}@@ -409,6 +403,7 @@ export function ComposerDictationCancelAction(props: {}export function ComposerDictationPrimaryAction(props: {+ readonly size?: "regular" | "large";readonly state: VoiceInputState;readonly presentation: VoiceComposerPresentation;readonly isAvailable: boolean;@@ -420,6 +415,7 @@ export function ComposerDictationPrimaryAction(props: {if (props.presentation.trailingAction === "confirm") {return (<VoiceActionButton+ size={props.size}accessibilityLabel={props.presentation.confirmationEnabled? "Finish dictation"@@ -438,6 +434,7 @@ export function ComposerDictationPrimaryAction(props: {}export function ComposerDictationStartAction(props: {+ readonly size?: "regular" | "large";readonly state: VoiceInputState;readonly isAvailable: boolean;readonly disabled?: boolean;@@ -448,6 +445,7 @@ export function ComposerDictationStartAction(props: {const openSettings = props.state.phase === "error" && props.state.errorAction === "settings";return (<VoiceActionButton+ size={props.size}accessibilityLabel={openSettings ? "Open microphone settings" : "Start dictation"}disabled={props.disabled}icon="mic"diff --git a/apps/mobile/src/features/workspace/AndroidWorkspaceNavigation.android.tsx b/apps/mobile/src/features/workspace/AndroidWorkspaceNavigation.android.tsxindex 78ee563b430..b813e61a1bc 100644--- a/apps/mobile/src/features/workspace/AndroidWorkspaceNavigation.android.tsx+++ b/apps/mobile/src/features/workspace/AndroidWorkspaceNavigation.android.tsx@@ -55,6 +55,7 @@ function nativeColor(value: string) {}export function AndroidWorkspaceNavigation(props: {+ readonly onNewThread: () => void;readonly rail?: boolean;readonly onSelect?: () => void;/** The rail needs the whole workspace while it widens over the list. */@@ -117,7 +118,7 @@ export function AndroidWorkspaceNavigation(props: {}}onNewThread={() => {Keyboard.dismiss();- navigation.navigate("NewTaskSheet", { screen: "NewTask" });+ props.onNewThread();}}onOverlayChange={(event) => props.onOverlayChange?.(event.nativeEvent.overlay)}style={rail ? { flex: 1 } : { height: 80 * Math.max(1, scale) }}diff --git a/apps/mobile/src/features/workspace/AndroidWorkspaceNavigation.tsx b/apps/mobile/src/features/workspace/AndroidWorkspaceNavigation.tsxindex 7d3bbd80e2e..edfe67e06de 100644--- a/apps/mobile/src/features/workspace/AndroidWorkspaceNavigation.tsx+++ b/apps/mobile/src/features/workspace/AndroidWorkspaceNavigation.tsx@@ -1,4 +1,5 @@export function AndroidWorkspaceNavigation(_props: {+ readonly onNewThread: () => void;readonly rail?: boolean;readonly onSelect?: () => void;readonly onOverlayChange?: (overlay: boolean) => void;diff --git a/apps/mobile/src/features/workspace/AndroidWorkspaceSettings.tsx b/apps/mobile/src/features/workspace/AndroidWorkspaceSettings.tsxindex c246604a8d8..9e616e2b8c0 100644--- a/apps/mobile/src/features/workspace/AndroidWorkspaceSettings.tsx+++ b/apps/mobile/src/features/workspace/AndroidWorkspaceSettings.tsx@@ -6,7 +6,7 @@ import { AndroidWorkspaceNavigation } from "./AndroidWorkspaceNavigation";/** Settings keeps its existing stack inside the full workspace, above compact navigation. */export function AndroidWorkspaceSettings(props: { readonly children: ReactNode }) {- const { layout } = useAdaptiveWorkspaceLayout();+ const { layout, startNewTask } = useAdaptiveWorkspaceLayout();const insets = useSafeAreaInsets();if (Platform.OS !== "android") return props.children;return (@@ -14,7 +14,7 @@ export function AndroidWorkspaceSettings(props: { readonly children: ReactNode }<SafeAreaInsetsContext value={layout.usesSplitView ? insets : { ...insets, bottom: 0 }}><View className="flex-1">{props.children}</View></SafeAreaInsetsContext>- {layout.usesSplitView ? null : <AndroidWorkspaceNavigation />}+ {layout.usesSplitView ? null : <AndroidWorkspaceNavigation onNewThread={startNewTask} />}</View>);}diff --git a/apps/mobile/src/features/workspace/WorkspaceRootScreen.android.tsx b/apps/mobile/src/features/workspace/WorkspaceRootScreen.android.tsxindex bbc8c62f983..240396d0469 100644--- a/apps/mobile/src/features/workspace/WorkspaceRootScreen.android.tsx+++ b/apps/mobile/src/features/workspace/WorkspaceRootScreen.android.tsx@@ -19,7 +19,7 @@ import type { WorkspaceTab } from "./workspace-tabs-state";const TABS: readonly WorkspaceTab[] = ["threads", "pullRequests"];export function WorkspaceRootScreen() {- const { layout } = useAdaptiveWorkspaceLayout();+ const { layout, startNewTask } = useAdaptiveWorkspaceLayout();const workspace = useWorkspaceTabs()!;const insets = useSafeAreaInsets();const { fabClearance } = useAndroidControlSizing();@@ -80,7 +80,7 @@ export function WorkspaceRootScreen() {}/></SafeAreaInsetsContext>- <AndroidWorkspaceNavigation />+ <AndroidWorkspaceNavigation onNewThread={startNewTask} /></View></WorkspaceTabsContext>);diff --git a/apps/mobile/src/features/workspace/WorkspaceRootScreen.tsx b/apps/mobile/src/features/workspace/WorkspaceRootScreen.tsxindex 97a11068057..c28ef1397a8 100644--- a/apps/mobile/src/features/workspace/WorkspaceRootScreen.tsx+++ b/apps/mobile/src/features/workspace/WorkspaceRootScreen.tsx@@ -56,7 +56,7 @@ function WorkspaceRootTitle(props: {function WorkspaceRootContent() {const navigation = useNavigation();const { width: windowWidth } = useWindowDimensions();- const { layout } = useAdaptiveWorkspaceLayout();+ const { layout, startNewTask } = useAdaptiveWorkspaceLayout();const primaryColumn = use(NativePrimaryColumnContext);const columnMetrics = useNativeColumnLayoutMetrics();const nativeMetrics = useNativeLayoutMetrics();@@ -98,7 +98,9 @@ function WorkspaceRootContent() {: Platform.OS === "ios"? Math.max(insets.bottom, keyboardHeight) +(systemTabBar || sidebarTabs || tab.searchMode !== "resting"- ? 16+ ? sidebarPicker+ ? 80+ : 16: WORKSPACE_DOCK.height + WORKSPACE_DOCK.bottomGap + 16): keyboardHeight > 0 && tab.searchMode !== "resting"? keyboardHeight + 64@@ -146,14 +148,11 @@ function WorkspaceRootContent() {]}/>)}- {sidebarPicker ? <WorkspaceSidebarTabs /> : null}<SafeAreaInsetsContext value={sidebarPicker ? { ...insets, top: 0 } : insets}>{state.selectedTab === "threads" ? <HomeRouteScreen /> : <PullRequestsScreen />}</SafeAreaInsetsContext>- <WorkspaceToolbar- sidebar={sidebarNavigation}- onNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}- />+ {sidebarPicker ? <WorkspaceSidebarTabs /> : null}+ <WorkspaceToolbar sidebar={sidebarNavigation} onNewTask={startNewTask} /></View></WorkspaceTabsContext>);diff --git a/apps/mobile/src/features/workspace/WorkspaceSidebarTabs.ios.tsx b/apps/mobile/src/features/workspace/WorkspaceSidebarTabs.ios.tsxindex 1e77784b872..476f6a386bf 100644--- a/apps/mobile/src/features/workspace/WorkspaceSidebarTabs.ios.tsx+++ b/apps/mobile/src/features/workspace/WorkspaceSidebarTabs.ios.tsx@@ -1,23 +1,33 @@-import { View } from "react-native";-import { SegmentedControl } from "../../components/ui/SegmentedControl";+import { requireNativeView } from "expo";+import type { NativeSyntheticEvent, ViewProps } from "react-native";+import { useSafeAreaInsets } from "react-native-safe-area-context";+import { useControlTheme } from "../../components/ui/useControlTheme";import { useWorkspaceTabs } from "./WorkspaceTabsContext";-import type { WorkspaceTab } from "./workspace-tabs-state";import { useSelectWorkspaceTab } from "./useSelectWorkspaceTab";+const NativeSidebarTabBar = requireNativeView<+ ViewProps & {+ selectedIndex: number;+ selectedColor: string;+ appearance: string;+ onSelectionChange: (event: NativeSyntheticEvent<{ index: number }>) => void;+ }+>("T3NativeControls", "SidebarTabBar");+export function WorkspaceSidebarTabs() {const workspace = useWorkspaceTabs()!;const selectTab = useSelectWorkspaceTab();+ const insets = useSafeAreaInsets();+ const { colors, colorScheme } = useControlTheme();return (- <View className="px-4 pb-3 pt-2">- <SegmentedControl- role="tab"- options={[- { value: "threads", label: "Threads" },- { value: "pullRequests", label: "Pull requests" },- ]}- selected={workspace.state.selectedTab}- onSelect={(tab: WorkspaceTab) => selectTab(tab)}- />- </View>+ <NativeSidebarTabBar+ selectedIndex={workspace.state.selectedTab === "threads" ? 0 : 1}+ selectedColor={colors["--color-primary"]}+ appearance={colorScheme}+ onSelectionChange={({ nativeEvent }) =>+ selectTab(nativeEvent.index === 0 ? "threads" : "pullRequests")+ }+ style={{ position: "absolute", bottom: 0, left: 0, right: 0, height: 64 + insets.bottom }}+ />);}diff --git a/apps/mobile/src/features/workspace/WorkspaceToolbar.ios.tsx b/apps/mobile/src/features/workspace/WorkspaceToolbar.ios.tsxindex 683b63e8f99..b9cb4c59f30 100644--- a/apps/mobile/src/features/workspace/WorkspaceToolbar.ios.tsx+++ b/apps/mobile/src/features/workspace/WorkspaceToolbar.ios.tsx@@ -1,3 +1,4 @@+import { useActiveNewTask } from "../../state/active-new-task";import { Toolbar } from "../../components/ui/Toolbar";import { useFocusEffect, useNavigation } from "@react-navigation/native";import { use, useCallback, useEffect, useRef, type ReactNode } from "react";@@ -59,6 +60,7 @@ export function WorkspaceToolbar(props: {readonly sidebar?: boolean;}) {const workspace = useWorkspaceTabs()!;+ const activeNewTask = useActiveNewTask();const navigation = useNavigation();const deviceType = useDeviceType();const sidebarTabs = useSidebarWorkspaceTabs();@@ -68,7 +70,8 @@ export function WorkspaceToolbar(props: {const nativeToolbarCompose =Platform.OS === "ios" &&deviceType === "duo-folded" &&- workspace.state.selectedTab === "threads";+ workspace.state.selectedTab === "threads" &&+ activeNewTask === null;// The Duo searches from a field at the bottom of the list in every pose. UIKit has no such// placement once the vertical bar holds the toolbar, and re-placing its search controller on// each fold replaces the search field.diff --git a/apps/mobile/src/lib/adaptive-navigation.test.ts b/apps/mobile/src/lib/adaptive-navigation.test.tsindex 2e6d78cf35b..bf0c8396754 100644--- a/apps/mobile/src/lib/adaptive-navigation.test.ts+++ b/apps/mobile/src/lib/adaptive-navigation.test.ts@@ -6,6 +6,15 @@ import {} 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({@@ -82,3 +91,23 @@ describe("resolveThreadSelectionOverlayState", () => {},);});++it("replacing a draft underneath an overlay removes its draft identity", () => {+ const result = resolveThreadSelectionOverlayState({+ state: {+ key: "root",+ type: "stack",+ stale: false,+ routeNames: ["Thread", "SettingsSheet"],+ index: 1,+ routes: [+ { key: "draft", name: "Thread", params: { draft: { draftId: "old" } } },+ { key: "settings", name: "SettingsSheet" },+ ],+ },+ 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.tsindex aa5efdcdbf2..1d139c5f2ba 100644--- a/apps/mobile/src/lib/adaptive-navigation.ts+++ b/apps/mobile/src/lib/adaptive-navigation.ts@@ -5,7 +5,7 @@ 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);+ return BASE_THREAD_ROUTE_PATTERN.test(pathname) || /^\/new\/draft\/?$/.test(pathname);}/**@@ -15,12 +15,15 @@ export function isBaseThreadRoute(pathname: string): boolean {export function resolveThreadSelectionNavigationAction(input: {readonly usesSplitView: boolean;readonly pathname: string;+ readonly workspaceRouteName?: string;}): AdaptiveNavigationAction {if (!input.usesSplitView || input.pathname === "/") {return "push";}- return isBaseThreadRoute(input.pathname) ? "set-params" : "replace";+ return input.workspaceRouteName === "Thread" || isBaseThreadRoute(input.pathname)+ ? "set-params"+ : "replace";}export function resolveThreadSelectionOverlayState(input: {@@ -43,7 +46,7 @@ export function resolveThreadSelectionOverlayState(input: {routes: [...routes,input.action === "set-params" && workspaceRoute?.name === "Thread"- ? { ...workspaceRoute, params: { ...workspaceRoute.params, ...input.params } }+ ? { ...workspaceRoute, params: input.params }: { name: "Thread", params: input.params },],};diff --git a/apps/mobile/src/lib/android-workspace-navigation.ts b/apps/mobile/src/lib/android-workspace-navigation.tsindex 19f074a4bbb..138704a03e6 100644--- a/apps/mobile/src/lib/android-workspace-navigation.ts+++ b/apps/mobile/src/lib/android-workspace-navigation.ts@@ -82,12 +82,13 @@ export function parentThreadIsBelow(state: NavigationState,parent: ReactNavigation.RootParamList["Thread"],) {+ if (!parent?.environmentId || !parent.threadId) return false;const previous = state.routes[state.index - 1];const params = previous?.params as ReactNavigation.RootParamList["Thread"] | undefined;return (previous?.name === "Thread" &¶ms?.environmentId === parent.environmentId &&- params.threadId === parent.threadId+ params?.threadId === parent.threadId);}diff --git a/apps/mobile/src/lib/appLinking.test.ts b/apps/mobile/src/lib/appLinking.test.tsindex 62781ce5d4b..480f58e0daa 100644--- a/apps/mobile/src/lib/appLinking.test.ts+++ b/apps/mobile/src/lib/appLinking.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vite-plus/test";-import { shouldHandleAppLink } from "./appLinking";+import { shouldHandleAppLink, restoreDraftLinkState } from "./appLinking";describe("shouldHandleAppLink", () => {it.each(["t3code://", "t3code:///", "t3code-dev://", "t3code-preview://"])(@@ -25,3 +25,43 @@ describe("shouldHandleAppLink", () => {},);});++describe("draft deep links", () => {+ it("opens the old draft URL on the thread screen with its draft identity", () => {+ const draft = { projectId: "project-1", environmentId: "env-1", draftId: "draft-1" };+ expect(+ restoreDraftLinkState(+ { routes: [{ name: "Home" }, { name: "Thread", params: draft }] },+ "/new/draft?draftId=draft-1",+ ),+ ).toEqual({+ index: 1,+ routes: [{ name: "Home" }, { name: "Thread", params: { draft } }],+ });+ });++ it.each([+ ["environment", "NewTaskEnvironment"],+ ["branch", "NewTaskBranch"],+ ["files", "NewTaskFiles"],+ ["files/src/index.ts", "NewTaskFile"],+ ["attachments/attachment-1", "NewTaskAttachment"],+ ["settings", "NewTaskThreadSettings"],+ ])("restores a draft beneath its %s screen", (path, name) => {+ const params = { environmentId: "env-1", projectId: "project-1" };+ const target = { name, params };+ expect(+ restoreDraftLinkState({ routes: [{ name: "Home" }, target] }, `/new/draft/${path}`),+ ).toEqual({+ index: 2,+ routes: [{ name: "Home" }, { name: "Thread", params: { draft: params } }, target],+ });+ });++ it("leaves live-thread and project-selection links unchanged", () => {+ const state = { routes: [{ name: "Thread", params: { threadId: "thread-1" } }] };+ expect(restoreDraftLinkState(state, "/threads/env-1/thread-1")).toBe(state);+ expect(restoreDraftLinkState(state, "/new")).toBe(state);+ expect(restoreDraftLinkState(undefined, "/new/draft")).toBeUndefined();+ });+});diff --git a/apps/mobile/src/lib/appLinking.ts b/apps/mobile/src/lib/appLinking.tsindex f720fbd0ea4..08263bb94d2 100644--- a/apps/mobile/src/lib/appLinking.ts+++ b/apps/mobile/src/lib/appLinking.ts@@ -1,3 +1,5 @@+import type { NavigationState, PartialState } from "@react-navigation/native";+/*** The Expo dev client launches the app via* <scheme>://expo-development-client/?url=<packager> — that URL addresses@@ -11,3 +13,19 @@ export function shouldHandleAppLink(url: string): boolean {!/^t3code(-dev|-preview)?:\/*$/.test(url));}++/** Keep the published draft URLs while using the root thread screen. */+export function restoreDraftLinkState(+ state: PartialState<NavigationState> | undefined,+ path: string,+) {+ const pathname = path.split("?")[0]?.replace(/^\/+|\/+$/g, "");+ if (!state || !pathname || !/^new\/draft(?:\/|$)/.test(pathname)) return state;+ const target = state.routes.at(-1);+ if (!target) return state;+ const draft = target.params ?? {};+ const routes = state.routes.slice(0, -1);+ routes.push({ name: "Thread", params: { draft } });+ if (pathname !== "new/draft") routes.push(target);+ return { ...state, index: routes.length - 1, routes };+}diff --git a/apps/mobile/src/native/createV5StackNavigator.ios.tsx b/apps/mobile/src/native/createV5StackNavigator.ios.tsxindex 1c8cea90061..194a6e7f7e5 100644--- a/apps/mobile/src/native/createV5StackNavigator.ios.tsx+++ b/apps/mobile/src/native/createV5StackNavigator.ios.tsx@@ -260,8 +260,7 @@ export function V5StackView(props: V5StackViewProps) {const groups = partitionStackPresentations(props.state.routes, (route) => {const presentation = props.descriptors[route.key]?.options.presentation;return (- ["SettingsSheet", "NewTaskSheet"].includes(route.name) ||- (presentation !== undefined && presentation !== "card")+ route.name === "SettingsSheet" || (presentation !== undefined && presentation !== "card"));});const routes = groups.map((group) => group[0]!);diff --git a/apps/mobile/src/native/native-layout-metrics.tsx b/apps/mobile/src/native/native-layout-metrics.tsxindex 195e7a2cec0..a2e28dc9161 100644--- a/apps/mobile/src/native/native-layout-metrics.tsx+++ b/apps/mobile/src/native/native-layout-metrics.tsx@@ -45,6 +45,9 @@ export function useDeviceType() {*/export function useDuoBottomBarInset() {const deviceType = useDeviceType();- const inset = use(NativeColumnLayoutMetricsContext)?.bottomBarInset;- return isDuoDevice(deviceType) ? inset : undefined;+ const metrics = use(NativeColumnLayoutMetricsContext);+ // Sheets have no rail to align with and can report zero for the bar region.+ // Their controls must keep using the sheet's bottom safe area.+ const inset = metrics?.bottomBarInset;+ return isDuoDevice(deviceType) && inset !== undefined && inset > 0 ? inset : undefined;}diff --git a/apps/mobile/src/native/workspace-stack-projection.test.ts b/apps/mobile/src/native/workspace-stack-projection.test.tsindex 9ae5d9a4a79..2b562a68137 100644--- a/apps/mobile/src/native/workspace-stack-projection.test.ts+++ b/apps/mobile/src/native/workspace-stack-projection.test.ts@@ -42,7 +42,7 @@ function history(describe("workspace router projection", () => {it("keeps workspace flows beside Home and restores them after a modal closes", () => {- const draft = { key: "draft", name: "NewTaskSheet" };+ const draft = { key: "draft", name: "Thread", params: { draft: {} } };const modal = { key: "connect", name: "ConnectOnboarding" };const routes = [home, thread, draft, settings, legal];const isOverlay = (route: { name: string }) => route.name === "ConnectOnboarding";diff --git a/apps/mobile/src/state/active-new-task.ts b/apps/mobile/src/state/active-new-task.tsnew file mode 100644index 00000000000..c29e618ea55--- /dev/null+++ b/apps/mobile/src/state/active-new-task.ts@@ -0,0 +1,9 @@+import { createContext, use } from "react";++export const ActiveNewTaskContext = createContext<{ readonly pendingKey: string | null } | null>(+ null,+);++export function useActiveNewTask() {+ return use(ActiveNewTaskContext);+}diff --git a/apps/mobile/src/state/thread-task-permissions.test.ts b/apps/mobile/src/state/thread-task-permissions.test.tsindex 82ac4dfff5b..eac2e40e983 100644--- a/apps/mobile/src/state/thread-task-permissions.test.ts+++ b/apps/mobile/src/state/thread-task-permissions.test.ts@@ -60,6 +60,7 @@ const state = vi.hoisted(() => ({vi.mock("react", () => ({useCallback: <A>(callback: A) => callback,useEffect: () => {},+ useLayoutEffect: () => {},useRef: <A>(current: A) => ({ current }),useMemo: <A>(factory: () => A) => factory(),useState: <A>(initial: A | (() => A)) => [diff --git a/apps/mobile/src/state/use-composer-attachment-actions.ts b/apps/mobile/src/state/use-composer-attachment-actions.tsnew file mode 100644index 00000000000..52fb05754ba--- /dev/null+++ b/apps/mobile/src/state/use-composer-attachment-actions.ts@@ -0,0 +1,136 @@+import * as Dialog from "../components/ui/Dialog";+import { useLayoutEffect, useRef } from "react";+import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, type ServerConfig } from "@t3tools/contracts";+import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";+import { nextPastedTextFileName } from "@t3tools/client-runtime/text-paste";+import type { ComposerTextPaste } from "../components/ComposerEditor";+import {+ convertPastedImagesToAttachments,+ createPastedTextComposerAttachment,+ pickComposerFiles,+ pickComposerMedia,+ removePersistedComposerAttachmentFile,+ type DraftComposerAttachment,+} from "../lib/composerImages";+import {+ appendComposerDraftAttachments,+ captureComposerDraftInsertion,+ countComposerDraftAttachmentsAfterSelection,+ getComposerDraftSnapshot,+ type ComposerDraftInsertion,+} from "./use-composer-drafts";++export function useComposerAttachmentActions(props: {+ readonly draftKey: string | null;+ readonly serverConfig: ServerConfig | null | undefined;+ readonly locked?: boolean;+}) {+ const currentKey = useRef(props.draftKey);+ const reservedNames = useRef(new Map<string, Set<string>>());+ useLayoutEffect(() => {+ currentKey.current = props.draftKey;+ return () => {+ currentKey.current = null;+ };+ }, [props.draftKey]);+ const capabilities = props.serverConfig?.environment.capabilities;+ const append = async (+ key: string,+ attachments: ReadonlyArray<DraftComposerAttachment>,+ insertion: ComposerDraftInsertion,+ ) => {+ // A picker may finish after selecting another draft or sending this one.+ if (currentKey.current !== key) {+ await Promise.all(+ attachments.flatMap((item) =>+ item.fileUri ? [removePersistedComposerAttachmentFile(item.fileUri)] : [],+ ),+ );+ return 0;+ }+ return appendComposerDraftAttachments(key, attachments, { appendReference: true, insertion });+ };+ const report = (title: string, error: string | null | undefined, rejected: number) => {+ const problems = [+ ...(error ? [error] : []),+ ...(rejected+ ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`]+ : []),+ ];+ if (problems.length) Dialog.alert(title, problems.join("\n\n"));+ };+ const onPickDraftMedia = async () => {+ const key = props.draftKey;+ if (!key || props.locked) return;+ const insertion = captureComposerDraftInsertion(key);+ const result = await pickComposerMedia({+ existingCount: countComposerDraftAttachmentsAfterSelection(key, insertion),+ maxVideoBytes: capabilities?.attachmentUploads+ ? capabilities.fileAttachments?.maxUploadBytes+ : undefined,+ });+ report(+ "Could not attach photo or video",+ result.error,+ await append(key, result.attachments, insertion),+ );+ };+ const onPickDraftFiles = async () => {+ const key = props.draftKey;+ if (!key || props.locked) return;+ const maxBytes = capabilities?.fileAttachments?.maxUploadBytes;+ if (maxBytes === undefined) {+ Dialog.alert("Could not attach file", "This server does not support file attachments.");+ return;+ }+ const insertion = captureComposerDraftInsertion(key);+ const result = await pickComposerFiles({+ existingCount: countComposerDraftAttachmentsAfterSelection(key, insertion),+ maxBytes,+ });+ report("Could not attach file", result.error, await append(key, result.files, insertion));+ };+ const onNativePasteImages = async (uris: ReadonlyArray<string>) => {+ const key = props.draftKey;+ if (!key || props.locked || !uris.length) return;+ const insertion = captureComposerDraftInsertion(key);+ try {+ const images = await convertPastedImagesToAttachments({+ uris,+ existingCount: countComposerDraftAttachmentsAfterSelection(key, insertion),+ });+ report("Could not paste images", null, await append(key, images, insertion));+ } catch (error) {+ Dialog.alert("Could not paste images", error instanceof Error ? error.message : "Try again.");+ }+ };+ const onNativePasteText = async (paste: ComposerTextPaste) => {+ const key = props.draftKey;+ if (!key || props.locked) return;+ const maxBytes = capabilities?.attachmentUploads+ ? capabilities.fileAttachments?.maxUploadBytes+ : undefined;+ if (maxBytes === undefined) return;+ const names = reservedNames.current.get(key) ?? new Set<string>();+ reservedNames.current.set(key, names);+ for (const attachment of getComposerDraftSnapshot(key).attachments) names.add(attachment.name);+ const name = nextPastedTextFileName([...names]);+ names.add(name);+ try {+ const attachment = await createPastedTextComposerAttachment({+ text: paste.text,+ name,+ maxBytes: clampFileAttachmentUploadBytes(maxBytes),+ });+ const rejected = await append(key, [attachment], { text: paste.value, ...paste.selection });+ if (rejected) await removePersistedComposerAttachmentFile(attachment.fileUri);+ report("Could not attach pasted text", null, rejected);+ } catch (error) {+ Dialog.alert(+ "Could not attach pasted text",+ error instanceof Error ? error.message : "Try again.",+ );+ }+ };+ return { onPickDraftMedia, onPickDraftFiles, onNativePasteImages, onNativePasteText };+}diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.tsindex ebdf9769d46..afd952d43ab 100644--- a/apps/mobile/src/state/use-thread-composer-state.ts+++ b/apps/mobile/src/state/use-thread-composer-state.ts@@ -1,7 +1,7 @@+import { useComposerAttachmentActions } from "./use-composer-attachment-actions";import * as Dialog from "../components/ui/Dialog";import { AuthOrchestrationOperateScope } from "@t3tools/contracts";import { readEnvironmentScope } from "./session";-import type { ComposerTextPaste } from "../native/T3ComposerEditor.types";import { useAtomValue } from "@effect/atom-react";import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";@@ -27,7 +27,6 @@ import {type RuntimeMode,type ThreadId,} from "@t3tools/contracts";-import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";import { nextPastedTextFileName, pastedTextDisposition } from "@t3tools/client-runtime/text-paste";import {@@ -47,11 +46,8 @@ import {} from "../lib/modelOptions";import { resolveProviderInteractionMode } from "./legacy-plan-mode";import {- convertPastedImagesToAttachments,createPastedTextComposerAttachment,pasteComposerClipboard,- pickComposerFiles,- pickComposerMedia,removePersistedComposerAttachmentFile,} from "../lib/composerImages";import type { DraftComposerImageAttachment } from "../lib/composerImages";@@ -741,68 +737,11 @@ export function useThreadComposerState() {setComposerDraftText(threadKey, value);};- const onPickDraftMedia = async () => {- if (!selectedThreadShell) {- return;- }-- const threadKey = activeComposerDraftKey(selectedThreadShell);- const insertion = captureComposerDraftInsertion(threadKey);- const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;- const result = await pickComposerMedia({- existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),- maxVideoBytes:- capabilities?.attachmentUploads === true- ? capabilities.fileAttachments?.maxUploadBytes- : undefined,+ const { onPickDraftMedia, onPickDraftFiles, onNativePasteImages, onNativePasteText } =+ useComposerAttachmentActions({+ draftKey: selectedThreadShell ? activeComposerDraftKey(selectedThreadShell) : null,+ serverConfig: selectedEnvironmentRuntime?.serverConfig,});- const rejectedCount = appendComposerDraftAttachments(threadKey, result.attachments, {- appendReference: true,- insertion,- });- const problems = [- ...(result.error ? [result.error] : []),- ...(rejectedCount > 0- ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`]- : []),- ];- if (problems.length > 0) {- Dialog.alert("Could not attach photo or video", problems.join("\n\n"));- }- };-- const onPickDraftFiles = async () => {- if (!selectedThreadShell) {- return;- }- const maxBytes =- selectedEnvironmentRuntime?.serverConfig?.environment.capabilities.fileAttachments- ?.maxUploadBytes;- if (maxBytes === undefined) {- Dialog.alert("Could not attach file", "This server does not support file attachments.");- return;- }-- const threadKey = activeComposerDraftKey(selectedThreadShell);- const insertion = captureComposerDraftInsertion(threadKey);- const result = await pickComposerFiles({- existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),- maxBytes,- });- const rejectedCount = appendComposerDraftAttachments(threadKey, result.files, {- appendReference: true,- insertion,- });- const problems = [- ...(result.error ? [result.error] : []),- ...(rejectedCount > 0- ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`]- : []),- ];- if (problems.length > 0) {- Dialog.alert("Could not attach file", problems.join("\n\n"));- }- };const onPasteIntoDraft = async () => {if (!selectedThreadShell) {@@ -893,69 +832,6 @@ export function useThreadComposerState() {}};- const onNativePasteImages = async (uris: ReadonlyArray<string>) => {- if (!selectedThreadShell || uris.length === 0) {- return;- }-- const threadKey = activeComposerDraftKey(selectedThreadShell);- const insertion = captureComposerDraftInsertion(threadKey);- try {- const images = await convertPastedImagesToAttachments({- uris,- existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),- });- if (images.length > 0) {- appendComposerDraftAttachments(threadKey, images, { appendReference: true, insertion });- }- } catch (error) {- console.error("[native paste] error converting images", {- environmentId: selectedThreadShell.environmentId,- threadId: selectedThreadShell.id,- uriCount: uris.length,- ...safeErrorLogAttributes(error),- });- }- };-- const onNativePasteText = async (paste: ComposerTextPaste) => {- if (!selectedThreadShell) return;- const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;- const advertisedMax =- capabilities?.attachmentUploads === true- ? capabilities.fileAttachments?.maxUploadBytes- : undefined;- if (advertisedMax === undefined) return;-- const threadKey = activeComposerDraftKey(selectedThreadShell);- const insertion = { text: paste.value, ...paste.selection };- const currentAttachments = getComposerDraftSnapshot(threadKey).attachments;- try {- const attachment = await createPastedTextComposerAttachment({- text: paste.text,- name: reservePastedTextFileName(- threadKey,- currentAttachments.map((item) => item.name),- ),- maxBytes: clampFileAttachmentUploadBytes(advertisedMax),- });- const rejectedCount = appendComposerDraftAttachments(threadKey, [attachment], {- appendReference: true,- insertion,- });- if (rejectedCount > 0) {- await removePersistedComposerAttachmentFile(attachment.fileUri);- setPendingConnectionError(- `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,- );- }- } catch (error) {- setPendingConnectionError(- error instanceof Error ? error.message : "Could not attach pasted text.",- );- }- };-const onRemoveDraftImage = (imageId: string) => {if (!selectedThreadShell) {return;diff --git a/apps/mobile/src/state/use-thread-selection.ts b/apps/mobile/src/state/use-thread-selection.tsindex b4080c7f5e1..edd9b4e7774 100644--- a/apps/mobile/src/state/use-thread-selection.ts+++ b/apps/mobile/src/state/use-thread-selection.ts@@ -157,13 +157,11 @@ function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefinconst message = queued ?? outcome?.message ?? null;return message === null ? null : { message, outcome };})();- // Until the creation is delivered the server has no thread to subscribe- // to. Every detail reader must use this ref, not the route id: an earlier- // read gets a definitive not-found, which the thread state keeps as deleted.+ // The shell can arrive before creation is acknowledged. Wait for delivery+ // before subscribing: an early not-found is cached as a deleted thread.+ // Every detail reader must use this ref, not the route id.const selectedThreadDetailRef =- selectedThreadShell !== null ||- pendingCreation === null ||- pendingCreation.outcome?.kind === "delivered"+ pendingCreation === null || pendingCreation.outcome?.kind === "delivered"? selectedThreadRef: null;const [previousCreation, setPreviousCreation] = useState<PendingThreadCreation | null>(null);