@devries-cameron20 / t3code-1 / commits / 8d3b061121
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(mobile): unify draft and thread navigation and composer behavior (#23467)

Julius Marminge committed Oct 22, 2026 at 02:43 UTC 8d3b061121fe65669d5d43d011b48cd3027a4108
78 files changed +2533 -1829
apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
+12 -23
@@ -467,7 +467,8 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
467 public required init(appContext: AppContext? = nil) {
468 super.init(appContext: appContext)
469
470 - clipsToBounds = false
470 + clipsToBounds = true
471 + textView.clipsToBounds = true
472 textView.delegate = self
473 textView.textDropDelegate = self
474 textView.backgroundColor = .clear
@@ -1215,28 +1216,16 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
1216 }
1217
1218 private func emitContentSizeIfNeeded() {
1218 - // The laid-out text without insets. A one-line draft reports its natural width, so
1219 - // JS can tell whether it fits a narrower row than the one it is laid out in; past
1220 - // one line only the height matters, so layout stops at the second line. The width
1221 - // comes from the line fragment because usedRect spans the container once the view
1222 - // scrolls. A trailing newline's empty line only exists as the extra fragment.
1223 - let layout = textView.layoutManager
1224 - let container = textView.textContainer
1225 - var lines = 0
1226 - var width: CGFloat = 0
1227 - var height: CGFloat = 0
1228 - let glyphs = NSRange(location: 0, length: layout.numberOfGlyphs)
1229 - layout.enumerateLineFragments(forGlyphRange: glyphs) { _, used, _, _, stop in
1230 - lines += 1
1231 - width = used.width
1232 - height = used.maxY
1233 - if lines > 1 { stop.pointee = true }
1234 - }
1235 - if lines < 2, layout.extraLineFragmentTextContainer === container {
1236 - lines += 1
1237 - height = max(height, layout.extraLineFragmentUsedRect.maxY)
1238 - }
1239 - let nextSize = CGSize(width: lines == 1 ? ceil(width) : 0, height: ceil(height))
1219 + guard bounds.width > 0 else { return }
1220 + // Fit independently of the animated viewport: when scrolling is disabled,
1221 + // its current height can clip TextKit's laid-out line fragments.
1222 + let fittedHeight = textView.sizeThatFits(CGSize(width: bounds.width, height: .greatestFiniteMagnitude)).height
1223 + - textView.textContainerInset.top - textView.textContainerInset.bottom
1224 + let measuredHeight = min(lineHeight * 4, fittedHeight)
1225 + let width = fittedHeight <= lineHeight + 0.5
1226 + ? textView.layoutManager.usedRect(for: textView.textContainer).width
1227 + : 0
1228 + let nextSize = CGSize(width: ceil(width), height: ceil(measuredHeight))
1229 guard abs(nextSize.width - lastContentSize.width) > 0.5 ||
1230 abs(nextSize.height - lastContentSize.height) > 0.5 else {
1231 return
apps/mobile/modules/t3-native-controls/ios/Resources/Icons/pull-request.png
Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/pull-request.png differ
apps/mobile/modules/t3-native-controls/ios/Resources/Icons/pull-request@2x.png
Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/pull-request@2x.png differ
apps/mobile/modules/t3-native-controls/ios/Resources/Icons/pull-request@3x.png
Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/pull-request@3x.png differ
apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec
+1
@@ -15,5 +15,6 @@ Pod::Spec.new do |s|
15 s.pod_target_xcconfig = {
16 'DEFINES_MODULE' => 'YES',
17 }
18 + s.resource_bundles = { 'T3NativeControlIcons' => ['Resources/Icons/pull-request*.png'] }
19 s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}'
20 end
apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
+8
@@ -32,6 +32,14 @@ public final class T3NativeControlsModule: Module {
32 Prop("appearance") { (view: T3SegmentedControlView, value: String) in view.appearance = value }
33 }
34
35 + View(T3SidebarTabBarView.self) {
36 + ViewName("SidebarTabBar")
37 + Events("onSelectionChange")
38 + Prop("selectedIndex") { (view: T3SidebarTabBarView, value: Int) in view.selectedIndex = value }
39 + Prop("selectedColor") { (view: T3SidebarTabBarView, value: UIColor) in view.selectedColor = value }
40 + Prop("appearance") { (view: T3SidebarTabBarView, value: String) in view.appearance = value }
41 + }
42 +
43 View(T3LayoutMetricsView.self) {
44 ViewName("LayoutMetrics")
45 Events("onMetricsChange")
apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift new
+60
@@ -0,0 +1,60 @@
1 +import ExpoModulesCore
2 +import UIKit
3 +
4 +final class T3SidebarTabBarView: ExpoView, UITabBarDelegate {
5 + let onSelectionChange = EventDispatcher()
6 + private let tabBar = UITabBar()
7 + var selectedIndex = 0 { didSet { updateSelection() } }
8 + var selectedColor: UIColor = .systemBlue { didSet { tabBar.tintColor = selectedColor } }
9 + var appearance = "light" {
10 + didSet { overrideUserInterfaceStyle = appearance == "dark" ? .dark : .light }
11 + }
12 +
13 + required init(appContext: AppContext? = nil) {
14 + super.init(appContext: appContext)
15 + let iconBundle = Bundle(for: Self.self).url(forResource: "T3NativeControlIcons", withExtension: "bundle").flatMap(Bundle.init(url:))
16 + let pullRequestIcon = UIImage(named: "pull-request", in: iconBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate)
17 + tabBar.items = [
18 + UITabBarItem(title: "Threads", image: tabIcon(UIImage(systemName: "text.bubble")), tag: 0),
19 + UITabBarItem(title: "Pulls", image: tabIcon(pullRequestIcon), tag: 1),
20 + ]
21 + tabBar.items?.last?.accessibilityLabel = "Pull requests"
22 + tabBar.items?.first?.selectedImage = tabIcon(UIImage(systemName: "text.bubble.fill"))
23 + tabBar.itemPositioning = .fill
24 + tabBar.delegate = self
25 + addSubview(tabBar)
26 + updateSelection()
27 + }
28 +
29 + override func layoutSubviews() {
30 + super.layoutSubviews()
31 + tabBar.frame = bounds
32 + updateSelection()
33 + }
34 +
35 + override func didMoveToWindow() {
36 + super.didMoveToWindow()
37 + updateSelection()
38 + }
39 +
40 + // Give symbols and bitmap assets the same image box; UIKit otherwise scales symbols independently.
41 + private func tabIcon(_ image: UIImage?) -> UIImage? {
42 + guard let image else { return nil }
43 + let canvas = CGSize(width: 28, height: 28)
44 + let scale = min(24 / image.size.width, 24 / image.size.height)
45 + let size = CGSize(width: image.size.width * scale, height: image.size.height * scale)
46 + return UIGraphicsImageRenderer(size: canvas).image { _ in
47 + image.draw(in: CGRect(x: (canvas.width - size.width) / 2, y: (canvas.height - size.height) / 2, width: size.width, height: size.height))
48 + }.withRenderingMode(.alwaysTemplate)
49 + }
50 +
51 + private func updateSelection() {
52 + guard let items = tabBar.items, items.indices.contains(selectedIndex) else { return }
53 + guard tabBar.selectedItem !== items[selectedIndex] else { return }
54 + tabBar.selectedItem = items[selectedIndex]
55 + }
56 +
57 + func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
58 + onSelectionChange(["index": item.tag])
59 + }
60 +}
apps/mobile/src/App.tsx
+4 -2
@@ -6,7 +6,7 @@ import { StatusBar } from "react-native";
6 import { GestureHandlerRootView } from "react-native-gesture-handler";
7 import { KeyboardProvider } from "react-native-keyboard-controller";
8 import { SafeAreaProvider } from "react-native-safe-area-context";
9 -import { createStaticNavigation } from "@react-navigation/native";
9 +import { createStaticNavigation, getStateFromPath } from "@react-navigation/native";
10
11 import { RegistryContext } from "@effect/atom-react";
12 import { ThreadArrangementHost } from "./features/threads/ThreadArrangementSheet";
@@ -24,7 +24,7 @@ import { subscribeComposerDraftModelReconciliation } from "./state/use-composer-
24 import { environmentThreadShells } from "./state/threads";
25 import { environmentShell } from "./state/shell";
26 import { OverlayPortalHost } from "./components/ui/OverlayPortal";
27 -import { shouldHandleAppLink } from "./lib/appLinking";
27 +import { shouldHandleAppLink, restoreDraftLinkState } from "./lib/appLinking";
28 import { useMobileNavigationTheme } from "./lib/useMobileNavigationTheme";
29 import { useUiRuntimeMemoryWarningGc } from "./lib/useUiRuntimeMemoryWarningGc";
30 import { SubscriptionUsageCoordinator } from "./widgets/SubscriptionUsageCoordinator";
@@ -44,6 +44,8 @@ const appLinking = {
44 prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
45 config: { initialRouteName: "Home" },
46 filter: shouldHandleAppLink,
47 + getStateFromPath: (path: string, options: Parameters<typeof getStateFromPath>[1]) =>
48 + restoreDraftLinkState(getStateFromPath(path, options), path),
49 };
50
51 const Navigation = createStaticNavigation(RootStack);
apps/mobile/src/Stack.tsx
+126 -148
@@ -1,11 +1,9 @@
1 +import { isDraftThreadRoute } from "./features/threads/thread-route-state";
2 import { ComponentCatalogScreen } from "./features/development/ComponentCatalogScreen";
3 import { PullRequestGuideStopScreen } from "./features/pull-requests/guide/PullRequestGuideScreen";
4 import { PullRequestInlineCommentScreen } from "./features/pull-requests/PullRequestInlineCommentScreen";
5 import { PullRequestDiscussionScreen } from "./features/pull-requests/PullRequestDiscussionScreen";
5 -import {
6 - createV5StackNavigator as createNativeStackNavigator,
7 - createV5SheetStackNavigator,
8 -} from "./native/createV5StackNavigator";
6 +import { createV5SheetStackNavigator } from "./native/createV5StackNavigator";
7 import { createWorkspaceStackNavigator } from "./features/layout/createWorkspaceStackNavigator";
8 import {
9 createPathConfigForStaticNavigation,
@@ -19,14 +17,7 @@ import {
17 type NativeStackNavigationOptions,
18 } from "@react-navigation/native-stack";
19 import { useEffect, useRef, type ReactNode } from "react";
22 -import {
23 - Platform,
24 - Pressable,
25 - ScrollView,
26 - StyleSheet,
27 - View,
28 - useWindowDimensions,
29 -} from "react-native";
20 +import { Platform, Pressable, ScrollView, StyleSheet, useWindowDimensions } from "react-native";
21 import { useResolveClassNames } from "uniwind";
22
23 import { AppText as Text } from "./components/ui/AppText";
@@ -82,7 +73,6 @@ import { AddProjectLocalRoute } from "./features/projects/AddProjectLocalRoute";
73 import { AddProjectNewRoute } from "./features/projects/AddProjectNewRoute";
74 import { AddProjectRepositoryRoute } from "./features/projects/AddProjectRepositoryRoute";
75 import { AddProjectSourceRoute } from "./features/projects/AddProjectSourceRoute";
85 -import { NewTaskDraftRouteScreen } from "./features/threads/NewTaskDraftRouteScreen";
76 import {
77 NewTaskBranchPickerRouteScreen,
78 NewTaskEnvironmentPickerRouteScreen,
@@ -461,95 +451,6 @@ const SettingsSheetStack = createV5SheetStackNavigator({
451 // across two bars the whole screen slides).
452 const THREAD_LINKING_PREFIX = "threads/:environmentId/:threadId";
453
464 -const NewTaskSheetStack = createNativeStackNavigator({
465 - initialRouteName: "NewTask",
466 - screenOptions: {
467 - ...SHEET_GLASS_HEADER_OPTIONS,
468 - contentStyle: Platform.OS === "ios" ? { backgroundColor: "transparent" } : undefined,
469 - // UIKit's default push adds a dimming shadow and independently transitions
470 - // the navigation bar. Both read as mismatched sheet backgrounds here.
471 - animation: Platform.OS === "ios" ? "simple_push" : undefined,
472 - animationDuration: Platform.OS === "ios" ? 350 : undefined,
473 - },
474 - screens: {
475 - NewTask: createNativeStackScreen({
476 - screen: NewTaskRouteScreen,
477 - linking: "",
478 - options: {
479 - title: "Choose project",
480 - },
481 - }),
482 - NewTaskDraft: createNativeStackScreen({
483 - screen: NewTaskDraftRouteScreen,
484 - linking: "draft",
485 - options: {
486 - headerBackVisible: false,
487 - title: "",
488 - },
489 - }),
490 - NewTaskEnvironment: createNativeStackScreen({
491 - screen: NewTaskEnvironmentPickerRouteScreen,
492 - linking: "draft/environment",
493 - options: {
494 - title: "Environment",
495 - },
496 - }),
497 - NewTaskBranch: createNativeStackScreen({
498 - screen: NewTaskBranchPickerRouteScreen,
499 - linking: "draft/branch",
500 - options: {
501 - title: "Branch",
502 - },
503 - }),
504 - NewTaskFile: createNativeStackScreen({
505 - screen: ThreadFileScreen,
506 - linking: "draft/files/:path*",
507 - options: SOLID_HEADER_OPTIONS,
508 - }),
509 - NewTaskAttachment: createNativeStackScreen({
510 - screen: AttachmentFileScreen,
511 - linking: "draft/attachments/:attachmentId",
512 - options: SOLID_HEADER_OPTIONS,
513 - }),
514 - ThreadSettings: createNativeStackScreen({
515 - screen: NewTaskThreadSettingsRouteScreen,
516 - linking: "draft/settings",
517 - options: {
518 - gestureEnabled: true,
519 - headerShown: false,
520 - ...(Platform.OS === "android"
521 - ? { presentation: "card" as const }
522 - : {
523 - ...THREAD_SETTINGS_SHEET_OPTIONS,
524 - }),
525 - },
526 - }),
527 - AddProject: createNativeStackScreen({
528 - screen: AddProjectSourceRoute,
529 - linking: "add-project",
530 - options: {
531 - title: "Add Project",
532 - },
533 - }),
534 - AddProjectRepository: createNativeStackScreen({
535 - screen: AddProjectRepositoryRoute,
536 - linking: "add-project/repository",
537 - }),
538 - AddProjectDestination: createNativeStackScreen({
539 - screen: AddProjectDestinationRoute,
540 - linking: "add-project/destination",
541 - }),
542 - AddProjectLocal: createNativeStackScreen({
543 - screen: AddProjectLocalRoute,
544 - linking: "add-project/local",
545 - }),
546 - AddProjectNew: createNativeStackScreen({
547 - screen: AddProjectNewRoute,
548 - linking: "add-project/new",
549 - }),
550 - },
551 -});
552 -
454 const WORKSPACE_OVERLAY_ROUTES = new Set([
455 "PullRequestReview",
456 "PullRequestInlineComment",
@@ -560,7 +461,18 @@ const WORKSPACE_OVERLAY_ROUTES = new Set([
461 "GitCommit",
462 "GitConfirm",
463 "GitOverview",
563 - "NewTaskSheet",
464 + "NewTaskProject",
465 + "NewTaskFiles",
466 + "NewTaskFile",
467 + "NewTaskAttachment",
468 + "NewTaskThreadSettings",
469 + "AddProject",
470 + "AddProjectRepository",
471 + "AddProjectDestination",
472 + "AddProjectLocal",
473 + "AddProjectNew",
474 + "NewTaskEnvironment",
475 + "NewTaskBranch",
476 "SettingsLegal",
477 "SettingsSheet",
478 "ThreadAgents",
@@ -611,44 +523,58 @@ function RootStackLayout(props: {
523 const path = getPathFromState(props.state, navigationPathConfig);
524 const pathname = path.startsWith("/") ? path : `/${path}`;
525 const workspaceLocation = workspaceLocationFromState(props.state);
526 + const draftRoute = props.state.routes.findLast((route) => route.name === "Thread");
527 + const draftParams = (
528 + draftRoute?.params as
529 + | { draft?: { draftId?: string | string[]; pendingTaskId?: string | string[] } }
530 + | undefined
531 + )?.draft;
532 + const routeDraftId = Array.isArray(draftParams?.draftId)
533 + ? draftParams.draftId[0]
534 + : draftParams?.draftId;
535 + const routePendingTaskId = Array.isArray(draftParams?.pendingTaskId)
536 + ? draftParams.pendingTaskId[0]
537 + : draftParams?.pendingTaskId;
538 useAgentNotificationNavigation(workspaceLocation.pathname);
539 useConnectOnboardingNavigation();
540 useAppShortcuts(props.state);
541 useEffect(() => {
618 - const topRouteName = props.state.routes[props.state.index]?.name;
542 const transition = transitionIncomingSharePresentation(sharePresentationRef.current, {
620 - isShareSheetPresented: topRouteName === "NewTaskSheet",
543 + isShareSheetPresented: isDraftThreadRoute(props.state.routes[props.state.index]),
544 pendingShareId: pendingShare?.id ?? null,
545 });
546 sharePresentationRef.current = transition.state;
547 if (!transition.shareIdToPresent) {
548 return;
549 }
627 - navigation.navigate("NewTaskSheet", {
628 - screen: "NewTask",
629 - params: { incomingShareId: transition.shareIdToPresent },
630 - });
550 + navigation.navigate("Thread", { draft: { incomingShareId: transition.shareIdToPresent } });
551 }, [navigation, pendingShare, props.state]);
552
553 return (
634 - <HardwareKeyboardCommandProvider pathname={pathname}>
635 - <ThreadOutboxDrainWorker />
636 - <ShowcaseCaptureCoordinator pathname={pathname} />
637 - <ExistingThreadSettingsRouteProvider>
638 - <WorkspaceConnectionStatusProvider>
639 - <AndroidWorkspaceTabsProvider state={props.state}>
640 - <AdaptiveWorkspaceLayout
641 - pathname={workspaceLocation.pathname}
642 - workspaceRouteKey={workspaceLocation.routeKey}
643 - selectedPullRequestKey={selectedPullRequestKey(props.state)}
644 - >
645 - {props.children}
646 - <HardwareKeyboardCommandOverlay />
647 - </AdaptiveWorkspaceLayout>
648 - </AndroidWorkspaceTabsProvider>
649 - </WorkspaceConnectionStatusProvider>
650 - </ExistingThreadSettingsRouteProvider>
651 - </HardwareKeyboardCommandProvider>
554 + <NewTaskFlowProvider
555 + active={isDraftThreadRoute(draftRoute)}
556 + routeDraftId={routeDraftId}
557 + routePendingTaskId={routePendingTaskId}
558 + >
559 + <HardwareKeyboardCommandProvider pathname={pathname}>
560 + <ThreadOutboxDrainWorker />
561 + <ShowcaseCaptureCoordinator pathname={pathname} />
562 + <ExistingThreadSettingsRouteProvider>
563 + <WorkspaceConnectionStatusProvider>
564 + <AndroidWorkspaceTabsProvider state={props.state}>
565 + <AdaptiveWorkspaceLayout
566 + pathname={workspaceLocation.pathname}
567 + workspaceRouteKey={workspaceLocation.routeKey}
568 + selectedPullRequestKey={selectedPullRequestKey(props.state)}
569 + >
570 + {props.children}
571 + <HardwareKeyboardCommandOverlay />
572 + </AdaptiveWorkspaceLayout>
573 + </AndroidWorkspaceTabsProvider>
574 + </WorkspaceConnectionStatusProvider>
575 + </ExistingThreadSettingsRouteProvider>
576 + </HardwareKeyboardCommandProvider>
577 + </NewTaskFlowProvider>
578 );
579 }
580
@@ -780,9 +706,79 @@ const RootStackConfig = createWorkspaceStackNavigator({
706 }),
707 Thread: createNativeStackScreen({
708 screen: ThreadRouteScreen,
783 - linking: THREAD_LINKING_PREFIX,
709 + linking: { path: "threads/:environmentId?/:threadId?", alias: ["new/draft"] },
710 options: DETAIL_HEADER_OPTIONS,
711 }),
712 + NewTaskProject: createNativeStackScreen({
713 + screen: NewTaskRouteScreen,
714 + linking: { path: "new", alias: ["new/project"] },
715 + options: { ...GLASS_HEADER_OPTIONS, title: "Choose project" },
716 + }),
717 + NewTaskEnvironment: createNativeStackScreen({
718 + linking: "new/draft/environment",
719 + screen: NewTaskEnvironmentPickerRouteScreen,
720 + options: { ...GLASS_HEADER_OPTIONS, title: "Environment" },
721 + }),
722 + NewTaskBranch: createNativeStackScreen({
723 + linking: "new/draft/branch",
724 + screen: NewTaskBranchPickerRouteScreen,
725 + options: { ...GLASS_HEADER_OPTIONS, title: "Branch" },
726 + }),
727 + AddProject: createNativeStackScreen({
728 + linking: "new/add-project",
729 + screen: AddProjectSourceRoute,
730 +
731 + options: {
732 + ...GLASS_HEADER_OPTIONS,
733 + title: "Add project",
734 + },
735 + }),
736 + AddProjectRepository: createNativeStackScreen({
737 + linking: "new/add-project/repository",
738 + screen: AddProjectRepositoryRoute,
739 + options: GLASS_HEADER_OPTIONS,
740 + }),
741 + AddProjectDestination: createNativeStackScreen({
742 + linking: "new/add-project/destination",
743 + screen: AddProjectDestinationRoute,
744 + options: GLASS_HEADER_OPTIONS,
745 + }),
746 + AddProjectLocal: createNativeStackScreen({
747 + linking: "new/add-project/local",
748 + screen: AddProjectLocalRoute,
749 + options: GLASS_HEADER_OPTIONS,
750 + }),
751 + AddProjectNew: createNativeStackScreen({
752 + linking: "new/add-project/new",
753 + screen: AddProjectNewRoute,
754 + options: GLASS_HEADER_OPTIONS,
755 + }),
756 + NewTaskFiles: createNativeStackScreen({
757 + linking: "new/draft/files",
758 + screen: ThreadFilesTreeScreen,
759 + options: SOLID_HEADER_OPTIONS,
760 + }),
761 + NewTaskFile: createNativeStackScreen({
762 + linking: "new/draft/files/:path*",
763 + screen: ThreadFileScreen,
764 + options: SOLID_HEADER_OPTIONS,
765 + }),
766 + NewTaskAttachment: createNativeStackScreen({
767 + screen: AttachmentFileScreen,
768 + linking: "new/draft/attachments/:attachmentId",
769 + options: SOLID_HEADER_OPTIONS,
770 + }),
771 + NewTaskThreadSettings: createNativeStackScreen({
772 + screen: NewTaskThreadSettingsRouteScreen,
773 + linking: "new/draft/settings",
774 + options: {
775 + gestureEnabled: true,
776 + headerShown: false,
777 + ...(Platform.OS === "android"
778 + ? { presentation: "card" as const }
779 + : THREAD_SETTINGS_SHEET_OPTIONS),
780 + },
781 + }),
782 ThreadTerminal: createNativeStackScreen({
783 screen: ThreadTerminalRouteScreen,
784 linking: `${THREAD_LINKING_PREFIX}/terminal`,
@@ -1002,24 +998,6 @@ const RootStackConfig = createWorkspaceStackNavigator({
998 sheetGrabberVisible: true,
999 },
1000 }),
1005 - NewTaskSheet: createNativeStackScreen({
1006 - screen: NewTaskSheetStack,
1007 - linking: "new",
1008 - // A screen's layout replaces the navigator's screenLayout.
1009 - layout: ({ children, route }) => (
1010 - <GuardedScreenLayout route={route}>
1011 - <NewTaskFlowProvider>
1012 - <View className="flex-1 bg-sheet-solid">{children}</View>
1013 - </NewTaskFlowProvider>
1014 - </GuardedScreenLayout>
1015 - ),
1016 - options: {
1017 - ...NESTED_NAVIGATOR_OPTIONS,
1018 - sheetPrefersHorizontalBars: true,
1019 - gestureEnabled: true,
1020 - headerShown: false,
1021 - },
1022 - }),
1001 NotFound: createNativeStackScreen({
1002 screen: NotFoundScreen,
1003 linking: "*",
@@ -1073,14 +1051,14 @@ export const RootStack = RootStackConfig.with(function AdaptiveRootStack({ Navig
1051 },
1052 }}
1053 screenOptions={({ route }) => {
1076 - if (route.name !== "SettingsSheet" && route.name !== "NewTaskSheet") {
1054 + if (route.name !== "SettingsSheet") {
1055 return Platform.OS === "android"
1056 ? { animation: androidWorkspaceDestinationAnimation(route.name, usesSplitView) }
1057 : {};
1058 }
1059
1060 // Moving an open flow between a sheet and a split column remounts its nested
1083 - // navigator. Keep its presentation until dismissal so folding preserves the draft.
1061 + // navigator. Keep its presentation until dismissal so folding preserves the settings flow.
1062 let usesCard = flowPresentations.current.get(route.key);
1063 if (usesCard === undefined) {
1064 usesCard = usesWorkspaceFlowScreens;
apps/mobile/src/components/ComposerAttachmentStrip.tsx
+2
@@ -347,6 +347,8 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
347 onPressDocument={props.onPressDocument}
348 />
349 <Pressable
350 + accessibilityRole="button"
351 + accessibilityLabel={`Remove ${attachment.name}`}
352 className="absolute h-[22px] w-[22px] items-center justify-center rounded-[11px] bg-black/55"
353 style={{
354 top: removeButtonPlacement === "gutter" ? 0 : 4,
apps/mobile/src/components/ComposerModelControl.tsx
+11 -3
@@ -17,8 +17,8 @@ export function ComposerModelControl(props: {
17 readonly prompt: string;
18 readonly surfaceColor: string;
19 readonly disabled?: boolean;
20 + readonly size?: "regular" | "large";
21 readonly iconOnly?: boolean;
21 - readonly showSummary?: boolean;
22 readonly onPress: () => void;
23 }) {
24 const descriptors = resolveProviderOptionDescriptors({
@@ -48,6 +48,7 @@ export function ComposerModelControl(props: {
48 ]
49 .filter(Boolean)
50 .join(", ")}
51 + size={props.size}
52 disabled={props.disabled}
53 emphasized
54 renderIcon={(size) =>
@@ -72,8 +73,15 @@ export function ComposerModelControl(props: {
73 label={label}
74 iconOnly={props.iconOnly}
75 suffix={
75 - props.showSummary !== false && summary ? (
76 - <Text className="text-xs text-foreground-muted" numberOfLines={1}>
76 + summary ? (
77 + <Text
78 + className={
79 + props.size === "large"
80 + ? "text-sm text-foreground-muted"
81 + : "text-xs text-foreground-muted"
82 + }
83 + numberOfLines={1}
84 + >
85 {summary}
86 </Text>
87 ) : undefined
apps/mobile/src/components/ComposerToolbar.tsx
+14 -20
@@ -1,7 +1,6 @@
1 import type { ComponentProps, ReactNode } from "react";
2 import { useCallback, useMemo, useState } from "react";
3 import {
4 - Platform,
4 Pressable,
5 ScrollView,
6 View,
@@ -13,7 +12,7 @@ import {
12 type ViewStyle,
13 } from "react-native";
14
16 -import Animated, { FadeIn, LinearTransition } from "react-native-reanimated";
15 +import Animated, { FadeIn } from "react-native-reanimated";
16
17 import { cn } from "../lib/cn";
18 import { AppText as Text } from "./ui/AppText";
@@ -24,11 +23,8 @@ const COMPOSER_TOOLBAR_GAP = 8;
23 const COMPOSER_TOOLBAR_FADE_WIDTH = 18;
24 const COMPOSER_TOOLBAR_SCROLL_EPSILON = 4;
25 const INLINE_CONTROL_LABEL_ENTERING = FadeIn.duration(160);
27 -// Android runs no composer layout transitions, so the toolbar never trails the dock.
28 -const INLINE_CONTROL_WIDTH_TRANSITION =
29 - Platform.OS === "android" ? undefined : LinearTransition.duration(180);
30 -
26 export function ComposerInlineControl(props: {
27 + readonly size?: "regular" | "large";
28 readonly accessibilityHint?: string;
29 readonly accessibilityLabel?: string;
30 readonly disabled?: boolean;
@@ -47,13 +43,11 @@ export function ComposerInlineControl(props: {
43 readonly showChevron?: boolean;
44 }) {
45 const { scale, smallIconSize } = useAndroidControlSizing();
50 - // The label fades in as the control widens, and leaves at once: an exiting view keeps
51 - // drawing at its old place while the chevron moves into it. The clip keeps content laid out
52 - // at the final width inside the frame while it eases there.
46 + // Keep the picker anchored to its parent while the editor changes height.
47 const animatesLabel = props.iconOnly !== undefined;
48 + const iconSize = props.size === "large" ? 20 : smallIconSize;
49 return (
50 <Animated.View
56 - layout={animatesLabel ? INLINE_CONTROL_WIDTH_TRANSITION : undefined}
51 style={{
52 maxWidth: props.maxWidth ?? 190,
53 overflow: animatesLabel ? "hidden" : undefined,
@@ -66,7 +60,7 @@ export function ComposerInlineControl(props: {
60 accessibilityState={
61 props.static ? undefined : { disabled: props.disabled, selected: props.selected }
62 }
69 - className="h-11 flex-row items-center gap-2 rounded-xl px-2 active:bg-subtle"
63 + className="h-[44px] flex-row items-center gap-2 rounded-xl px-2 active:bg-subtle"
64 disabled={props.disabled || props.static}
65 onPress={props.onPress}
66 style={{ opacity: props.disabled ? 0.45 : 1 }}
@@ -74,16 +68,14 @@ export function ComposerInlineControl(props: {
68 {props.renderIcon ? (
69 <View
70 className="size-4 shrink-0 items-center justify-center"
77 - style={
78 - Platform.OS === "android" ? { width: 14 * scale, height: 14 * scale } : undefined
79 - }
71 + style={{ width: iconSize, height: iconSize }}
72 >
81 - {props.renderIcon(smallIconSize)}
73 + {props.renderIcon(iconSize)}
74 </View>
75 ) : props.icon ? (
76 <SymbolView
77 name={props.icon}
86 - size={smallIconSize}
78 + size={iconSize}
79 tintColorClassName={
80 props.emphasized || props.selected ? "accent-icon" : "accent-icon-muted"
81 }
@@ -97,7 +89,7 @@ export function ComposerInlineControl(props: {
89 >
90 <Text
91 className={cn(
100 - "text-sm font-t3-medium",
92 + props.size === "large" ? "text-base font-t3-medium" : "text-sm font-t3-medium",
93 props.emphasized || props.selected ? "text-foreground" : "text-foreground-muted",
94 )}
95 numberOfLines={1}
@@ -112,7 +104,7 @@ export function ComposerInlineControl(props: {
104 {props.showChevron === false ? null : (
105 <SymbolView
106 name={props.chevronDirection === "right" ? "chevron.right" : "chevron.down"}
115 - size={Math.round(10 * scale)}
107 + size={Math.round((props.size === "large" ? 12 : 10) * scale)}
108 tintColorClassName={
109 props.emphasized || props.selected ? "accent-icon" : "accent-icon-muted"
110 }
@@ -252,6 +244,7 @@ export function ComposerToolbarScroller(props: {
244 }
245
246 export function ComposerActionButton(props: {
247 + readonly size?: "regular" | "large";
248 readonly accessibilityLabel: string;
249 readonly disabled?: boolean;
250 readonly icon: ComponentProps<typeof SymbolView>["name"];
@@ -263,13 +256,14 @@ export function ComposerActionButton(props: {
256 readonly onTouchStart?: PressableProps["onTouchStart"];
257 }) {
258 const { scale, smallIconSize } = useAndroidControlSizing();
266 - const circleSize = Math.round(30 * scale);
259 + const circleSize = Math.round((props.size === "large" ? 44 : 30) * scale);
260 return (
261 <Pressable
262 accessibilityLabel={props.accessibilityLabel}
263 accessibilityRole="button"
264 accessibilityState={{ disabled: props.disabled }}
265 className="size-[44px] shrink-0 items-center justify-center active:opacity-70"
266 + style={props.size === "large" ? { width: 62 } : undefined}
267 disabled={props.disabled}
268 onPress={props.onPress}
269 onLongPress={props.onLongPress}
@@ -288,7 +282,7 @@ export function ComposerActionButton(props: {
282 >
283 <SymbolView
284 name={props.icon}
291 - size={smallIconSize}
285 + size={props.size === "large" ? Math.round(20 * scale) : smallIconSize}
286 weight="semibold"
287 tintColorClassName={
288 props.variant === "danger" ? "accent-danger-foreground" : "accent-primary-foreground"
apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx
+17 -10
@@ -337,7 +337,9 @@ function FileContent(props: {
337
338 type ThreadFilesRouteScreenProps = StaticScreenProps<{
339 readonly environmentId: string;
340 - readonly threadId: string;
340 + readonly threadId?: string;
341 + readonly cwd?: string;
342 + readonly projectName?: string;
343 }>;
344
345 type ThreadFileRouteScreenProps = StaticScreenProps<{
@@ -430,6 +432,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
432 const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
433 props.route.params,
434 );
435 + const hasFileInspector = fileInspector.supported && threadId !== null;
436 const revealedInspectorRef = useRef(false);
437 const fileAccessSession = useEnvironmentQuery(
438 environmentId !== null ? environmentSession.sessionStateAtom(environmentId) : null,
@@ -444,7 +447,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
447 const { canReadFiles } = fileAccess;
448 const entriesQuery = useFileTreeEntries({
449 environmentId,
447 - cwd: !canReadFiles || fileInspector.supported ? null : cwd,
450 + cwd: !canReadFiles || hasFileInspector ? null : cwd,
451 searchQuery,
452 });
453 const handleReturnToThread = () => {
@@ -463,16 +466,20 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
466 };
467
468 const handleSelectFile = (path: string) => {
466 - if (environmentId === null || threadId === null) {
469 + if (environmentId === null || cwd === null) {
470 return;
471 }
472 const params = {
473 environmentId: String(environmentId),
471 - threadId: String(threadId),
474 + ...(threadId === null ? { cwd, projectName } : { threadId: String(threadId) }),
475 path: path.split("/").filter((segment) => segment.length > 0),
476 };
477 + if (threadId === null) {
478 + navigation.navigate("NewTaskFile", params);
479 + return;
480 + }
481 const navigationAction = resolveFileSelectionNavigationAction({
475 - hasPersistentFileInspector: fileInspector.supported,
482 + hasPersistentFileInspector: hasFileInspector,
483 });
484 if (navigationAction === "replace") {
485 navigation.dispatch(StackActions.replace("ThreadFile", params));
@@ -503,14 +510,14 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
510 });
511 };
512 useEffect(() => {
506 - if (fileInspector.supported && cwd !== null && !revealedInspectorRef.current) {
513 + if (hasFileInspector && cwd !== null && !revealedInspectorRef.current) {
514 revealedInspectorRef.current = true;
515 showAuxiliaryPane("inspector");
516 }
510 - }, [cwd, fileInspector.supported, showAuxiliaryPane]);
517 + }, [cwd, hasFileInspector, showAuxiliaryPane]);
518
512 - if (selectedThread === null || environmentId === null || threadId === null) {
513 - if (fileInspector.supported) {
519 + if (environmentId === null || (threadId !== null && selectedThread === null)) {
520 + if (hasFileInspector) {
521 return (
522 <ThreadRouteScreen
523 onReturnToThread={handleReturnToThread}
@@ -534,7 +541,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
541 return <FilesUnavailable />;
542 }
543
537 - if (fileInspector.supported) {
544 + if (hasFileInspector) {
545 return (
546 <ThreadRouteScreen
547 onReturnToThread={handleReturnToThread}
apps/mobile/src/features/home/HomeRouteScreen.tsx
+16 -16
@@ -1,3 +1,4 @@
1 +import { uuidv4 } from "../../lib/uuid";
2 import { ThreadUndoNotice } from "./ThreadUndoNotice";
3 import { Toolbar } from "../../components/ui/Toolbar";
4 import { use } from "react";
@@ -27,7 +28,7 @@ import { HomeScreen } from "./HomeScreen";
28 import { HomeHeader } from "./HomeHeader";
29 import { useHomeListOptions } from "./home-list-options";
30 import { useAtomValueWhileVisible, useHomeRouteVisible } from "./home-route-visibility";
30 -import { useHomeThreadSelection } from "./home-thread-navigation";
31 +import { useHomeThreadRouteSelection, useHomeThreadSelection } from "./home-thread-navigation";
32 import { buildHomeProjectScopes } from "./homeThreadList";
33 import { usePendingTaskListActions } from "./usePendingTaskListActions";
34 import { useThreadListActions } from "./useThreadListActions";
@@ -40,7 +41,7 @@ export function HomeRouteScreen() {
41 const columnMetrics = useNativeColumnLayoutMetrics();
42 const deviceType = useDeviceType();
43 const headerWidth = nativePrimaryColumn ? (columnMetrics?.width ?? windowWidth) : windowWidth;
43 - const { layout, panes, primarySidebarSearchQuery, setPrimarySidebarSearchQuery } =
44 + const { layout, panes, primarySidebarSearchQuery, setPrimarySidebarSearchQuery, startNewTask } =
45 useAdaptiveWorkspaceLayout();
46 const projects = useProjects();
47 // Streaming turns rewrite thread shells many times a second. While a Thread
@@ -65,11 +66,12 @@ export function HomeRouteScreen() {
66 else setLocalSearchQuery(query);
67 };
68 const handleSelectThread = useHomeThreadSelection();
69 + const selectThreadRoute = useHomeThreadRouteSelection();
70 const handleNewThreadOnBranch = useCallback(
71 (thread: EnvironmentThreadShell) => {
70 - navigation.navigate("NewTaskSheet", {
71 - screen: "NewTaskDraft",
72 - params: {
72 + selectThreadRoute({
73 + draft: {
74 + requestId: uuidv4(),
75 environmentId: String(thread.environmentId),
76 projectId: String(thread.projectId),
77 branch: thread.branch,
@@ -77,7 +79,7 @@ export function HomeRouteScreen() {
79 },
80 });
81 },
80 - [navigation],
82 + [selectThreadRoute],
83 );
84
85 useEffect(() => {
@@ -177,7 +179,7 @@ export function HomeRouteScreen() {
179 <Toolbar.Button
180 accessibilityLabel="New task"
181 icon="square.and.pencil"
180 - onPress={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
182 + onPress={startNewTask}
183 />
184 </Toolbar>
185 ) : null}
@@ -193,9 +195,7 @@ export function HomeRouteScreen() {
195 : undefined
196 }
197 onStartNewTask={
196 - Platform.OS === "android" && panes.primarySidebarVisible
197 - ? undefined
198 - : () => navigation.navigate("NewTaskSheet", { screen: "NewTask" })
198 + Platform.OS === "android" && panes.primarySidebarVisible ? undefined : startNewTask
199 }
200 />
201 </>
@@ -205,7 +205,7 @@ export function HomeRouteScreen() {
205 return (
206 <AndroidHomeFabLayout
207 disabled={workspace !== null && Platform.OS !== "android"}
208 - onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
208 + onStartNewTask={startNewTask}
209 >
210 <>
211 {/* Restore the header after leaving split view; screen options are
@@ -248,7 +248,7 @@ export function HomeRouteScreen() {
248 })
249 }
250 onSearchQueryChange={setSearchQuery}
251 - onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
251 + onStartNewTask={startNewTask}
252 />
253
254 <HomeScreen
@@ -286,16 +286,16 @@ export function HomeRouteScreen() {
286 onDeletePendingTask={confirmDeletePendingTask}
287 onNewThreadOnBranch={handleNewThreadOnBranch}
288 onNewThreadInProject={(project) => {
289 - navigation.navigate("NewTaskSheet", {
290 - screen: "NewTaskDraft",
291 - params: {
289 + selectThreadRoute({
290 + draft: {
291 + requestId: uuidv4(),
292 environmentId: String(project.environmentId),
293 projectId: String(project.id),
294 title: project.title,
295 },
296 });
297 }}
298 - onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
298 + onStartNewTask={startNewTask}
299 pendingTasks={pendingTasks}
300 projectGroupingMode={listOptions.projectGroupingMode}
301 projects={projects}
apps/mobile/src/features/home/HomeScreen.tsx
+16 -3
@@ -1,8 +1,11 @@
1 +import { useActiveNewTask } from "../../state/active-new-task";
2 import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
3 import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";
4 import type { ThreadMoveDestination } from "../threads/threadOrder";
5 import { computeThreadMoveAvailability } from "../threads/threadOrder";
5 -import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
6 +import type { LegendListRef } from "@legendapp/list/react-native";
7 +import { AnimatedLegendList } from "@legendapp/list/reanimated";
8 +import { THREAD_SIDEBAR_ROW_LAYOUT } from "../threads/threadListAnimations";
9 import {
10 type EnvironmentProject,
11 type EnvironmentThreadShell,
@@ -262,7 +265,8 @@ export function HomeScreen(props: HomeScreenProps) {
265 Platform.OS === "android" ? "bg-header" : contentBackground,
266 );
267 const columnMetrics = useNativeColumnLayoutMetrics();
265 - const selectedThreadKey = primaryColumn?.selectedThreadKey ?? null;
268 + const activeNewTask = useActiveNewTask();
269 + const selectedThreadKey = activeNewTask ? null : (primaryColumn?.selectedThreadKey ?? null);
270 const fullSwipeWidth = primaryColumn && columnMetrics ? columnMetrics.width - 20 : undefined;
271 const queuedThreadKeys = useQueuedThreadKeys();
272 const openSwipeableRef = useRef<SwipeableMethods | null>(null);
@@ -579,7 +583,14 @@ export function HomeScreen(props: HomeScreenProps) {
583 );
584 return (
585 <ThreadListV2PendingRow
586 + pane={primaryColumn ? "sidebar" : "screen"}
587 pendingTask={item.pendingTask}
588 + selected={
589 + activeNewTask?.pendingKey === item.pendingTask.key ||
590 + (item.pendingTask.kind === "pending" &&
591 + scopedThreadKey(item.pendingTask.environmentId, item.pendingTask.message.threadId) ===
592 + selectedThreadKey)
593 + }
594 project={projectByKey.get(pendingScopeKey) ?? null}
595 projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}
596 environmentLabel={
@@ -707,6 +718,7 @@ export function HomeScreen(props: HomeScreenProps) {
718 // every HomeScreen render — and the minute clock must stay out of it for
719 // the same reason: the clock text is precomputed per item instead.
720 const v2ExtraData = {
721 + activeNewTask,
722 projectByKey,
723 projectTitleByProjectKey: v2ProjectTitleByProjectKey,
724 listEnvironments,
@@ -844,7 +856,8 @@ export function HomeScreen(props: HomeScreenProps) {
856 >
857 <SwipeableScrollGateProvider enabled={swipeEnabled} activation={swipeRowActivation}>
858 <GestureDetector gesture={homeScrollGesture}>
847 - <LegendList
859 + <AnimatedLegendList
860 + itemLayoutAnimation={primaryColumn ? THREAD_SIDEBAR_ROW_LAYOUT : undefined}
861 ref={listRef}
862 onLoad={() => activateVisibleRows(threadListV2Items)}
863 onTouchStart={(event) => trackListTouches(event, true)}
apps/mobile/src/features/home/home-thread-navigation.test.ts
+37 -1
@@ -26,7 +26,10 @@ vi.mock("@react-navigation/native", () => {
26 return { CommonActions, StackActions };
27 });
28
29 -import { createHomeThreadNavigationAction } from "./home-thread-navigation";
29 +import {
30 + createHomeThreadRouteAction,
31 + createHomeThreadNavigationAction,
32 +} from "./home-thread-navigation";
33
34 const { StackActions, StackRouter } = loadRouters();
35 const routeNames = ["Home", "Thread"];
@@ -196,3 +199,36 @@ describe("createHomeThreadNavigationAction", () => {
199 });
200 });
201 });
202 +
203 +describe("draft and live thread selection", () => {
204 + it("keeps the screen key and clears old identity when switching both ways", () => {
205 + const live = selectThread(initialState(), thread("thread-a"));
206 + const key = live.routes[live.index]!.key;
207 + const draft = apply(
208 + live,
209 + createHomeThreadRouteAction({
210 + state: live,
211 + dismissingRouteKey: null,
212 + params: { draft: { draftId: "new-task:draft-a" } },
213 + }),
214 + );
215 + expect(draft.routes[draft.index]).toMatchObject({
216 + key,
217 + params: {
218 + environmentId: undefined,
219 + threadId: undefined,
220 + draft: { draftId: "new-task:draft-a" },
221 + },
222 + });
223 + const restored = selectThread(draft, thread("thread-b"));
224 + expect(restored.routes[restored.index]).toMatchObject({
225 + key,
226 + params: {
227 + environmentId: "environment-1",
228 + threadId: "thread-b",
229 + draft: undefined,
230 + },
231 + });
232 + expect(restored.routes).toHaveLength(live.routes.length);
233 + });
234 +});
apps/mobile/src/features/home/home-thread-navigation.ts
+42 -16
@@ -12,27 +12,44 @@ import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSe
12
13 type ThreadSelection = Pick<EnvironmentThreadShell, "environmentId" | "id">;
14
15 -export function createHomeThreadNavigationAction(input: {
15 +export function createHomeThreadRouteAction(input: {
16 readonly state: Pick<NavigationState, "index" | "routes">;
17 readonly dismissingRouteKey: string | null;
18 - readonly thread: ThreadSelection;
18 + readonly params: ReactNavigation.RootParamList["Thread"];
19 }) {
20 const currentRoute = input.state.routes[input.state.index];
21 - const params = {
22 - environmentId: input.thread.environmentId,
23 - threadId: input.thread.id,
24 - };
25 -
26 - // Native swipe-back pops the outgoing route after its animation. Reusing
27 - // that key would also discard this selection when the dismissal arrives.
21 if (input.dismissingRouteKey !== null && currentRoute?.key === input.dismissingRouteKey) {
29 - return StackActions.push("Thread", params);
22 + return StackActions.push("Thread", input.params);
23 + }
24 + if (currentRoute?.name === "Thread") {
25 + return {
26 + ...CommonActions.setParams({
27 + environmentId: undefined,
28 + threadId: undefined,
29 + draft: undefined,
30 + ...input.params,
31 + }),
32 + source: currentRoute.key,
33 + };
34 }
35 + return CommonActions.navigate("Thread", input.params);
36 +}
37
32 - return CommonActions.navigate("Thread", params);
38 +export function createHomeThreadNavigationAction(input: {
39 + readonly state: Pick<NavigationState, "index" | "routes">;
40 + readonly dismissingRouteKey: string | null;
41 + readonly thread: ThreadSelection;
42 +}) {
43 + return createHomeThreadRouteAction({
44 + ...input,
45 + params: {
46 + environmentId: input.thread.environmentId,
47 + threadId: input.thread.id,
48 + },
49 + });
50 }
51
35 -export function useHomeThreadSelection() {
52 +export function useHomeThreadRouteSelection() {
53 const navigation =
54 useNavigation<NativeStackNavigationProp<ReactNavigation.RootParamList, "Home">>();
55 const dismissingRouteKey = useRef<string | null>(null);
@@ -60,22 +77,31 @@ export function useHomeThreadSelection() {
77 }, [navigation]);
78
79 return useCallback(
63 - (thread: ThreadSelection) => {
80 + (params: ReactNavigation.RootParamList["Thread"]) => {
81 if (Platform.OS === "android") {
82 selectAndroidWorkspace({
83 name: "Thread",
67 - params: { environmentId: String(thread.environmentId), threadId: String(thread.id) },
84 + params,
85 });
86 return;
87 }
88 navigation.dispatch((state) =>
72 - createHomeThreadNavigationAction({
89 + createHomeThreadRouteAction({
90 state,
91 dismissingRouteKey: dismissingRouteKey.current,
75 - thread,
92 + params,
93 }),
94 );
95 },
96 [navigation, selectAndroidWorkspace],
97 );
98 }
99 +
100 +export function useHomeThreadSelection() {
101 + const selectRoute = useHomeThreadRouteSelection();
102 + return useCallback(
103 + (thread: ThreadSelection) =>
104 + selectRoute({ environmentId: thread.environmentId, threadId: thread.id }),
105 + [selectRoute],
106 + );
107 +}
apps/mobile/src/features/home/usePendingTaskListActions.ts
+21 -14
@@ -1,5 +1,5 @@
1 import * as Dialog from "../../components/ui/Dialog";
2 -import { useNavigation } from "@react-navigation/native";
2 +import { useHomeThreadRouteSelection } from "./home-thread-navigation";
3 import { useCallback } from "react";
4
5 import { removeThreadOutboxMessage } from "../../state/thread-outbox-removal";
@@ -13,26 +13,33 @@ import {
13 } from "../../state/use-thread-outbox";
14 import { withThreadDismissal } from "./thread-dismissal";
15
16 -export function usePendingTaskListActions(): {
16 +export function usePendingTaskListActions(
17 + selectRoute?: (params: ReactNavigation.RootParamList["Thread"]) => void,
18 +): {
19 readonly openPendingTask: (pendingTask: PendingNewTask) => void;
20 readonly confirmDeletePendingTask: (pendingTask: PendingNewTask) => void;
21 } {
20 - const navigation = useNavigation();
22 + const selectHomeRoute = useHomeThreadRouteSelection();
23 + const selectThreadRoute = selectRoute ?? selectHomeRoute;
24
25 const openPendingTask = useCallback(
26 (pendingTask: PendingNewTask) => {
24 - navigation.navigate("NewTaskSheet", {
25 - screen: "NewTaskDraft",
26 - params: {
27 - environmentId: String(pendingTask.environmentId),
28 - projectId: String(pendingTask.projectId),
29 - ...(pendingTask.kind === "pending"
30 - ? { pendingTaskId: String(pendingTask.message.messageId) }
31 - : { draftId: pendingTask.draftKey }),
32 - },
33 - });
27 + selectThreadRoute(
28 + pendingTask.kind === "pending"
29 + ? {
30 + environmentId: String(pendingTask.environmentId),
31 + threadId: String(pendingTask.message.threadId),
32 + }
33 + : {
34 + draft: {
35 + environmentId: String(pendingTask.environmentId),
36 + projectId: String(pendingTask.projectId),
37 + draftId: pendingTask.draftKey,
38 + },
39 + },
40 + );
41 },
35 - [navigation],
42 + [selectThreadRoute],
43 );
44
45 const confirmDeletePendingTask = useCallback((pendingTask: PendingNewTask) => {
apps/mobile/src/features/keyboard/CommandPalette.tsx
+11 -9
@@ -1,3 +1,4 @@
1 +import { uuidv4 } from "../../lib/uuid";
2 import { useNavigation } from "@react-navigation/native";
3 import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
4 import { THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts";
@@ -142,7 +143,7 @@ export function CommandPalette(props: {
143 }) {
144 const navigation = useNavigation();
145 const { themeVariables } = useAppearancePreferences();
145 - const { selectThread } = useAdaptiveWorkspaceLayout();
146 + const { selectThread, selectThreadRoute } = useAdaptiveWorkspaceLayout();
147 const runCommand = props.onCommand;
148 const projects = useProjects();
149 const threads = useThreadShells();
@@ -190,14 +191,14 @@ export function CommandPalette(props: {
191 kind: "action",
192 title: "New thread in…",
193 searchTerms: ["new task", "chat", "create", "project"],
193 - run: () => navigation.navigate("NewTaskSheet", { screen: "NewTask" }),
194 + run: () => runCommand("newTask"),
195 },
196 {
197 key: "addProject",
198 kind: "action",
199 title: "Add project",
200 searchTerms: ["folder", "clone", "repository", "git"],
200 - run: () => navigation.navigate("NewTaskSheet", { screen: "AddProject" }),
201 + run: () => navigation.navigate("AddProject"),
202 },
203 {
204 key: "settings",
@@ -279,9 +280,9 @@ export function CommandPalette(props: {
280 title: `New thread in ${activeProject.title}`,
281 searchTerms: ["new task", "chat", "create"],
282 run: () =>
282 - navigation.navigate("NewTaskSheet", {
283 - screen: "NewTaskDraft",
284 - params: {
283 + selectThreadRoute({
284 + draft: {
285 + requestId: uuidv4(),
286 environmentId: activeProject.environmentId,
287 projectId: activeProject.id,
288 title: activeProject.title,
@@ -313,9 +314,9 @@ export function CommandPalette(props: {
314 detail: `New thread · ${savedConnectionsById[project.environmentId]?.environmentLabel ?? project.environmentId}`,
315 searchTerms: [project.workspaceRoot, "new thread", "project"],
316 run: () =>
316 - navigation.navigate("NewTaskSheet", {
317 - screen: "NewTaskDraft",
318 - params: {
317 + selectThreadRoute({
318 + draft: {
319 + requestId: uuidv4(),
320 environmentId: project.environmentId,
321 projectId: project.id,
322 title: project.title,
@@ -356,6 +357,7 @@ export function CommandPalette(props: {
357 runCommand,
358 savedConnectionsById,
359 selectThread,
360 + selectThreadRoute,
361 threads,
362 ]);
363 const results = useMemo(
apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx
+1 -1
@@ -148,7 +148,7 @@ export function HardwareKeyboardCommandProvider({
148 }
149
150 if (command === "newTask") {
151 - navigation.navigate("NewTaskSheet", { screen: "NewTask" });
151 + navigation.navigate("Thread", { draft: {} });
152 return;
153 }
154 if (command === "back") {
apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx
+110 -45
@@ -1,3 +1,5 @@
1 +import { createDeferredNavigation } from "./deferred-navigation";
2 +import { uuidv4 } from "../../lib/uuid";
3 import type {
4 EnvironmentProject,
5 EnvironmentThreadShell,
@@ -52,6 +54,9 @@ import {
54 } from "../../lib/adaptive-navigation";
55 import { scopedThreadKey } from "../../lib/scopedEntities";
56 import type { ThreadListFilters } from "../../persistence/mobile-preferences";
57 +import { appAtomRegistry } from "../../state/atom-registry";
58 +import { useProjects } from "../../state/entities";
59 +import { environmentThreadShells } from "../../state/threads";
60 import { mobilePreferencesAtom } from "../../state/preferences";
61 import {
62 DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS,
@@ -69,6 +74,7 @@ import {
74 import { AndroidWorkspaceSidebar } from "../workspace/AndroidWorkspaceSidebar";
75 import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSelection";
76 import { HomeListOptionsProvider } from "../home/home-list-options";
77 +import { newTaskDestination } from "../threads/new-task-project-selection";
78 import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
79 import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
80 import { useOpenThreadPullRequests } from "../threads/use-open-thread-pull-requests";
@@ -93,7 +99,10 @@ interface AdaptiveWorkspaceContextValue {
99 readonly panes: WorkspacePaneLayout;
100 readonly fileInspector: FileInspectorPaneLayout;
101 readonly primarySidebarSearchQuery: string;
102 + readonly startNewTask: () => void;
103 + readonly deferThreadSelectionUntil: (operation: Promise<unknown>) => void;
104 readonly selectThread: (thread: EnvironmentThreadShell) => void;
105 + readonly selectThreadRoute: (params: ReactNavigation.RootParamList["Thread"]) => void;
106 readonly activateAuxiliaryPaneRole: (role: WorkspaceAuxiliaryPaneRole) => () => void;
107 readonly registerWorkspaceInspector: (render: () => ReactNode) => () => void;
108 readonly setPrimarySidebarSearchQuery: (query: string) => void;
@@ -126,7 +135,10 @@ const AdaptiveWorkspaceContext = createContext<AdaptiveWorkspaceContextValue>({
135 panes: compactPanes,
136 fileInspector: compactFileInspector,
137 primarySidebarSearchQuery: "",
138 + startNewTask: () => undefined,
139 + deferThreadSelectionUntil: () => undefined,
140 selectThread: () => undefined,
141 + selectThreadRoute: () => undefined,
142 activateAuxiliaryPaneRole: () => () => undefined,
143 registerWorkspaceInspector: () => () => undefined,
144 setPrimarySidebarSearchQuery: () => undefined,
@@ -485,10 +497,94 @@ function AdaptiveWorkspaceLayoutContent(
497 });
498 };
499
500 + const selectAndroidWorkspace = useAndroidWorkspaceSelection();
501 + const deferredThreadSelection = useMemo(() => createDeferredNavigation(), []);
502 + function handleSelectThreadRoute(params: ReactNavigation.RootParamList["Thread"]) {
503 + deferredThreadSelection.run(() => applyThreadRouteSelection(params));
504 + }
505 + function applyThreadRouteSelection(params: ReactNavigation.RootParamList["Thread"]) {
506 + if (Platform.OS === "android") {
507 + setFileInspectorPreferredVisible(false);
508 + selectAndroidWorkspace({ name: "Thread", params });
509 + return;
510 + }
511 + const navigationAction = resolveThreadSelectionNavigationAction({
512 + usesSplitView: layout.usesSplitView,
513 + pathname,
514 + workspaceRouteName: navigation
515 + .getState()
516 + ?.routes.find((route) => route.key === props.workspaceRouteKey)?.name,
517 + });
518 + const overlayState = resolveThreadSelectionOverlayState({
519 + state: navigation.getState(),
520 + workspaceRouteKey: props.workspaceRouteKey,
521 + action: navigationAction,
522 + params,
523 + });
524 + if (overlayState !== null) {
525 + setFileInspectorPreferredVisible(false);
526 + navigation.dispatch(CommonActions.reset(overlayState));
527 + return;
528 + }
529 + if (navigationAction === "set-params") {
530 + setFileInspectorPreferredVisible(false);
531 + const state = navigation.getState();
532 + const route = state?.routes.find((candidate) => candidate.key === props.workspaceRouteKey);
533 + if (route?.name === "Thread") {
534 + navigation.dispatch({
535 + ...CommonActions.setParams({
536 + environmentId: undefined,
537 + threadId: undefined,
538 + draft: undefined,
539 + ...params,
540 + }),
541 + source: route.key,
542 + });
543 + } else {
544 + navigation.navigate("Thread", params);
545 + }
546 + return;
547 + }
548 + if (navigationAction === "replace") {
549 + setFileInspectorPreferredVisible(false);
550 + navigation.dispatch(StackActions.replace("Thread", params));
551 + return;
552 + }
553 + navigation.navigate("Thread", params);
554 + }
555 +
556 + const projects = useProjects();
557 const handleStartNewTask = () => {
489 - navigation.navigate("NewTaskSheet", { screen: "NewTask" });
558 + const thread = appAtomRegistry
559 + .get(environmentThreadShells.navigationThreadShellsAtom)
560 + .find((candidate) => candidate.environmentId === environmentId && candidate.id === threadId);
561 + const currentRoute = navigation
562 + .getState()
563 + ?.routes.find((route) => route.key === props.workspaceRouteKey);
564 + const draft =
565 + currentRoute?.name === "Thread"
566 + ? (currentRoute.params as ReactNavigation.RootParamList["Thread"])?.draft
567 + : undefined;
568 + const first = (value: string | string[] | undefined) =>
569 + Array.isArray(value) ? value[0] : value;
570 + const draftEnvironmentId = first(draft?.environmentId);
571 + const draftProjectId = first(draft?.projectId);
572 + const currentProject = thread
573 + ? { environmentId: thread.environmentId, id: thread.projectId }
574 + : projects.find(
575 + (project) =>
576 + project.environmentId === draftEnvironmentId && project.id === draftProjectId,
577 + );
578 + handleSelectThreadRoute(
579 + newTaskDestination(layout.usesSplitView, projects, currentProject, uuidv4()),
580 + );
581 };
582
583 + useHardwareKeyboardCommand("newTask", () => {
584 + handleStartNewTask();
585 + return true;
586 + });
587 +
588 // Minted here (root stack navigation) so the sidebar pane stays free of
589 // navigation hooks — on iOS it renders inside an independent nav tree.
590 const handleOpenEnvironmentSettings = () => {
@@ -499,12 +595,13 @@ function AdaptiveWorkspaceLayoutContent(
595 };
596
597 const handleOpenThreadPullRequests = useOpenThreadPullRequests();
502 - const { openPendingTask: handleOpenPendingTask } = usePendingTaskListActions();
598 + const { openPendingTask: handleOpenPendingTask } =
599 + usePendingTaskListActions(handleSelectThreadRoute);
600
601 const handleNewThreadOnBranch = (thread: EnvironmentThreadShell) => {
505 - navigation.navigate("NewTaskSheet", {
506 - screen: "NewTaskDraft",
507 - params: {
602 + handleSelectThreadRoute({
603 + draft: {
604 + requestId: uuidv4(),
605 environmentId: String(thread.environmentId),
606 projectId: String(thread.projectId),
607 branch: thread.branch,
@@ -514,9 +611,9 @@ function AdaptiveWorkspaceLayoutContent(
611 };
612
613 const handleNewThreadInProject = (project: EnvironmentProject) => {
517 - navigation.navigate("NewTaskSheet", {
518 - screen: "NewTaskDraft",
519 - params: {
614 + handleSelectThreadRoute({
615 + draft: {
616 + requestId: uuidv4(),
617 environmentId: String(project.environmentId),
618 projectId: String(project.id),
619 title: project.title,
@@ -684,47 +781,11 @@ function AdaptiveWorkspaceLayoutContent(
781 ),
782 );
783
687 - const selectAndroidWorkspace = useAndroidWorkspaceSelection();
784 const handleSelectThread = (thread: EnvironmentThreadShell) => {
689 - const params = {
785 + handleSelectThreadRoute({
786 environmentId: String(thread.environmentId),
787 threadId: String(thread.id),
692 - };
693 - if (Platform.OS === "android") {
694 - setFileInspectorPreferredVisible(false);
695 - selectAndroidWorkspace({ name: "Thread", params });
696 - return;
697 - }
698 - const navigationAction = resolveThreadSelectionNavigationAction({
699 - usesSplitView: layout.usesSplitView,
700 - pathname,
701 - });
702 - const overlayState = resolveThreadSelectionOverlayState({
703 - state: navigation.getState(),
704 - workspaceRouteKey: props.workspaceRouteKey,
705 - action: navigationAction,
706 - params,
788 });
708 - if (overlayState !== null) {
709 - setFileInspectorPreferredVisible(false);
710 - navigation.dispatch(CommonActions.reset(overlayState));
711 - return;
712 - }
713 - if (navigationAction === "set-params") {
714 - const nextThreadKey = scopedThreadKey(thread.environmentId, thread.id);
715 - if (nextThreadKey === selectedThreadKey) {
716 - return;
717 - }
718 - setFileInspectorPreferredVisible(false);
719 - navigation.navigate("Thread", params);
720 - return;
721 - }
722 - if (navigationAction === "replace") {
723 - setFileInspectorPreferredVisible(false);
724 - navigation.dispatch(StackActions.replace("Thread", params));
725 - return;
726 - }
727 - navigation.navigate("Thread", params);
789 };
790
791 const contextValue = {
@@ -732,7 +793,10 @@ function AdaptiveWorkspaceLayoutContent(
793 panes,
794 fileInspector,
795 primarySidebarSearchQuery,
796 + startNewTask: handleStartNewTask,
797 + deferThreadSelectionUntil: deferredThreadSelection.waitFor,
798 selectThread: handleSelectThread,
799 + selectThreadRoute: handleSelectThreadRoute,
800 activateAuxiliaryPaneRole,
801 registerWorkspaceInspector,
802 setPrimarySidebarSearchQuery,
@@ -881,6 +945,7 @@ function AdaptiveWorkspaceLayoutContent(
945 style={railOverlay ? { right: 0 } : { width: navigationRailWidth }}
946 >
947 <AndroidWorkspaceNavigation
948 + onNewThread={handleStartNewTask}
949 rail
950 onSelect={revealPrimarySidebar}
951 onOverlayChange={setRailOverlay}
apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx
+59 -13
@@ -48,6 +48,7 @@ import {
48 nativeWorkspacePopAction,
49 projectWorkspaceStack,
50 partitionStackPresentations,
51 + reconcileStackScreens,
52 type CollapsedSplitColumn,
53 } from "../../native/workspace-stack-projection";
54 import {
@@ -68,9 +69,10 @@ const isPullRequestRoute = (route: Route) =>
69 function ColumnScreen(props: {
70 readonly descriptor: Descriptor;
71 readonly primary?: boolean;
72 + readonly attached?: boolean;
73 readonly selectedThreadKey?: string | null;
74 readonly selectedPullRequestKey?: string | null;
73 - readonly onDismiss: (routeKey: string) => void;
75 + readonly onDismiss: (routeKey: string, native: boolean) => void;
76 readonly onAppearance: (type: "willAppear" | "didAppear" | "willDisappear", key: string) => void;
77 readonly onCompose?: () => void;
78 readonly navigation: ViewProps["navigation"];
@@ -90,8 +92,9 @@ function ColumnScreen(props: {
92 return (
93 <Split.Screen
94 screenKey={key}
95 + activityMode={props.attached === false ? "detached" : "attached"}
96 onDismiss={(event) => {
94 - if (event.nativeEvent.isNativeDismiss) props.onDismiss(key);
97 + props.onDismiss(key, event.nativeEvent.isNativeDismiss);
98 }}
99 onWillAppear={() => {
100 props.onAppearance("willAppear", key);
@@ -115,7 +118,13 @@ function ColumnScreen(props: {
118 options={descriptor.options}
119 canGoBack={!props.primary}
120 column={props.primary ? "primary" : "detail"}
118 - onCompose={props.onCompose}
121 + onCompose={
122 + descriptor.route.params &&
123 + "draft" in descriptor.route.params &&
124 + descriptor.route.params.draft
125 + ? undefined
126 + : props.onCompose
127 + }
128 />
129 <ColumnContent
130 primary={props.primary}
@@ -136,10 +145,39 @@ function ColumnScreen(props: {
145 function WorkspaceColumns(
146 props: ViewProps & { readonly primary: Route; readonly detail: Route[] },
147 ) {
139 - const { layout, panes, togglePrimarySidebar, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
148 + const { layout, panes, togglePrimarySidebar, toggleAuxiliaryPane, startNewTask } =
149 + useAdaptiveWorkspaceLayout();
150 const deviceType = useDeviceType();
151 + // Split screens must remain mounted while UIKit animates a detached route away.
152 + const [screens, setScreens] = useState({
153 + routes: props.detail,
154 + descriptors: props.descriptors,
155 + observedRoutes: props.detail,
156 + observedDescriptors: props.descriptors,
157 + completed: new Set<string>(),
158 + });
159 + if (
160 + screens.observedRoutes !== props.detail ||
161 + screens.observedDescriptors !== props.descriptors
162 + ) {
163 + const routes = reconcileStackScreens(screens.routes, props.detail, screens.completed);
164 + const retained = new Set(routes.map((route) => route.key));
165 + const active = new Set(props.detail.map((route) => route.key));
166 + setScreens({
167 + routes,
168 + descriptors: Object.fromEntries(
169 + Object.entries({ ...screens.descriptors, ...props.descriptors }).filter(([key]) =>
170 + retained.has(key),
171 + ),
172 + ),
173 + observedRoutes: props.detail,
174 + observedDescriptors: props.descriptors,
175 + completed: new Set([...screens.completed].filter((key) => active.has(key))),
176 + });
177 + }
178 +
179 const selectedTab = useWorkspaceTabs()?.state.selectedTab;
142 - const openNewTask = () => props.navigation.navigate("NewTaskSheet", { screen: "NewTask" });
180 + const openNewTask = startNewTask;
181 // The Duo keeps compose in the detail column's bar, which is its vertical bar in landscape
182 // and folded, so it sits with the column's other actions whichever screen is shown. Pull
183 // requests leave it out, including one opened from a thread; their bar is already full of
@@ -178,10 +216,17 @@ function WorkspaceColumns(
216 )
217 : null;
218 const handleNativeDismiss = useCallback(
181 - (key: string) => {
182 - const state = props.navigation.getState();
183 - const action = nativeWorkspacePopAction(state, key);
184 - if (action) props.navigation.dispatch(action);
219 + (key: string, native: boolean) => {
220 + setScreens((current) => ({
221 + ...current,
222 + routes: current.routes.filter((route) => route.key !== key),
223 + completed: new Set([...current.completed, key]),
224 + }));
225 + if (native) {
226 + const state = props.navigation.getState();
227 + const action = nativeWorkspacePopAction(state, key);
228 + if (action) props.navigation.dispatch(action);
229 + }
230 },
231 [props.navigation],
232 );
@@ -288,12 +333,13 @@ function WorkspaceColumns(
333 />
334 </ColumnContent>
335 </Split.Screen>
291 - {props.detail.map((route) => {
292 - const descriptor = props.descriptors[route.key];
336 + {screens.routes.map((route) => {
337 + const descriptor = props.descriptors[route.key] ?? screens.descriptors[route.key];
338 return descriptor ? (
339 <ColumnScreen
340 key={route.key}
341 descriptor={descriptor}
342 + attached={props.detail.some((current) => current.key === route.key)}
343 onDismiss={handleNativeDismiss}
344 onAppearance={followCollapsedSplit}
345 onCompose={isPullRequestRoute(route) ? undefined : detailCompose}
@@ -316,7 +362,7 @@ function WorkspaceColumns(
362 }
363
364 function WorkspaceStackView(props: ViewProps & { readonly nativeColumns: boolean }) {
319 - const { layout } = useAdaptiveWorkspaceLayout();
365 + const { layout, startNewTask } = useAdaptiveWorkspaceLayout();
366 // Native dismiss commits the route pop after the transition. Restore the dock
367 // when the primary screen starts appearing, including interactive back gestures.
368 const [primaryVisible, setPrimaryVisible] = useState(false);
@@ -343,7 +389,7 @@ function WorkspaceStackView(props: ViewProps & { readonly nativeColumns: boolean
389 options: { headerShown: false },
390 render: () => (
391 <WorkspaceNativeTabs
346 - onNewTask={() => props.navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
392 + onNewTask={startNewTask}
393 hidden={
394 projection.detail.length > 0 &&
395 !primaryVisible &&
apps/mobile/src/features/layout/deferred-navigation.test.ts new
+54
@@ -0,0 +1,54 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +import { createDeferredNavigation } from "./deferred-navigation";
3 +
4 +describe("workspace mutation navigation", () => {
5 + it("keeps only the latest selection until all checkouts settle", async () => {
6 + const navigation = createDeferredNavigation();
7 + const first = Promise.withResolvers<void>();
8 + const second = Promise.withResolvers<void>();
9 + const selected: string[] = [];
10 + navigation.waitFor(first.promise);
11 + navigation.waitFor(second.promise);
12 + navigation.run(() => selected.push("old draft"));
13 + navigation.run(() => selected.push("latest draft"));
14 + first.resolve();
15 + await first.promise;
16 + expect(selected).toEqual([]);
17 + second.resolve();
18 + await second.promise;
19 + expect(selected).toEqual(["latest draft"]);
20 + navigation.run(() => selected.push("thread"));
21 + expect(selected).toEqual(["latest draft", "thread"]);
22 + });
23 +
24 + it("waits for the removal guard commit after checkout completes", async () => {
25 + const navigation = createDeferredNavigation();
26 + const checkout = Promise.withResolvers<void>();
27 + const guardCommit = Promise.withResolvers<void>();
28 + let selected = false;
29 + const ready = Promise.allSettled([checkout.promise, guardCommit.promise]);
30 + navigation.waitFor(ready);
31 + navigation.run(() => {
32 + selected = true;
33 + });
34 + checkout.resolve();
35 + await checkout.promise;
36 + expect(selected).toBe(false);
37 + guardCommit.resolve();
38 + await ready;
39 + expect(selected).toBe(true);
40 + });
41 +
42 + it("releases selection after a failed checkout", async () => {
43 + const navigation = createDeferredNavigation();
44 + const checkout = Promise.withResolvers<void>();
45 + let selected = false;
46 + navigation.waitFor(checkout.promise);
47 + navigation.run(() => {
48 + selected = true;
49 + });
50 + checkout.reject(new Error("Checkout failed"));
51 + await checkout.promise.catch(() => undefined);
52 + expect(selected).toBe(true);
53 + });
54 +});
apps/mobile/src/features/layout/deferred-navigation.ts new
+22
@@ -0,0 +1,22 @@
1 +/** Hold in-place route changes while a workspace mutation is still running. */
2 +export function createDeferredNavigation() {
3 + let pending = 0;
4 + let latest: (() => void) | null = null;
5 + return {
6 + run(action: () => void) {
7 + if (pending > 0) latest = action;
8 + else action();
9 + },
10 + waitFor(operation: Promise<unknown>) {
11 + pending += 1;
12 + const release = () => {
13 + pending -= 1;
14 + if (pending !== 0) return;
15 + const action = latest;
16 + latest = null;
17 + action?.();
18 + };
19 + void operation.then(release, release);
20 + },
21 + };
22 +}
apps/mobile/src/features/layout/useWorkspaceSidebarHeaderItem.ts new
+27
@@ -0,0 +1,27 @@
1 +import { useMemo } from "react";
2 +import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns";
3 +import { useAdaptiveWorkspaceLayout } from "./AdaptiveWorkspaceLayout";
4 +import { withNativeGlassHeaderItem } from "./native-glass-header-items";
5 +
6 +export function useWorkspaceSidebarHeaderItem() {
7 + const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();
8 + const { panes, togglePrimarySidebar } = useAdaptiveWorkspaceLayout();
9 + return useMemo(
10 + () =>
11 + withNativeGlassHeaderItem({
12 + axisBehavior: usesNativeWorkspaceColumns ? "horizontalOnly" : undefined,
13 + accessibilityLabel: panes.primarySidebarVisible
14 + ? "Maximize content"
15 + : "Show thread sidebar",
16 + icon: {
17 + name: panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left",
18 + type: "sfSymbol" as const,
19 + },
20 + identifier: "thread-left-sidebar",
21 + label: panes.primarySidebarVisible ? "Maximize content" : "Show thread sidebar",
22 + onPress: togglePrimarySidebar,
23 + type: "button" as const,
24 + }),
25 + [panes.primarySidebarVisible, togglePrimarySidebar, usesNativeWorkspaceColumns],
26 + );
27 +}
apps/mobile/src/features/projects/AddProjectScreen.tsx
+29 -35
@@ -54,7 +54,13 @@ import {
54 resolveEnvironmentMachineKind,
55 SourceControlProviderKind,
56 } from "@t3tools/contracts";
57 -import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
57 +import {
58 + CommonActions,
59 + StackActions,
60 + useNavigation,
61 + type NavigationState,
62 + type ParamListBase,
63 +} from "@react-navigation/native";
64 import { SymbolView } from "../../components/ui/AppSymbol";
65 import { useEffect, useRef, useState, type ReactNode } from "react";
66 import { Platform, Pressable, View } from "react-native";
@@ -648,7 +654,10 @@ export function AddProjectSourceScreen() {
654 }
655
656 function openNewTaskDraft(
651 - navigation: { dispatch: (action: ReturnType<typeof CommonActions.reset>) => void },
657 + navigation: {
658 + dispatch: (action: ReturnType<typeof CommonActions.reset>) => void;
659 + getState: () => NavigationState<ParamListBase> | undefined;
660 + },
661 params: {
662 environmentId: EnvironmentId;
663 projectId: ProjectId;
@@ -657,9 +666,14 @@ function openNewTaskDraft(
666 draftId?: string;
667 },
668 ) {
660 - navigation.dispatch(
661 - CommonActions.reset({ index: 0, routes: [{ name: "NewTaskDraft", params }] }),
662 - );
669 + const state = navigation.getState();
670 + if (!state) return;
671 + const threadIndex = state.routes.findLastIndex((route) => route.name === "Thread");
672 + const routes = [
673 + ...state.routes.slice(0, threadIndex < 0 ? state.index : threadIndex),
674 + { key: uuidv4(), name: "Thread", params: { draft: params } },
675 + ];
676 + navigation.dispatch(CommonActions.reset({ ...state, index: routes.length - 1, routes }));
677 }
678
679 async function draftWithPrompt(
@@ -698,21 +712,11 @@ function useCreateProject(environment: EnvironmentOption | null) {
712 });
713 if (existing) {
714 Dialog.alert("Project already exists", existing.title);
701 - navigation.dispatch(
702 - CommonActions.reset({
703 - index: 0,
704 - routes: [
705 - {
706 - name: "NewTaskDraft",
707 - params: {
708 - environmentId: existing.environmentId,
709 - projectId: existing.id,
710 - title: existing.title,
711 - },
712 - },
713 - ],
714 - }),
715 - );
715 + openNewTaskDraft(navigation, {
716 + environmentId: existing.environmentId,
717 + projectId: existing.id,
718 + title: existing.title,
719 + });
720 return;
721 }
722
@@ -729,21 +733,11 @@ function useCreateProject(environment: EnvironmentOption | null) {
733 if (AsyncResult.isFailure(result)) {
734 return result;
735 }
732 - navigation.dispatch(
733 - CommonActions.reset({
734 - index: 0,
735 - routes: [
736 - {
737 - name: "NewTaskDraft",
738 - params: {
739 - environmentId: environment.environmentId,
740 - projectId,
741 - title: inferProjectTitleFromPath(workspaceRoot),
742 - },
743 - },
744 - ],
745 - }),
746 - );
736 + openNewTaskDraft(navigation, {
737 + environmentId: environment.environmentId,
738 + projectId,
739 + title: inferProjectTitleFromPath(workspaceRoot),
740 + });
741 return result;
742 };
743 }
apps/mobile/src/features/prompt-links/usePromptLinkResolver.ts
+5 -3
@@ -131,9 +131,11 @@ export function usePromptLinkResolver(params: Readonly<Record<string, unknown>>
131 }
132 const modelUnavailable = writeDraft(draftKey, project.environmentId, request);
133 navigation.dispatch(
134 - StackActions.push("NewTaskDraft", {
135 - draftId: draftKey,
136 - title: request.pullRequest ? `PR #${request.pullRequest.number}` : project.title,
134 + StackActions.push("Thread", {
135 + draft: {
136 + draftId: draftKey,
137 + title: request.pullRequest ? `PR #${request.pullRequest.number}` : project.title,
138 + },
139 }),
140 );
141 if (request.prompt || pullRequestUnavailable !== null || modelUnavailable) {
apps/mobile/src/features/pull-requests/usePullRequestThreads.ts
+2 -3
@@ -146,9 +146,8 @@ export function usePullRequestThreads(
146 previousPrompts.current.set(draftKey, pullRequestAgentPrompt(task));
147 if (thread) openThread(thread);
148 else
149 - navigation.navigate("NewTaskSheet", {
150 - screen: "NewTaskDraft",
151 - params: { draftId: draftKey, title: `Ask about #${pr.number}` },
149 + navigation.navigate("Thread", {
150 + draft: { draftId: draftKey, title: `Ask about #${pr.number}` },
151 });
152 });
153 pending.current = false;
apps/mobile/src/features/threads/ComposerAttachmentButton.tsx
+2 -1
@@ -12,6 +12,7 @@ const ATTACHMENT_MENU_ACTIONS: MenuAction[] = [
12
13 export function ComposerAttachmentButton(props: {
14 readonly disabled?: boolean;
15 + readonly size?: "regular" | "large";
16 readonly supportsFiles: boolean;
17 readonly onPickMedia: () => Promise<void>;
18 readonly onPickFiles: () => Promise<void>;
@@ -28,7 +29,7 @@ export function ComposerAttachmentButton(props: {
29 >
30 <SymbolView
31 name="plus"
31 - size={Math.round(20 * scale)}
32 + size={Math.round((props.size === "large" ? 26 : 20) * scale)}
33 weight="regular"
34 tintColorClassName="accent-icon"
35 type="monochrome"
apps/mobile/src/features/threads/DraftEnvironmentControl.tsx new
+38
@@ -0,0 +1,38 @@
1 +import { Pressable } from "react-native";
2 +import type { EnvironmentMachineKind } from "@t3tools/contracts";
3 +import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
4 +import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
5 +import { AppText as Text } from "../../components/ui/AppText";
6 +import { SymbolView } from "../../components/ui/AppSymbol";
7 +
8 +import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";
9 +
10 +export function DraftEnvironmentControl(props: {
11 + readonly label: string;
12 + readonly connectionState: EnvironmentConnectionPhase;
13 + readonly machineKind: EnvironmentMachineKind;
14 + readonly disabled: boolean;
15 + readonly onChooseEnvironment: () => void;
16 +}) {
17 + const disconnected = props.connectionState !== "connected";
18 + return (
19 + <Pressable
20 + accessibilityRole="button"
21 + accessibilityLabel={`Choose environment, ${props.label}, ${disconnected ? "Offline" : "Connected"}`}
22 + disabled={props.disabled}
23 + onPress={props.onChooseEnvironment}
24 + className="flex-row items-center gap-1.5 rounded-xl px-3 py-2 active:opacity-65"
25 + >
26 + <EnvironmentMachineSymbol
27 + kind={props.machineKind}
28 + size={13}
29 + tintColorClassName="accent-icon-muted"
30 + />
31 + <Text className="shrink text-sm text-foreground-muted" numberOfLines={1}>
32 + on {props.label}
33 + </Text>
34 + <SymbolView name="chevron.right" size={11} tintColorClassName="accent-icon-muted" />
35 + {disconnected ? <ConnectionStatusDot state="error" pulse={false} size={6} /> : null}
36 + </Pressable>
37 + );
38 +}
apps/mobile/src/features/threads/DraftThreadHeader.tsx new
+100
@@ -0,0 +1,100 @@
1 +import { uuidv4 } from "../../lib/uuid";
2 +import * as Dialog from "../../components/ui/Dialog";
3 +import { useNavigation } from "@react-navigation/native";
4 +import { AsyncResult } from "effect/reactivity";
5 +import * as Cause from "effect/Cause";
6 +import { AuthFilesystemReadScope, AuthSourceControlWriteScope } from "@t3tools/contracts";
7 +import type {
8 + EnvironmentProject,
9 + EnvironmentThreadShell,
10 +} from "@t3tools/client-runtime/state/shell";
11 +import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
12 +import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
13 +import { useEnvironmentQuery } from "../../state/query";
14 +import { useEnvironmentScope } from "../../state/session";
15 +import { useAtomCommand } from "../../state/use-atom-command";
16 +import { vcsActionManager, vcsEnvironment } from "../../state/vcs";
17 +import { useVcsActionState } from "../../state/use-vcs-action-state";
18 +import { ThreadHeader } from "./ThreadHeader";
19 +
20 +export function DraftThreadHeader(props: {
21 + readonly thread: EnvironmentThreadShell;
22 + readonly project: EnvironmentProject;
23 + readonly cwd: string | null;
24 +}) {
25 + const navigation = useNavigation();
26 + const { themeVariables } = useAppearancePreferences();
27 + const environmentId = props.thread.environmentId;
28 + const canReadFiles = useEnvironmentScope(environmentId, AuthFilesystemReadScope);
29 + const canWriteGit = useEnvironmentScope(environmentId, AuthSourceControlWriteScope);
30 + const status = useEnvironmentQuery(
31 + props.cwd ? vcsEnvironment.status({ environmentId, input: { cwd: props.cwd } }) : null,
32 + );
33 + const target = { environmentId, cwd: props.cwd };
34 + const progress = useVcsActionState(target);
35 + const runAction = useAtomCommand(vcsActionManager.runStackedAction(target), {
36 + reportFailure: false,
37 + });
38 + const pull = useAtomCommand(vcsEnvironment.pull, { reportFailure: false });
39 + const openFiles = () => {
40 + if (!props.cwd || !canReadFiles) return;
41 + navigation.navigate("NewTaskFiles", {
42 + environmentId,
43 + cwd: props.cwd,
44 + projectName: props.project.title,
45 + });
46 + };
47 + const requiresThread = () =>
48 + Dialog.alert("Available after the first message", "This action needs a saved thread.");
49 + return (
50 + <ThreadHeader
51 + draft
52 + title="New thread"
53 + subtitle=""
54 + headerColor={themeVariables["--color-header"]}
55 + usesNativeHeaderGlass={NATIVE_LIQUID_GLASS_SUPPORTED}
56 + hasThreadCwd={props.cwd !== null}
57 + hasWorkspaceRoot={Boolean(props.project.workspaceRoot)}
58 + fileInspectorSupported={false}
59 + inspectorMode={null}
60 + onToggleInspector={openFiles}
61 + onOpenFilesInspector={openFiles}
62 + onOpenGitInspector={requiresThread}
63 + gitControls={{
64 + environmentId,
65 + threadId: props.thread.id,
66 + hasThread: false,
67 + currentBranch: props.thread.branch,
68 + gitStatus: status.data,
69 + gitOperationLabel: progress.currentLabel,
70 + canOpenTerminal: false,
71 + canOperateTerminal: false,
72 + canOpenFiles: canReadFiles && props.cwd !== null,
73 + projectScripts: [],
74 + terminalSessions: [],
75 + onOpenFilesInspector: openFiles,
76 + onOpenGitInspector: requiresThread,
77 + onOpenTerminal: requiresThread,
78 + onOpenNewTerminal: requiresThread,
79 + onRunProjectScript: async () => {
80 + requiresThread();
81 + },
82 + onPull: async () => {
83 + if (!canWriteGit || !props.cwd) return;
84 + const result = await pull({ environmentId, input: { cwd: props.cwd } });
85 + if (AsyncResult.isFailure(result))
86 + Dialog.alert("Could not pull", String(Cause.squash(result.cause)));
87 + },
88 + onRunAction: async (input) => {
89 + if (!canWriteGit || !props.cwd) return null;
90 + const result = await runAction({ ...input, actionId: uuidv4() });
91 + if (AsyncResult.isFailure(result)) {
92 + Dialog.alert("Git action failed", String(Cause.squash(result.cause)));
93 + return null;
94 + }
95 + return result.value;
96 + },
97 + }}
98 + />
99 + );
100 +}
apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx
+101 -13
@@ -7,7 +7,11 @@ import { NavigationRow } from "../../components/ui/NavigationRow";
7 import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
8 import { shouldCheckoutNewTaskBranch } from "./new-task-context-presentation";
9 import type { VcsRef } from "@t3tools/client-runtime/state/vcs";
10 -import { AuthSourceControlWriteScope, resolveEnvironmentMachineKind } from "@t3tools/contracts";
10 +import {
11 + AuthSourceControlWriteScope,
12 + resolveEnvironmentMachineKind,
13 + type EnvironmentId,
14 +} from "@t3tools/contracts";
15 import { LegendList } from "@legendapp/list/react-native";
16 import {
17 isAtomCommandInterrupted,
@@ -27,7 +31,6 @@ import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSym
31 import { ThemedSwitch } from "../../components/ui/ThemedSwitch";
32 import { cn } from "../../lib/cn";
33 import { NativeStackScreenOptions } from "../../native/StackHeader";
30 -import { useServerConfigs } from "../../state/entities";
34 import { useEnvironmentScope } from "../../state/session";
35 import { useAtomCommand } from "../../state/use-atom-command";
36 import { vcsEnvironment } from "../../state/vcs";
@@ -39,6 +42,100 @@ import { useNativeMailSearchToolbar } from "../../native/use-native-mail-search-
42 import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
43 import { checkoutNewTaskBranch } from "./checkout-new-task-branch";
44
45 +import { useEnvironmentPresentation } from "../../state/presentation";
46 +import { useRemoteConnections } from "../../state/use-remote-environment-registry";
47 +import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";
48 +import {
49 + ConnectionDiagnosisDetails,
50 + useConnectionDiagnosis,
51 +} from "../connection/ConnectionDiagnosisDetails";
52 +import { environmentStatusText } from "../connection/environmentStatusText";
53 +
54 +function EnvironmentPickerRow(props: {
55 + environmentId: EnvironmentId;
56 + title: string;
57 + selected: boolean;
58 + disabled: boolean;
59 + isLast: boolean;
60 + onPress: () => void;
61 +}) {
62 + const [expanded, setExpanded] = useState(false);
63 + const { presentation } = useEnvironmentPresentation(props.environmentId);
64 + const { diagnosis, state } = useConnectionDiagnosis(props.environmentId, presentation);
65 + const { onReconnectEnvironment } = useRemoteConnections();
66 + const connection = presentation?.connection;
67 + const status =
68 + diagnosis?.headline ??
69 + (connection ? environmentStatusText({ ...connection, error: null }) : "Offline");
70 + return (
71 + <View className={cn("bg-grouped-card", !props.isLast && "border-b border-border-subtle")}>
72 + <View className="flex-row items-center">
73 + <Pressable
74 + accessibilityRole="radio"
75 + accessibilityLabel={`${props.title}, ${status}`}
76 + accessibilityState={{ checked: props.selected }}
77 + disabled={props.disabled}
78 + onPress={props.onPress}
79 + className="min-h-16 flex-1 flex-row items-center gap-3 px-4 py-3 active:bg-subtle"
80 + >
81 + <EnvironmentMachineSymbol
82 + kind={resolveEnvironmentMachineKind(presentation?.serverConfig ?? null)}
83 + size={20}
84 + tintColorClassName="accent-icon-muted"
85 + />
86 + <View className="min-w-0 flex-1 gap-1">
87 + <Text className="text-base font-t3-medium text-foreground" numberOfLines={1}>
88 + {props.title}
89 + </Text>
90 + <View className="flex-row items-center gap-1.5">
91 + <ConnectionStatusDot state={connection?.phase ?? "offline"} pulse={false} size={6} />
92 + <Text className="shrink text-xs text-foreground-muted" numberOfLines={2}>
93 + {status}
94 + </Text>
95 + </View>
96 + </View>
97 + {props.selected ? (
98 + <SymbolView name="checkmark" size={16} tintColorClassName="accent-icon" />
99 + ) : null}
100 + </Pressable>
101 + <Pressable
102 + accessibilityRole="button"
103 + accessibilityLabel={`${expanded ? "Hide" : "Show"} connection details for ${props.title}`}
104 + accessibilityState={{ expanded }}
105 + onPress={() => setExpanded(!expanded)}
106 + className="min-h-11 min-w-11 items-center justify-center active:opacity-65"
107 + >
108 + <SymbolView
109 + name={expanded ? "chevron.up" : "chevron.down"}
110 + size={13}
111 + tintColorClassName="accent-icon-muted"
112 + />
113 + </Pressable>
114 + </View>
115 + {expanded ? (
116 + <View className="gap-3 px-4 pb-4">
117 + {diagnosis ? (
118 + <ConnectionDiagnosisDetails hostLabel={props.title} diagnosis={diagnosis} />
119 + ) : (
120 + <Text className="text-sm text-foreground-muted">{status}</Text>
121 + )}
122 + {state.retryAt ? (
123 + <Text className="text-sm text-foreground-muted">
124 + Next reconnect at {new Date(state.retryAt).toLocaleTimeString()}
125 + </Text>
126 + ) : null}
127 + {connection?.phase !== "connected" ? (
128 + <Button
129 + label="Reconnect now"
130 + onPress={() => onReconnectEnvironment(props.environmentId)}
131 + />
132 + ) : null}
133 + </View>
134 + ) : null}
135 + </View>
136 + );
137 +}
138 +
139 function SelectionRow(props: {
140 readonly icon?: "arrow.triangle.branch" | ReactNode;
141 readonly onPress: () => void;
@@ -203,7 +300,6 @@ export function NewTaskEnvironmentPickerRouteScreen() {
300 const flow = useNewTaskFlow();
301 const navigation = useNavigation();
302 const insets = useSafeAreaInsets();
206 - const serverConfigs = useServerConfigs();
303 return (
304 <View className="flex-1 bg-sheet" collapsable={false}>
305 <NativeStackScreenOptions
@@ -231,17 +327,9 @@ export function NewTaskEnvironmentPickerRouteScreen() {
327 >
328 <PickerSurface>
329 {flow.environments.map((environment, index) => (
234 - <SelectionRow
330 + <EnvironmentPickerRow
331 key={String(environment.environmentId)}
236 - icon={
237 - <EnvironmentMachineSymbol
238 - kind={resolveEnvironmentMachineKind(
239 - serverConfigs.get(environment.environmentId) ?? null,
240 - )}
241 - size={Platform.OS === "android" ? 24 : 17}
242 - tintColorClassName="accent-icon-muted"
243 - />
244 - }
332 + environmentId={environment.environmentId}
333 isLast={index === flow.environments.length - 1}
334 disabled={flow.switchingToEnvironmentId !== null}
335 onPress={() => {
apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx
+48 -21
@@ -1,6 +1,14 @@
1 +import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
2 +import { useNewTaskFlow } from "./new-task-flow-provider";
3 import * as Dialog from "../../components/ui/Dialog";
2 -import { useNavigation, usePreventRemove, type StaticScreenProps } from "@react-navigation/native";
3 -import { useEffect, useMemo, useRef, useState } from "react";
4 +import {
5 + useNavigation,
6 + useRoute,
7 + usePreventRemove,
8 + usePreventRemoveContext,
9 + type StaticScreenProps,
10 +} from "@react-navigation/native";
11 +import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
12 import { View } from "react-native";
13 import {
14 isAtomCommandInterrupted,
@@ -15,22 +23,22 @@ import { checkoutNewTaskBranch } from "./checkout-new-task-branch";
23 import { resolveNewTaskBranchWorktreePath } from "./new-task-context-presentation";
24 import { NativeStackScreenOptions } from "../../native/StackHeader";
25
26 +import { ThreadScreenFallback } from "./ThreadScreenHost";
27 import { NewTaskDraftScreen } from "./NewTaskDraftScreen";
28
20 -type NewTaskDraftRouteParams = {
21 - readonly environmentId?: string | string[];
22 - readonly projectId?: string | string[];
23 - readonly branch?: string | null;
24 - readonly worktreePath?: string | null;
25 - readonly title?: string | string[];
26 - readonly cloning?: string | string[];
27 - readonly pendingTaskId?: string | string[];
28 - readonly draftId?: string | string[];
29 - readonly incomingShareId?: string | string[];
30 -};
29 +import type { NewTaskDraftRouteParams } from "./thread-route-state";
30 +export type { NewTaskDraftRouteParams } from "./thread-route-state";
31
32 export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraftRouteParams>) {
33 + const currentRoute = useRoute();
34 const params = useMemo(() => route.params ?? {}, [route.params]);
35 + const { reset } = useNewTaskFlow();
36 + const { deferThreadSelectionUntil } = useAdaptiveWorkspaceLayout();
37 + const [initialized, setInitialized] = useState(false);
38 + useLayoutEffect(() => {
39 + reset();
40 + setInitialized(true);
41 + }, [reset]);
42 const pendingTaskId = Array.isArray(params.pendingTaskId)
43 ? params.pendingTaskId[0]
44 : params.pendingTaskId;
@@ -70,6 +78,7 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
78
79 const [pendingCheckouts, setPendingCheckouts] = useState(0);
80 const checkoutTail = useRef(Promise.resolve());
81 + const committedCheckoutReleases = useRef(new Set<() => void>());
82 const waitingForProject =
83 !project &&
84 (catalogState.isLoadingConnections ||
@@ -103,10 +112,14 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
112 setPendingCheckouts((count) => count - 1);
113 if (active) setPreparation({ request: initialProjectRef, result, workspaceRoot });
114 });
115 + const committed = Promise.withResolvers<void>();
116 + committedCheckoutReleases.current.add(committed.resolve);
117 + deferThreadSelectionUntil(Promise.allSettled([checkoutTail.current, committed.promise]));
118 return () => {
119 active = false;
120 };
121 }, [
122 + deferThreadSelectionUntil,
123 environmentId,
124 workspaceRoot,
125 initialProjectRef,
@@ -124,6 +137,21 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
137 // A replaced request must settle too before the shared checkout is left behind.
138 const checkoutPending = pendingCheckouts > 0 || (needsPreparation && result === null);
139 usePreventRemove(checkoutPending, () => undefined);
140 + const { preventedRoutes } = usePreventRemoveContext();
141 + const removalBlocked = preventedRoutes[currentRoute.key]?.preventRemove === true;
142 + useEffect(() => {
143 + if (checkoutPending || removalBlocked) return;
144 + // Native-stack reads the provider state, which commits after the hook updates its registry.
145 + for (const release of committedCheckoutReleases.current) release();
146 + committedCheckoutReleases.current.clear();
147 + }, [checkoutPending, removalBlocked]);
148 + useEffect(() => {
149 + const releases = committedCheckoutReleases.current;
150 + return () => {
151 + for (const release of releases) release();
152 + releases.clear();
153 + };
154 + }, []);
155 useEffect(() => {
156 if (checkoutPending || result?._tag !== "Failure") return;
157 if (!isAtomCommandInterrupted(result)) {
@@ -153,17 +181,16 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
181 );
182 const preparingBranch = checkoutPending || (needsPreparation && result?._tag !== "Success");
183
184 + if (!initialized) return null;
185 return (
186 <>
158 - <NativeStackScreenOptions
159 - options={{
160 - title: Array.isArray(params.title) ? params.title[0] : (params.title ?? "New task"),
161 - }}
162 - />
187 {preparingBranch ? (
164 - <View className="flex-1 items-center justify-center bg-screen">
165 - <Text className="text-foreground">Switching branch...</Text>
166 - </View>
188 + <ThreadScreenFallback>
189 + <NativeStackScreenOptions options={{ title: "New thread" }} />
190 + <View className="flex-1 items-center justify-center bg-screen">
191 + <Text className="text-foreground">Switching branch...</Text>
192 + </View>
193 + </ThreadScreenFallback>
194 ) : (
195 <NewTaskDraftScreen
196 initialProjectRef={preparedProjectRef}
apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+273 -875
@@ -1,110 +1,59 @@
1 -import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader";
2 -import { SheetHeader } from "../../components/ui/SheetHeader";
3 -import { Button } from "../../components/ui/Button";
1 +import { DraftEnvironmentControl } from "./DraftEnvironmentControl";
2 +import { NativeScrollEdgeEffectsContext } from "../../native/NativeScrollViewMarker";
3 +import { DraftThreadHeader } from "./DraftThreadHeader";
4 +import { threadHeaderAppearance } from "./thread-header-appearance";
5 +import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
6 +import { useComposerAttachmentActions } from "../../state/use-composer-attachment-actions";
7 +import { useWorkspaceBackNavigation } from "../workspace/useAndroidWorkspaceNavigation";
8 +import { submittedThreadParams } from "./thread-route-state";
9 +import { ThreadScreenBinding, ThreadScreenFallback } from "./ThreadScreenHost";
10 +import { draftThreadShell } from "./draft-thread-shell";
11 +import { connectionTone } from "../connection/connectionTone";
12 +import { AppBar } from "../../components/ui/AppBar";
13 +import { ThreadId } from "@t3tools/contracts";
14 +
15 import * as Dialog from "../../components/ui/Dialog";
16 import { useAtomValue } from "@effect/atom-react";
17 import * as Cause from "effect/Cause";
18 import { AsyncResult } from "effect/reactivity";
19 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
9 -import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
10 -import {
11 - nextPastedTextFileName,
12 - pastedTextDisposition,
13 - replaceTextSelection,
14 -} from "@t3tools/client-runtime/text-paste";
15 -import { NativeStackScreenOptions } from "../../native/StackHeader";
20 import {
21 CommonActions,
22 StackActions,
19 - useFocusEffect,
23 useNavigation,
24 usePreventRemove,
22 - type NavigationAction,
25 } from "@react-navigation/native";
24 -import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from "react";
26 +import { useEffect, useEffectEvent, useRef, useState } from "react";
27 import { Platform, Pressable, View } from "react-native";
28 import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
27 -import {
28 - KeyboardController,
29 - KeyboardStickyView,
30 - useKeyboardState,
31 -} from "react-native-keyboard-controller";
32 -import Animated, { FadeInDown, ReduceMotion } from "react-native-reanimated";
33 -import { useSafeAreaInsets } from "react-native-safe-area-context";
34 -import { useUniwindTheme } from "../../lib/useUniwindTheme";
35 -import { FONT_FAMILIES } from "../../lib/fontFamilies";
29 +import { KeyboardController } from "react-native-keyboard-controller";
30 +
31 import {
32 AuthOrchestrationOperateScope,
33 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
39 - PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
34 resolveEnvironmentMachineKind,
35 } from "@t3tools/contracts";
42 -import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
36
44 -import {
45 - ComposerEditor,
46 - type ComposerEditorHandle,
47 - type ComposerTextPaste,
48 -} from "../../components/ComposerEditor";
37 +import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
38 import { composerContextImportsAtom } from "../../state/use-composer-drafts";
50 -import {
51 - composerContextSendBlockReason,
52 - type ComposerDocumentAttachment,
53 -} from "../../lib/composerContext";
54 -import {
55 - ComposerActionButton,
56 - ComposerInlineControl,
57 - ComposerToolbarRow,
58 -} from "../../components/ComposerToolbar";
59 -import { ScreenContent } from "../../components/ui/ScreenContent";
60 -import { ComposerAttachmentButton } from "./ComposerAttachmentButton";
61 -import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
62 -import { composerStripAttachments } from "../../lib/composerImages";
63 -import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
39 +import { composerContextSendBlockReason } from "../../lib/composerContext";
40 +import { ComposerInlineControl } from "../../components/ComposerToolbar";
41 +
42 import {
43 composerAttachmentUploadBlockReason,
44 composerAttachmentsStillUploading,
45 composerAttachmentUploadsAtom,
46 } from "../../state/composer-attachment-uploads";
69 -import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
70 -import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";
71 -import { ComposerModelControl } from "../../components/ComposerModelControl";
47 +
48 import { SymbolView } from "../../components/ui/AppSymbol";
49 import { AppText as Text } from "../../components/ui/AppText";
74 -import { hasProviderUsageLimits, isUsageLimitsCommand } from "@t3tools/shared/usageLimits";
50 import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences";
76 -import { COMPOSER_LAYOUT_TRANSITION, ComposerSurface } from "./ThreadComposer";
77 -import { ComposerCommandPopover } from "./ComposerCommandPopover";
78 -import { ComposerPopoverAnchor } from "./ComposerPopoverAnchor";
79 -import { useComposerCommandMenu } from "./use-composer-command-menu";
80 -import {
81 - ComposerDictationCancelAction,
82 - ComposerDictationPrimaryAction,
83 - ComposerDictationStatus,
84 - ComposerDictationToolbar,
85 -} from "../voice-input/ComposerDictationControl";
86 -import { useVoiceInputController } from "../voice-input/useVoiceInputController";
87 -import { resolveVoiceComposerPresentation } from "../voice-input/voiceInputPresentation";
88 -import {
89 - useThreadSettingsSheetPresentation,
90 - type NavigationWithFinishTransitioning,
91 -} from "./use-thread-settings-sheet-presentation";
51 +
52 import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
93 -import {
94 - convertPastedImagesToAttachments,
95 - createPastedTextComposerAttachment,
96 - pickComposerFiles,
97 - pickComposerMedia,
98 - removePersistedComposerAttachmentFile,
99 - type DraftComposerFileAttachment,
100 -} from "../../lib/composerImages";
101 -import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
53 +
54 import {
55 clearComposerDraftContent,
104 - captureComposerDraftInsertion,
105 - countComposerDraftAttachmentsAfterSelection,
56 getComposerDraftSnapshot,
107 - composerDraftsAtom,
57 mergeComposerDraftContent,
58 restoreComposerDraftSnapshot,
59 updateComposerDraftSettings,
@@ -112,7 +61,7 @@ import {
61 type ComposerDraft,
62 waitForComposerDraftsLoaded,
63 } from "../../state/use-composer-drafts";
115 -import { useEnvironmentServerConfig, useProjects, useThreadShells } from "../../state/entities";
64 +import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
65 import { useProjectClone } from "../../state/projectClones";
66 import { projectEnvironment } from "../../state/projects";
67 import { sourceControlEnvironment } from "../../state/sourceControl";
@@ -123,9 +72,11 @@ import {
72 isModelSelectionUnavailable,
73 resolveSelectableModelSelection,
74 } from "../../lib/modelOptions";
126 -import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
75 import { enqueueThreadOutboxMessage } from "../../state/thread-outbox";
128 -import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
76 +import {
77 + useRemoteConnections,
78 + useRemoteEnvironmentRuntime,
79 +} from "../../state/use-remote-environment-registry";
80 import { useNewTaskFlow } from "./new-task-flow-provider";
81 import {
82 nextEnvironmentId,
@@ -142,10 +93,8 @@ import { useIncomingShare } from "../sharing/IncomingShareProvider";
93 import { selectIncomingShareAttachmentsForServer } from "../sharing/incoming-share-model";
94 import { appAtomRegistry } from "../../state/atom-registry";
95 import { serverEnvironment } from "../../state/server";
145 -import { fileRoutePathSegments } from "../files/filePath";
146 -import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
96
148 -const COMPOSER_POPOVER_ENTERING = FadeInDown.duration(180).reduceMotion(ReduceMotion.System);
97 +import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
98
99 function NewTaskWorkspaceIcon(props: {
100 readonly workspaceMode: "local" | "worktree";
@@ -204,9 +153,11 @@ export function NewTaskDraftScreen(props: {
153 readonly draftId?: string;
154 readonly incomingShareId?: string;
155 }) {
156 + const [creationMetadata] = useState(makeTurnCommandMetadata);
157 const projects = useProjects();
158 const flow = useNewTaskFlow();
159 const navigation = useNavigation();
160 + const goBack = useWorkspaceBackNavigation("threads");
161 const {
162 consumeShare,
163 getShare,
@@ -214,10 +165,6 @@ export function NewTaskDraftScreen(props: {
165 releaseShareReservation,
166 reserveShare,
167 } = useIncomingShare();
217 - const insets = useSafeAreaInsets();
218 - const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
219 - const controlsBottomPadding = Math.max(insets.bottom, 10);
220 - const keyboardOpenedOffset = Math.max(0, controlsBottomPadding - 8);
168 const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
169 const selectedProjectLabel = (() => {
170 if (!selectedProject) return null;
@@ -230,22 +177,17 @@ export function NewTaskDraftScreen(props: {
177 );
178 return scope?.title ?? selectedProject.title;
179 })();
233 - const { connectedEnvironments } = useRemoteConnectionStatus();
180 + const { onReconnectEnvironment } = useRemoteConnections();
181 + const environmentRuntime = useRemoteEnvironmentRuntime(selectedProject?.environmentId ?? null);
182 + const connectionState = environmentRuntime?.connectionState ?? "offline";
183 const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
184 selectedProject?.environmentId ?? null,
185 );
237 - const environmentConnected =
238 - selectedProject !== null &&
239 - connectedEnvironments.find(
240 - (environment) => environment.environmentId === selectedProject.environmentId,
241 - )?.connectionState === "connected";
186 + const environmentConnected = connectionState === "connected";
187 const canOperate = useEnvironmentScope(
188 selectedProject?.environmentId ?? null,
189 AuthOrchestrationOperateScope,
190 );
246 - const taskPermissionReason =
247 - environmentConnected && !canOperate ? "This connection cannot start tasks." : null;
248 - const modelUnavailable = environmentConnected && flow.selectedModelOption?.isUnavailable === true;
191 const projectCloneState = useProjectClone(
192 selectedProject
193 ? { environmentId: selectedProject.environmentId, projectId: selectedProject.id }
@@ -323,105 +265,22 @@ export function NewTaskDraftScreen(props: {
265 const queuesInsteadOfStarting = !environmentConnected || attachmentsUploading;
266 const promptInputRef = useRef<ComposerEditorHandle>(null);
267 const loadedBranchesProjectKeyRef = useRef<string | null>(null);
326 - const [isComposerFocused, setIsComposerFocused] = useState(false);
327 - const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
328 - const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
329 - const wasFocusedBeforePreviewRef = useRef(false);
330 - const openVideoPreview = (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
331 - wasFocusedBeforePreviewRef.current = isComposerFocused;
332 - setPreviewFile(null);
333 - setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
334 - };
335 - const openFilePreview = (source: FilePreviewSource) => {
336 - wasFocusedBeforePreviewRef.current = isComposerFocused;
337 - setPreviewVideo(null);
338 - setPreviewFile((current) => current ?? source);
339 - };
340 - const closeMediaPreview = () => {
341 - setPreviewVideo(null);
342 - setPreviewFile(null);
343 - if (wasFocusedBeforePreviewRef.current) {
344 - setTimeout(() => {
345 - if (navigation.isFocused()) promptInputRef.current?.focus();
346 - }, 100);
347 - }
348 - };
349 - const settingsSheetPresentation = useThreadSettingsSheetPresentation({
350 - editorRef: promptInputRef,
351 - isEditorFocused: isComposerFocused,
352 - });
353 - useEffect(() => {
354 - if (Platform.OS !== "ios") {
355 - return;
356 - }
357 -
358 - navigation.getParent()?.setOptions({ gestureEnabled: !isKeyboardVisible });
359 - }, [isKeyboardVisible, navigation]);
360 - useEffect(() => {
361 - return () => {
362 - if (Platform.OS === "ios") {
363 - navigation.getParent()?.setOptions({ gestureEnabled: true });
364 - }
365 - };
366 - }, [navigation]);
367 - const settingsRoutePresentedRef = useRef(false);
368 - useEffect(() => {
369 - if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
370 - return;
371 - }
372 -
373 - settingsRoutePresentedRef.current = true;
374 - navigation.dispatch(StackActions.push("ThreadSettings"));
375 - }, [navigation, settingsSheetPresentation.isVisible]);
376 - useFocusEffect(() => {
377 - if (!settingsRoutePresentedRef.current) {
378 - return;
379 - }
380 -
381 - settingsRoutePresentedRef.current = false;
382 - settingsSheetPresentation.onDismissed();
383 - });
384 - useEffect(
385 - () =>
386 - // UIKit's completion callback for the sheet dismissal, surfaced by the
387 - // native-stack patch. This is when the queued keyboard restore runs.
388 - (navigation as unknown as NavigationWithFinishTransitioning).addListener(
389 - "finishTransitioning",
390 - settingsSheetPresentation.onStackTransitionsFinished,
391 - ),
392 - [navigation, settingsSheetPresentation.onStackTransitionsFinished],
393 - );
268 const [importingShareKey, setImportingShareKey] = useState<string | null>(null);
269 const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);
270 const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);
271 const [isReturningToProjectPicker, setIsReturningToProjectPicker] = useState(false);
398 - const [submitNavigationAction, setSubmitNavigationAction] = useState<NavigationAction | null>(
399 - null,
400 - );
272 const [shareImportAttempt, setShareImportAttempt] = useState(0);
273 const startedShareImportKeyRef = useRef<string | null>(null);
274 const cancellingShareImportKeyRef = useRef<string | null>(null);
275 const shareImportDraftBackupRef = useRef(new Map<string, ComposerDraft>());
276 const activeShareImportTokenRef = useRef<symbol | null>(null);
277 const shareImportMountedRef = useRef(true);
407 - const pendingPastedTextAttachmentCountRef = useRef(0);
408 - const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0);
409 - const pastedTextFileNamesRef = useRef<{ draftKey: string | null; names: Set<string> }>({
410 - draftKey: null,
411 - names: new Set(),
412 - });
278 // The share import resumes after awaits; this reads the screen's current
279 // draft and share at that point without re-running the import effect.
280 const isCurrentShareImport = useEffectEvent(
281 (draftKey: string, shareId: string) =>
282 flow.draftKey === draftKey && props.incomingShareId === shareId,
283 );
419 - // Pasted-text attachments finish in an event handler, where an effect event
420 - // cannot be called and the provider's draft key has no store to read.
421 - const latestDraftKeyRef = useRef(flow.draftKey);
422 - useLayoutEffect(() => {
423 - latestDraftKeyRef.current = flow.draftKey;
424 - });
284 const isImportingShare = importingShareKey !== null;
285 const alertedUnavailableIncomingShareIdRef = useRef<string | null>(null);
286 // The share this screen already moved into its draft. Sending clears the
@@ -463,66 +322,15 @@ export function NewTaskDraftScreen(props: {
322 };
323 const cycleEnvironmentCommands = environments.length > 1 ? (["cycleHost"] as const) : [];
324 useHardwareKeyboardCommand(cycleEnvironmentCommands, cycleEnvironment);
466 - const offersUsageLimits =
467 - flow.selectedProviderStatus !== null &&
468 - hasProviderUsageLimits(
469 - flow.selectedProviderStatus.driver,
470 - selectedEnvironmentServerConfig?.providers ?? [],
471 - selectedEnvironmentServerConfig?.usageLimitSources ?? [],
472 - );
325 const composerWorkspaceCwd =
326 (flow.workspaceMode === "worktree"
327 ? selectedProject?.workspaceRoot
328 : (flow.selectedWorktreePath ?? selectedProject?.workspaceRoot)) || null;
477 - const stripAttachments = composerStripAttachments(flow.attachments);
478 - const composerMenu = useComposerCommandMenu({
479 - draftMessage: flow.prompt,
480 - ownerKey: flow.draftKey,
481 - environmentId: selectedProject?.environmentId ?? null,
482 - threadShells: useThreadShells(),
483 - pullRequestProjectId: selectedEnvironmentServerConfig?.environment.capabilities.pullRequests
484 - ? (selectedProject?.id ?? null)
485 - : null,
486 - pullRequestRepository: selectedProject?.repositoryIdentity?.displayName ?? null,
487 - projectCwd: composerWorkspaceCwd,
488 - selectedProviderStatus: flow.selectedProviderStatus,
489 - hasThread: false,
490 - hasCompactableConversation: false,
491 - offersUsageLimits: offersUsageLimits,
492 - enabled: isComposerFocused && !isComposerInteractionLocked,
493 - onChangeDraftMessage: flow.setPrompt,
494 - onUpdateInteractionMode: flow.planModeEnabled ? flow.setInteractionMode : undefined,
495 - });
496 - const voiceInput = useVoiceInputController({
497 - ownerKey: flow.draftKey,
498 - label: selectedProjectLabel ? `New task in ${selectedProjectLabel}` : "New task",
499 - readDraftMessage: () => (flow.draftKey ? getComposerDraftSnapshot(flow.draftKey).text : null),
500 - subscribeToDraftChanges: (onChange) => appAtomRegistry.subscribe(composerDraftsAtom, onChange),
501 - selection: composerMenu.selection,
502 - disabled: isIncomingShareTransferPending || isImportingShare || flow.submitting,
503 - onChangeDraftMessage: flow.setPrompt,
504 - onChangeSelection: composerMenu.onSelectionChange,
505 - });
506 - const voicePresentation = resolveVoiceComposerPresentation(
507 - voiceInput.state,
508 - voiceInput.elapsedSeconds,
509 - );
510 - const isVoiceInputPresented = voicePresentation.statusLabel !== null;
329 const preventRemove =
330 (isIncomingShareTransferPending && !isProjectPickerReturnActive) ||
331 isCancellingShareImport ||
332 flow.submitting;
333 usePreventRemove(preventRemove, () => undefined);
516 - useEffect(() => {
517 - if (preventRemove || submitNavigationAction === null) {
518 - return;
519 - }
520 - const frame = requestAnimationFrame(() => {
521 - setSubmitNavigationAction(null);
522 - (navigation.getParent() ?? navigation).dispatch(submitNavigationAction);
523 - });
524 - return () => cancelAnimationFrame(frame);
525 - }, [navigation, preventRemove, submitNavigationAction]);
334 const hasImportedIncomingShare = Boolean(
335 props.incomingShareId &&
336 (consumedIncomingShareId === props.incomingShareId ||
@@ -557,7 +365,7 @@ export function NewTaskDraftScreen(props: {
365 // route, otherwise the transfer guard can swallow the fallback action.
366 const frame = requestAnimationFrame(() => {
367 navigation.dispatch(
560 - StackActions.replace("NewTask", { incomingShareId: props.incomingShareId }),
368 + StackActions.replace("NewTaskProject", { incomingShareId: props.incomingShareId }),
369 );
370 });
371 return () => cancelAnimationFrame(frame);
@@ -606,7 +414,7 @@ export function NewTaskDraftScreen(props: {
414 return;
415 }
416 attemptedDraftIdRef.current = draftId;
609 - navigation.dispatch(StackActions.replace("NewTask"));
417 + navigation.dispatch(CommonActions.navigate("NewTaskProject"));
418 });
419 return () => {
420 cancelled = true;
@@ -623,7 +431,7 @@ export function NewTaskDraftScreen(props: {
431 }
432 attemptedPendingTaskIdRef.current = props.pendingTaskId;
433 if (!beginEditingPendingTask(props.pendingTaskId)) {
626 - navigation.dispatch(StackActions.replace("NewTask"));
434 + navigation.dispatch(CommonActions.navigate("NewTaskProject"));
435 }
436 }, [beginEditingPendingTask, editingPendingTask?.messageId, navigation, props.pendingTaskId]);
437
@@ -635,11 +443,6 @@ export function NewTaskDraftScreen(props: {
443 };
444 }, [props.pendingTaskId, cancelEditingPendingTask]);
445
638 - const theme = useUniwindTheme();
639 - const foregroundColor = theme["--color-foreground"];
640 - const regularFontFamily = FONT_FAMILIES.regular;
641 - const bodyText = useScaledTextRole("body");
642 -
446 const lastInitialProjectRefRef = useRef(props.initialProjectRef);
447
448 useEffect(() => {
@@ -712,7 +515,7 @@ export function NewTaskDraftScreen(props: {
515 return;
516 }
517
715 - navigation.dispatch(StackActions.replace("NewTask"));
518 + navigation.dispatch(CommonActions.navigate("NewTaskProject"));
519 }, [
520 projectScopes,
521 projects,
@@ -999,196 +802,41 @@ export function NewTaskDraftScreen(props: {
802 workspaceMode: flow.workspaceMode,
803 worktreePath: flow.selectedWorktreePath,
804 });
1002 - const showBranchLoading = flow.branchesLoading && flow.availableBranches.length === 0;
805 + const showBranchLoading =
806 + environmentConnected && flow.branchesLoading && flow.availableBranches.length === 0;
807
1004 - async function handlePickMedia(): Promise<void> {
1005 - if (isComposerInteractionLocked || voiceInput.isBusy) {
1006 - return;
1007 - }
1008 - const capabilities = selectedEnvironmentServerConfig?.environment.capabilities;
1009 - const insertion = flow.draftKey ? captureComposerDraftInsertion(flow.draftKey) : undefined;
1010 - const result = await pickComposerMedia({
1011 - existingCount:
1012 - flow.draftKey && insertion
1013 - ? countComposerDraftAttachmentsAfterSelection(flow.draftKey, insertion)
1014 - : flow.attachments.length,
1015 - maxVideoBytes:
1016 - capabilities?.attachmentUploads === true
1017 - ? capabilities.fileAttachments?.maxUploadBytes
1018 - : undefined,
1019 - });
1020 - const rejectedCount =
1021 - result.attachments.length > 0 ? flow.appendAttachments(result.attachments, insertion) : 0;
1022 - const problems = [
1023 - ...(result.error ? [result.error] : []),
1024 - ...(rejectedCount > 0
1025 - ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`]
1026 - : []),
1027 - ];
1028 - if (problems.length > 0) {
1029 - Dialog.alert("Could not attach photo or video", problems.join("\n\n"));
1030 - }
1031 - }
1032 -
1033 - async function handlePickFiles(): Promise<void> {
1034 - if (isComposerInteractionLocked || voiceInput.isBusy) {
1035 - return;
1036 - }
1037 - const maxBytes =
1038 - selectedEnvironmentServerConfig?.environment.capabilities.fileAttachments?.maxUploadBytes;
1039 - if (maxBytes === undefined) {
1040 - Dialog.alert("File attachments are not available on this server.");
1041 - return;
1042 - }
1043 - const insertion = flow.draftKey ? captureComposerDraftInsertion(flow.draftKey) : undefined;
1044 - const result = await pickComposerFiles({
1045 - existingCount:
1046 - flow.draftKey && insertion
1047 - ? countComposerDraftAttachmentsAfterSelection(flow.draftKey, insertion)
1048 - : flow.attachments.length,
1049 - maxBytes,
1050 - });
1051 - const rejectedCount =
1052 - result.files.length > 0 ? flow.appendAttachments(result.files, insertion) : 0;
1053 - const problems = [
1054 - ...(result.error ? [result.error] : []),
1055 - ...(rejectedCount > 0
1056 - ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`]
1057 - : []),
1058 - ];
1059 - if (problems.length > 0) {
1060 - Dialog.alert("Could not attach file", problems.join("\n\n"));
1061 - }
1062 - }
1063 -
1064 - const handleNativePasteImages = async (uris: ReadonlyArray<string>) => {
1065 - const insertion = flow.draftKey ? captureComposerDraftInsertion(flow.draftKey) : undefined;
1066 - const existingCount =
1067 - flow.draftKey && insertion
1068 - ? countComposerDraftAttachmentsAfterSelection(flow.draftKey, insertion)
1069 - : flow.attachments.length;
1070 - const converted = await settlePromise(() =>
1071 - convertPastedImagesToAttachments({ uris, existingCount }),
1072 - );
1073 - if (AsyncResult.isFailure(converted)) {
1074 - console.error("[native paste] error converting images", squashAtomCommandFailure(converted));
1075 - return;
1076 - }
1077 - if (converted.value.length > 0) flow.appendAttachments(converted.value, insertion);
1078 - };
808 + const {
809 + onPickDraftMedia: handlePickMedia,
810 + onPickDraftFiles: handlePickFiles,
811 + onNativePasteImages: handleNativePasteImages,
812 + onNativePasteText: handleNativePasteText,
813 + } = useComposerAttachmentActions({
814 + draftKey: flow.draftKey,
815 + serverConfig: selectedEnvironmentServerConfig,
816 + locked: isComposerInteractionLocked,
817 + });
818
1080 - const handleNativePasteText = async (paste: ComposerTextPaste) => {
819 + async function handleStart(): Promise<import("@t3tools/contracts").MessageId | null> {
820 + const selectedProject = flow.selectedProject;
821 const draftKey = flow.draftKey;
1082 - if (!draftKey) return;
1083 - const insertion = { text: paste.value, ...paste.selection };
1084 - const insertPaste = () => {
1085 - const insertion = replaceTextSelection({
1086 - value: paste.value,
1087 - selection: paste.selection,
1088 - text: paste.text,
1089 - });
1090 - const selection = { start: insertion.cursor, end: insertion.cursor };
1091 - flow.setPrompt(insertion.value);
1092 - composerMenu.onSelectionChange(selection);
1093 - };
1094 - const capabilities = selectedEnvironmentServerConfig?.environment.capabilities;
1095 - const advertisedMax =
1096 - capabilities?.attachmentUploads === true
1097 - ? capabilities.fileAttachments?.maxUploadBytes
1098 - : undefined;
1099 - const maxBytes =
1100 - advertisedMax === undefined ? null : clampFileAttachmentUploadBytes(advertisedMax);
1101 - const wouldExceedInputLimit =
1102 - paste.value.length -
1103 - Math.max(0, paste.selection.end - paste.selection.start) +
1104 - paste.text.length >
1105 - PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
1106 - const canAttach =
1107 - maxBytes !== null &&
1108 - countComposerDraftAttachmentsAfterSelection(draftKey, insertion) <
1109 - PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
1110 - new TextEncoder().encode(paste.text).byteLength <= maxBytes;
822 if (
1112 - pastedTextDisposition({
1113 - text: paste.text,
1114 - wouldExceedInputLimit,
1115 - canAttach: true,
1116 - }) === "attachment"
823 + !selectedProject ||
824 + !draftKey ||
825 + cloneBlocksStart ||
826 + !isIncomingShareReady ||
827 + isImportingShare ||
828 + isComposerInteractionLocked
829 ) {
1118 - if (canAttach && maxBytes !== null) {
1119 - pendingPastedTextAttachmentCountRef.current += 1;
1120 - setPendingPastedTextAttachmentCount(pendingPastedTextAttachmentCountRef.current);
1121 - const attached = await settlePromise(async () => {
1122 - if (pastedTextFileNamesRef.current.draftKey !== draftKey) {
1123 - pastedTextFileNamesRef.current = { draftKey, names: new Set() };
1124 - }
1125 - const reservedNames = pastedTextFileNamesRef.current.names;
1126 - for (const attachment of flow.attachments) reservedNames.add(attachment.name);
1127 - const name = nextPastedTextFileName([...reservedNames]);
1128 - reservedNames.add(name);
1129 - const attachment = await createPastedTextComposerAttachment({
1130 - text: paste.text,
1131 - name,
1132 - maxBytes,
1133 - });
1134 - if (latestDraftKeyRef.current !== draftKey) {
1135 - await removePersistedComposerAttachmentFile(attachment.fileUri);
1136 - return;
1137 - }
1138 - if (flow.appendAttachments([attachment], insertion) > 0) {
1139 - await removePersistedComposerAttachmentFile(attachment.fileUri);
1140 - Dialog.alert(
1141 - "Could not attach pasted text",
1142 - `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
1143 - );
1144 - }
1145 - });
1146 - pendingPastedTextAttachmentCountRef.current = Math.max(
1147 - 0,
1148 - pendingPastedTextAttachmentCountRef.current - 1,
1149 - );
1150 - setPendingPastedTextAttachmentCount(pendingPastedTextAttachmentCountRef.current);
1151 - if (AsyncResult.isFailure(attached)) {
1152 - const error = squashAtomCommandFailure(attached);
1153 - Dialog.alert(
1154 - "Could not attach pasted text",
1155 - error instanceof Error ? error.message : "Try again.",
1156 - );
1157 - }
1158 - return;
1159 - } else if (!wouldExceedInputLimit) {
1160 - insertPaste();
1161 - } else {
1162 - Dialog.alert(
1163 - wouldExceedInputLimit
1164 - ? "Pasted text is too large for this message"
1165 - : "Could not attach pasted text",
1166 - wouldExceedInputLimit
1167 - ? "Remove some text or an attachment, then paste again."
1168 - : "Remove an attachment or use a smaller paste, then try again.",
1169 - );
1170 - }
1171 - return;
1172 - }
1173 -
1174 - insertPaste();
1175 - };
1176 -
1177 - async function handleStart(): Promise<void> {
1178 - if (voiceInput.blocksSubmission || pendingPastedTextAttachmentCountRef.current > 0) return;
1179 - const selectedProject = flow.selectedProject;
1180 - const draftKey = flow.draftKey;
1181 - if (!selectedProject || !draftKey) {
1182 - return;
830 + return null;
831 }
832 if (
833 environmentConnected &&
834 !readEnvironmentScope(selectedProject.environmentId, AuthOrchestrationOperateScope)
835 ) {
1188 - return;
836 + return null;
837 }
838 const draft = getComposerDraftSnapshot(draftKey);
1191 - if (appAtomRegistry.get(composerContextImportsAtom)[draftKey]) return;
839 + if (appAtomRegistry.get(composerContextImportsAtom)[draftKey]) return null;
840 const modelSelection =
841 resolveSelectableModelSelection(
842 selectedEnvironmentServerConfig,
@@ -1215,7 +863,7 @@ export function NewTaskDraftScreen(props: {
863 flow.submitting ||
864 (workspaceMode === "worktree" && !selectedBranchName)
865 ) {
1218 - return;
866 + return null;
867 }
868 if (
869 environmentConnected &&
@@ -1231,21 +879,7 @@ export function NewTaskDraftScreen(props: {
879 selectedProject.id,
880 );
881 Dialog.alert(title, detail);
1234 - return;
1235 - }
1236 - // T3's own limits command is answered by the thread composer; a new task would
1237 - // send it to the agent. A provider's same-named command, or a prompt carrying
1238 - // attachments, goes through as usual.
1239 - if (
1240 - offersUsageLimits &&
1241 - isUsageLimitsCommand(initialMessageText) &&
1242 - draft.attachments.length === 0
1243 - ) {
1244 - Dialog.alert(
1245 - "Usage limits",
1246 - "Send /usage-limits inside a thread, or open Settings → Usage → Limits.",
1247 - );
1248 - return;
882 + return null;
883 }
884 // A failed-send restore can leave the draft over the cap on purpose (it
885 // never drops the user's files); starting anyway would upload everything
@@ -1255,13 +889,13 @@ export function NewTaskDraftScreen(props: {
889 "Too many attachments",
890 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
891 );
1258 - return;
892 + return null;
893 }
894
895 const contextBlockReason = composerContextSendBlockReason(draft.context);
896 if (contextBlockReason) {
897 Dialog.alert("Too much context", contextBlockReason);
1264 - return;
898 + return null;
899 }
900 const strandedThread = threadContextsOutsideEnvironment({
901 text: draft.text,
@@ -1277,7 +911,7 @@ export function NewTaskDraftScreen(props: {
911 "Attached thread unavailable",
912 `"${strandedThread.title}" is on another machine. Switch back to ${owner} or remove it from the draft.`,
913 );
1280 - return;
914 + return null;
915 }
916
917 const editingPendingTask = flow.editingPendingTask;
@@ -1289,26 +923,12 @@ export function NewTaskDraftScreen(props: {
923 messageId: editingPendingTask.messageId,
924 createdAt: editingPendingTask.createdAt,
925 }
1292 - : makeTurnCommandMetadata();
926 + : creationMetadata;
927 const message = flow.buildPendingTaskMessage(metadata, {
928 currentCheckoutBranch: queuesInsteadOfStarting ? null : flow.currentCheckoutBranchName,
929 });
930 if (!message) {
1297 - return;
1298 - }
1299 - if (!queuesInsteadOfStarting) {
1300 - // Arm the lock-screen card before the async thread creation: backgrounding
1301 - // the app right after tapping submit would otherwise reject the foreground
1302 - // -only Activity start. If creation fails, the token registration's replay
1303 - // finds no work and ends the card within seconds.
1304 - armAgentAwarenessLiveActivityForLocalWork({
1305 - environmentId: selectedProject.environmentId,
1306 - threadTitle: deriveThreadTitleSeed({
1307 - text: initialMessageText,
1308 - attachments: draft.attachments,
1309 - }),
1310 - projectTitle: selectedProject.title,
1311 - });
931 + return null;
932 }
933 // Persist before clearing the draft or leaving its editor. This only waits
934 // for the local outbox write; server and worktree setup run on the thread.
@@ -1321,8 +941,14 @@ export function NewTaskDraftScreen(props: {
941 "Could not queue task",
942 error instanceof Error ? error.message : "The task could not be saved to the outbox.",
943 );
1324 - return;
944 + return null;
945 }
946 + promptInputRef.current?.blur();
947 + navigation.dispatch(
948 + CommonActions.setParams(
949 + submittedThreadParams(String(message.environmentId), String(message.threadId)),
950 + ),
951 + );
952 const draftSnapshot = getComposerDraftSnapshot(draftKey);
953 if (editingPendingTask) {
954 flow.finishEditingPendingTask();
@@ -1335,137 +961,31 @@ export function NewTaskDraftScreen(props: {
961 deferAttachmentCleanup: true,
962 });
963 }
1338 - setSubmitNavigationAction(
1339 - queuesInsteadOfStarting
1340 - ? CommonActions.goBack()
1341 - : StackActions.replace("Thread", {
1342 - environmentId: String(message.environmentId),
1343 - threadId: String(message.threadId),
1344 - }),
1345 - );
964 scheduleUnusedComposerAttachmentCleanup(draftSnapshot.attachments);
965 + return message.messageId;
966 }
967
1349 - if (!selectedProject) {
1350 - return (
1351 - <View className="flex-1 bg-sheet" collapsable={false}>
1352 - {Platform.OS === "android" ? (
1353 - <>
1354 - <NativeStackScreenOptions options={{ headerShown: false }} />
1355 - <AndroidScreenHeader
1356 - title="New thread"
1357 - hideBottomBorder
1358 - onBack={() => navigation.goBack()}
1359 - />
1360 - </>
1361 - ) : (
1362 - <NativeStackScreenOptions options={{ title: "Loading task" }} />
1363 - )}
1364 - </View>
1365 - );
1366 - }
1367 -
1368 - const isAndroid = Platform.OS === "android";
1369 - const canStart =
1370 - !isImportingContext &&
1371 - !cloneBlocksStart &&
1372 - taskPermissionReason === null &&
1373 - attachmentBlockReason === null &&
1374 - !modelUnavailable &&
1375 - Boolean(flow.selectedProject) &&
1376 - Boolean(flow.selectedModel) &&
1377 - (flow.prompt.trim().length > 0 || flow.attachments.length > 0) &&
1378 - isIncomingShareReady &&
1379 - !isImportingShare &&
1380 - !flow.submitting &&
1381 - pendingPastedTextAttachmentCount === 0 &&
1382 - !voiceInput.blocksSubmission &&
1383 - // Until the repository check answers, a saved worktree selection may belong to a non-git folder.
1384 - !(flow.workspaceMode === "worktree" && (!flow.selectedBranchName || !flow.isGitRepoKnown));
1385 - const openDraftDocument = (attachment: ComposerDocumentAttachment) => {
1386 - // A draft attachment lives only in the draft. Without its key the screen would fall through
1387 - // to a remote lookup for bytes the server has never seen.
1388 - const draftKey = flow.draftKey;
1389 - if (!draftKey) return;
1390 - promptInputRef.current?.blur();
1391 - void KeyboardController.dismiss({ animated: true });
1392 - navigation.dispatch(
1393 - StackActions.push("NewTaskAttachment", {
1394 - environmentId: String(selectedProject.environmentId),
1395 - attachmentId: attachment.attachmentId,
1396 - name: attachment.name,
1397 - mimeType: attachment.mimeType,
1398 - sizeBytes: String(attachment.sizeBytes),
1399 - draftKey,
1400 - }),
1401 - );
1402 - };
1403 - const promptEditor = (
1404 - <>
1405 - <ComposerEditor
1406 - draftKey={flow.draftKey}
1407 - environmentId={selectedProject.environmentId}
1408 - onOpenAttachment={openDraftDocument}
1409 - onOpenMention={(path) => {
1410 - if (!composerWorkspaceCwd) return;
1411 - promptInputRef.current?.blur();
1412 - void KeyboardController.dismiss({ animated: true });
1413 - navigation.dispatch(
1414 - StackActions.push("NewTaskFile", {
1415 - environmentId: String(selectedProject.environmentId),
1416 - cwd: composerWorkspaceCwd,
1417 - projectName: selectedProject.title,
1418 - path: fileRoutePathSegments(path),
1419 - }),
1420 - );
1421 - }}
1422 - ref={promptInputRef}
1423 - autoFocus={false}
1424 - editable={!isIncomingShareTransferPending && !flow.submitting}
1425 - readOnly={voiceInput.freezesEditor}
1426 - multiline
1427 - scrollEnabled
1428 - value={flow.prompt}
1429 - skills={composerMenu.skills}
1430 - selection={composerMenu.selection}
1431 - onChangeText={flow.setPrompt}
1432 - onSubmit={() => {
1433 - if (canStart) void handleStart();
1434 - }}
1435 - onSelectionChange={composerMenu.onSelectionChange}
1436 - onFocus={() => setIsComposerFocused(true)}
1437 - onBlur={() => setIsComposerFocused(false)}
1438 - onPasteImages={(uris) => void handleNativePasteImages(uris)}
1439 - onPasteText={(paste) => void handleNativePasteText(paste)}
1440 - placeholder="Ask anything…"
1441 - singleLineCentered={false}
1442 - contentInsetVertical={0}
1443 - style={{
1444 - minHeight: 72,
1445 - maxHeight: 160,
1446 - paddingVertical: 4,
1447 - }}
1448 - textStyle={{ ...bodyText, color: foregroundColor, fontFamily: regularFontFamily }}
1449 - />
1450 - </>
1451 - );
968 + // Keep the current surface until the local draft selection is ready. Publishing
969 + // an empty loading surface here flashes between two already-cached threads.
970 + if (!selectedProject) return null;
971
1453 - const closeNewTask = () => {
1454 - void KeyboardController.dismiss({ animated: true });
1455 - const parentNavigation = navigation.getParent();
1456 - if (parentNavigation) {
1457 - parentNavigation.goBack();
1458 - return;
1459 - }
1460 - navigation.goBack();
1461 - };
972 + const setupBlockReason =
973 + isIncomingShareReady && !isImportingShare
974 + ? cloneBlocksStart
975 + ? "Wait for the project clone to finish."
976 + : flow.submitting
977 + ? "Starting the thread…"
978 + : flow.workspaceMode === "worktree" && (!flow.selectedBranchName || !flow.isGitRepoKnown)
979 + ? "Choose a base branch before creating a worktree."
980 + : null
981 + : "Wait for shared content to finish importing.";
982 const chooseProject = () => {
983 if (isComposerInteractionLocked) {
984 return;
985 }
986 promptInputRef.current?.blur();
987 void KeyboardController.dismiss({ animated: true });
1468 - navigation.dispatch(StackActions.push("NewTask", { incomingShareId: props.incomingShareId }));
988 + navigation.navigate("NewTaskProject", { incomingShareId: props.incomingShareId });
989 };
990 const openContextPicker = (routeName: "NewTaskBranch" | "NewTaskEnvironment") => {
991 if (isComposerInteractionLocked) {
@@ -1473,28 +993,16 @@ export function NewTaskDraftScreen(props: {
993 }
994 promptInputRef.current?.blur();
995 void KeyboardController.dismiss({ animated: true });
1476 - navigation.dispatch(StackActions.push(routeName));
996 + navigation.navigate(routeName);
997 };
998
999 const environmentControl = (
1480 - <ComposerInlineControl
1481 - accessibilityLabel={`Environment: ${selectedEnvironmentLabel}`}
1482 - chevronDirection="right"
1483 - disabled={isComposerInteractionLocked || voiceInput.isBusy}
1484 - renderIcon={(size) => (
1485 - <EnvironmentMachineSymbol
1486 - kind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}
1487 - size={size}
1488 - tintColorClassName="accent-icon-muted"
1489 - />
1490 - )}
1491 - label={`on ${selectedEnvironmentLabel}`}
1492 - maxWidth={flow.isScratchDraft ? 170 : 260}
1493 - onPress={
1494 - flow.environments.length > 1 ? () => openContextPicker("NewTaskEnvironment") : undefined
1495 - }
1496 - showChevron={flow.environments.length > 1}
1497 - static={flow.environments.length <= 1}
1000 + <DraftEnvironmentControl
1001 + connectionState={connectionState}
1002 + label={selectedEnvironmentLabel}
1003 + machineKind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}
1004 + disabled={isComposerInteractionLocked}
1005 + onChooseEnvironment={() => openContextPicker("NewTaskEnvironment")}
1006 />
1007 );
1008 const hero = flow.isScratchDraft ? (
@@ -1545,30 +1053,49 @@ export function NewTaskDraftScreen(props: {
1053 {environmentControl}
1054 </View>
1055 );
1548 - const heroViewport = (
1549 - <View className="flex-1" collapsable={false}>
1550 - <ScrollView
1551 - alwaysBounceVertical={isKeyboardVisible}
1552 - className="flex-1"
1553 - contentInsetAdjustmentBehavior="automatic"
1554 - contentContainerClassName="grow items-center pb-[236px] pt-12"
1555 - keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
1556 - keyboardShouldPersistTaps="handled"
1557 - showsVerticalScrollIndicator={false}
1558 - style={{ flex: 1 }}
1559 - testID="new-task-hero-scroll"
1056 + // The nested hero scroll view does not receive UIKit's automatic navigation inset in split columns.
1057 + const heroViewport = (headerInset: number, bottomInset: number, availableHeight: number) =>
1058 + availableHeight < 180 ? null : (
1059 + <NativeScrollEdgeEffectsContext
1060 + value={{ top: "hidden", bottom: "hidden", left: "hidden", right: "hidden" }}
1061 >
1561 - {hero}
1562 - </ScrollView>
1563 - </View>
1564 - );
1062 + <View
1063 + collapsable={false}
1064 + style={{
1065 + position: "absolute",
1066 + top: headerInset,
1067 + bottom: bottomInset,
1068 + left: 0,
1069 + right: 0,
1070 + overflow: "hidden",
1071 + }}
1072 + >
1073 + <ScrollView
1074 + alwaysBounceVertical={false}
1075 + className="flex-1"
1076 + contentInsetAdjustmentBehavior="never"
1077 + contentContainerClassName="grow items-center"
1078 + contentContainerStyle={{ paddingVertical: 24 }}
1079 + keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
1080 + keyboardShouldPersistTaps="handled"
1081 + showsVerticalScrollIndicator={false}
1082 + style={{ flex: 1 }}
1083 + testID="new-task-hero-scroll"
1084 + >
1085 + <View style={{ flexGrow: 1 }} />
1086 + {hero}
1087 + <View style={{ flexGrow: 2 }} />
1088 + </ScrollView>
1089 + </View>
1090 + </NativeScrollEdgeEffectsContext>
1091 + );
1092
1093 const workspaceControls = (
1094 <View className="flex-row items-center gap-1 px-2">
1095 <ComposerInlineControl
1096 accessibilityHint={`Switches to ${flow.workspaceMode === "local" ? "a new worktree" : "the current checkout"}`}
1097 accessibilityLabel={workspaceLabel}
1571 - disabled={isComposerInteractionLocked || voiceInput.isBusy || !flow.isGitRepo}
1098 + disabled={isComposerInteractionLocked || !flow.isGitRepo}
1099 renderIcon={(size) => (
1100 <NewTaskWorkspaceIcon
1101 workspaceMode={flow.workspaceMode}
@@ -1594,280 +1121,151 @@ export function NewTaskDraftScreen(props: {
1121 </View>
1122 );
1123
1597 - const composerPopover = composerMenu.trigger ? (
1598 - <ComposerCommandPopover
1599 - items={composerMenu.items}
1600 - triggerKind={composerMenu.trigger.kind}
1601 - isLoading={composerMenu.isLoading}
1602 - error={composerMenu.error}
1603 - onSelect={composerMenu.onSelect}
1604 - />
1605 - ) : null;
1606 - const composerDock = (
1607 - <View
1608 - className={
1609 - Platform.OS === "android" ? "bg-sheet-solid px-[12px] pt-1" : "bg-sheet px-[12px] pt-1"
1610 - }
1611 - style={{ paddingBottom: controlsBottomPadding }}
1612 - >
1613 - {!voiceInput.isBusy &&
1614 - composerMenu.trigger &&
1615 - (composerMenu.items.length > 0 || composerMenu.trigger.kind === "pull-request") ? (
1616 - Platform.OS === "ios" ? (
1617 - <View>
1618 - <ComposerPopoverAnchor>
1619 - <Animated.View entering={COMPOSER_POPOVER_ENTERING}>{composerPopover}</Animated.View>
1620 - </ComposerPopoverAnchor>
1621 - </View>
1622 - ) : (
1623 - <View className="mb-2">{composerPopover}</View>
1624 - )
1625 - ) : null}
1626 - {projectClone && projectClone.phase !== "done" && selectedProject ? (
1627 - <View className="px-1 pb-2">
1628 - <ProjectCloneBanner
1629 - clone={projectClone}
1630 - onCancel={() =>
1631 - void runCloneAction("Failed to cancel clone", () =>
1632 - cancelProjectClone({
1633 - environmentId: selectedProject.environmentId,
1634 - input: { projectId: selectedProject.id },
1635 - }),
1636 - )
1637 - }
1638 - onRetry={() =>
1639 - void runCloneAction("Failed to retry clone", () =>
1640 - retryProjectClone({
1641 - environmentId: selectedProject.environmentId,
1642 - input: { projectId: selectedProject.id },
1643 - }),
1644 - )
1645 - }
1646 - onRemove={() => void removeClonedProject()}
1647 - />
1648 - </View>
1649 - ) : null}
1650 - {flow.canChooseWorkspace ? <View className="pb-1">{workspaceControls}</View> : null}
1651 -
1652 - {taskPermissionReason ? (
1653 - <Text className="px-3 py-2 text-xs text-muted-foreground">{taskPermissionReason}</Text>
1654 - ) : null}
1655 -
1656 - {modelUnavailable ? (
1657 - <Button
1658 - label="Model unavailable. Open model settings."
1659 - tone="text"
1660 - disabled={isComposerInteractionLocked}
1661 - onPress={settingsSheetPresentation.open}
1662 - />
1663 - ) : null}
1664 -
1665 - <ComposerSurface
1666 - style={{
1667 - borderRadius: 26,
1668 - minHeight: 140,
1669 - overflow: "hidden",
1670 - paddingBottom: 6,
1671 - paddingTop: 14,
1672 - }}
1673 - >
1674 - {stripAttachments.length > 0 ? (
1675 - <View className="px-[14px] pb-2.5">
1676 - <ComposerAttachmentStrip
1677 - environmentId={selectedProject.environmentId}
1678 - attachments={stripAttachments}
1679 - imageBorderRadius={16}
1680 - imageSize={72}
1681 - onRemove={
1682 - isComposerInteractionLocked || voiceInput.isBusy
1683 - ? () => undefined
1684 - : flow.removeAttachment
1685 - }
1686 - onPressPreview={
1687 - isComposerInteractionLocked || voiceInput.isBusy ? undefined : openFilePreview
1688 - }
1689 - onPressVideo={
1690 - isComposerInteractionLocked || voiceInput.isBusy ? undefined : openVideoPreview
1691 - }
1692 - onPressDocument={
1693 - isComposerInteractionLocked || voiceInput.isBusy
1694 - ? undefined
1695 - : (attachment) =>
1696 - openDraftDocument({
1697 - attachmentId: attachment.id,
1698 - name: attachment.name,
1699 - mimeType: attachment.mimeType,
1700 - sizeBytes: attachment.sizeBytes,
1701 - })
1702 - }
1703 - />
1704 - </View>
1705 - ) : null}
1706 -
1707 - <View className="px-[14px]">{promptEditor}</View>
1708 - <View className="h-1" />
1709 -
1710 - <Animated.View layout={COMPOSER_LAYOUT_TRANSITION} collapsable={false}>
1711 - <ComposerDictationToolbar showsDictation={isVoiceInputPresented}>
1712 - <ComposerToolbarRow
1713 - paddingBottom={0}
1714 - paddingHorizontal={0}
1715 - paddingTop={0}
1716 - style={{ gap: 0 }}
1717 - >
1718 - <ComposerDictationCancelAction
1719 - presentation={voicePresentation}
1720 - onCancel={voiceInput.cancel}
1721 - />
1722 - {isVoiceInputPresented ? (
1723 - <ComposerDictationStatus
1724 - audioLevels={voiceInput.audioLevels}
1725 - elapsedSeconds={voiceInput.elapsedSeconds}
1726 - phase={voiceInput.state.phase}
1727 - presentation={voicePresentation}
1728 - onDismissError={voiceInput.cancel}
1729 - />
1730 - ) : (
1731 - <>
1732 - <ComposerAttachmentButton
1733 - disabled={isComposerInteractionLocked}
1734 - supportsFiles={Boolean(
1735 - selectedEnvironmentServerConfig?.environment.capabilities.fileAttachments,
1736 - )}
1737 - onPickMedia={handlePickMedia}
1738 - onPickFiles={handlePickFiles}
1739 - />
1740 - <View className="min-w-0 flex-1 flex-row items-center justify-end gap-2">
1741 - <View className="min-w-0 shrink">
1742 - <ComposerModelControl
1743 - modelOption={flow.selectedModelOption}
1744 - selection={flow.selectedModel}
1745 - provider={flow.selectedProviderStatus?.driver}
1746 - prompt={flow.prompt}
1747 - surfaceColor={theme["--color-composer-panel"]}
1748 - disabled={isComposerInteractionLocked}
1749 - onPress={settingsSheetPresentation.open}
1750 - />
1751 - </View>
1752 - {flow.planModeEnabled ? (
1753 - <ComposerInlineControl
1754 - accessibilityHint={`Switches to ${flow.interactionMode === "plan" ? "Build" : "Plan"} mode`}
1755 - accessibilityLabel={`Interaction mode: ${flow.interactionMode === "plan" ? "Plan" : "Build"}`}
1756 - disabled={isComposerInteractionLocked}
1757 - emphasized
1758 - icon={
1759 - flow.interactionMode === "plan"
1760 - ? { ios: "list.bullet.clipboard", android: "auto_awesome" }
1761 - : { ios: "hammer", android: "construction" }
1762 - }
1763 - label={flow.interactionMode === "plan" ? "Plan" : "Build"}
1764 - onPress={() =>
1765 - flow.setInteractionMode(
1766 - flow.interactionMode === "plan" ? "default" : "plan",
1767 - )
1768 - }
1769 - showChevron={false}
1770 - />
1771 - ) : null}
1772 - </View>
1773 - </>
1774 - )}
1775 - <ComposerDictationPrimaryAction
1776 - state={voiceInput.state}
1777 - presentation={voicePresentation}
1778 - isAvailable={voiceInput.isAvailable}
1779 - disabled={isIncomingShareTransferPending || isImportingShare || flow.submitting}
1780 - onStart={voiceInput.start}
1781 - onConfirm={voiceInput.stop}
1782 - onCancel={voiceInput.cancel}
1783 - />
1784 - {voicePresentation.showsSend ? (
1785 - <ComposerActionButton
1786 - accessibilityLabel={
1787 - taskPermissionReason ??
1788 - attachmentBlockReason ??
1789 - (cloneBlocksStart
1790 - ? projectClone === null || projectClone.phase === "running"
1791 - ? "Cloning repository"
1792 - : "Repository not cloned"
1793 - : pendingPastedTextAttachmentCount > 0
1794 - ? "Attaching pasted text"
1795 - : flow.submitting
1796 - ? "Starting task"
1797 - : attachmentsUploading
1798 - ? "Queue task, sends when uploads finish"
1799 - : environmentConnected
1800 - ? "Start task"
1801 - : "Queue task")
1802 - }
1803 - disabled={!canStart}
1804 - icon={queuesInsteadOfStarting ? "tray.and.arrow.up" : "arrow.up"}
1805 - onPress={() => void handleStart()}
1806 - variant="primary"
1807 - />
1808 - ) : null}
1809 - </ComposerToolbarRow>
1810 - </ComposerDictationToolbar>
1811 - </Animated.View>
1812 - </ComposerSurface>
1813 - <VideoPreviewModal source={previewVideo} onRequestClose={closeMediaPreview} />
1814 - <FilePreviewModal source={previewFile} onRequestClose={closeMediaPreview} />
1815 - </View>
1816 - );
1817 -
1818 - if (isAndroid) {
1124 + if (!flow.selectedModel) {
1125 return (
1820 - <View className="flex-1 bg-sheet" collapsable={false}>
1821 - <NativeStackScreenOptions options={{ headerShown: false }} />
1822 - <SheetHeader
1126 + <ThreadScreenFallback>
1127 + <AppBar
1128 title="New thread"
1824 - onCancel={closeNewTask}
1825 - accessibilityLabel="Cancel new task"
1129 + sidebar={false}
1130 + onBack={goBack}
1131 + options={{
1132 + ...threadHeaderAppearance(NATIVE_LIQUID_GLASS_SUPPORTED),
1133 + unstable_headerSubtitle: undefined,
1134 + unstable_headerRightItems: () => [],
1135 + unstable_headerToolbarItems: () => [],
1136 + }}
1137 />
1827 - <ScreenContent>
1828 - {heroViewport}
1829 -
1830 - <KeyboardStickyView
1831 - style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
1832 - offset={{ closed: 0, opened: keyboardOpenedOffset }}
1833 - >
1834 - {composerDock}
1835 - </KeyboardStickyView>
1836 - </ScreenContent>
1837 - </View>
1138 + <View className="flex-1 justify-end gap-3 p-4">
1139 + {environmentControl}
1140 + <Text className="text-foreground-muted">
1141 + Your draft is saved on this device. Connect to an environment to choose its first model.
1142 + </Text>
1143 + <ComposerEditor
1144 + draftKey={flow.draftKey}
1145 + value={flow.prompt}
1146 + onChangeText={flow.setPrompt}
1147 + placeholder="Ask the repo agent, or run a command…"
1148 + multiline
1149 + style={{ minHeight: 64 }}
1150 + />
1151 + </View>
1152 + </ThreadScreenFallback>
1153 );
1154 }
1840 -
1155 + const thread = draftThreadShell({
1156 + environmentId: selectedProject.environmentId,
1157 + projectId: selectedProject.id,
1158 + threadId: ThreadId.make(flow.editingPendingTask?.threadId ?? creationMetadata.threadId),
1159 + modelSelection: flow.selectedModel,
1160 + runtimeMode: flow.runtimeMode,
1161 + interactionMode: flow.interactionMode,
1162 + branch: flow.selectedBranchName,
1163 + worktreePath: flow.selectedWorktreePath,
1164 + createdAt: creationMetadata.createdAt,
1165 + });
1166 return (
1842 - <View className="flex-1 bg-sheet" collapsable={false}>
1843 - <NativeStackScreenOptions
1844 - options={{
1845 - headerBackVisible: false,
1846 - headerShadowVisible: false,
1847 - title: "New thread",
1848 - unstable_navigationItemStyle: "editor",
1167 + <>
1168 + <ThreadScreenBinding
1169 + environmentId={selectedProject.environmentId}
1170 + header={
1171 + <DraftThreadHeader thread={thread} project={selectedProject} cwd={composerWorkspaceCwd} />
1172 + }
1173 + draftMode={{
1174 + content: heroViewport,
1175 + controls: (
1176 + <View className="px-3 pb-1">
1177 + {projectClone && projectClone.phase !== "done" && selectedProject ? (
1178 + <View className="px-1 pb-2">
1179 + <ProjectCloneBanner
1180 + clone={projectClone}
1181 + onCancel={() =>
1182 + void runCloneAction("Failed to cancel clone", () =>
1183 + cancelProjectClone({
1184 + environmentId: selectedProject.environmentId,
1185 + input: { projectId: selectedProject.id },
1186 + }),
1187 + )
1188 + }
1189 + onRetry={() =>
1190 + void runCloneAction("Failed to retry clone", () =>
1191 + retryProjectClone({
1192 + environmentId: selectedProject.environmentId,
1193 + input: { projectId: selectedProject.id },
1194 + }),
1195 + )
1196 + }
1197 + onRemove={() => void removeClonedProject()}
1198 + />
1199 + </View>
1200 + ) : null}
1201 + {flow.canChooseWorkspace ? workspaceControls : null}
1202 + </View>
1203 + ),
1204 + editorRef: promptInputRef,
1205 + sendBlockedReason: setupBlockReason,
1206 + interactionLocked: isComposerInteractionLocked,
1207 }}
1208 + canOperateThread={canOperate}
1209 + selectedThread={thread}
1210 + selectedThreadDetailRef={null}
1211 + contentPresentation={{ kind: "ready" }}
1212 + screenTone={connectionTone(connectionState)}
1213 + connectionError={environmentRuntime?.connectionError ?? null}
1214 + environmentLabel={selectedEnvironmentLabel}
1215 + feedbackSubmissions={[]}
1216 + onDismissFeedback={() => {}}
1217 + selectedThreadFeed={[]}
1218 + activityRun={null}
1219 + activeWorkStartedAt={null}
1220 + isCompacting={false}
1221 + creationState={null}
1222 + activePendingApproval={null}
1223 + activePendingApprovals={[]}
1224 + respondingApprovalId={null}
1225 + activePendingUserInput={null}
1226 + activePendingUserInputDrafts={{}}
1227 + activePendingUserInputAnswers={null}
1228 + respondingUserInputId={null}
1229 + connectionStateLabel={connectionState}
1230 + activeThreadBusy={false}
1231 + canStopThread={false}
1232 + queuedRunEdit={null}
1233 + composerDraftKey={flow.draftKey}
1234 + followUpBehavior="queue"
1235 + canSteerActiveTurn={false}
1236 + isSavingQueuedEdit={false}
1237 + onCancelQueuedRunEdit={() => {}}
1238 + onRemoveQueuedEditAttachment={() => {}}
1239 + projectWorkspaceRoot={selectedProject.workspaceRoot}
1240 + threadCwd={composerWorkspaceCwd}
1241 + selectedThreadQueueCount={0}
1242 + queuedMessages={[]}
1243 + dispatchingMessageId={null}
1244 + serverConfig={selectedEnvironmentServerConfig}
1245 + usesAutomaticContentInsets
1246 + onOpenConnectionEditor={() => navigation.navigate("Connections")}
1247 + onChangeDraftMessage={flow.setPrompt}
1248 + onPickDraftMedia={handlePickMedia}
1249 + onPickDraftFiles={handlePickFiles}
1250 + onNativePasteImages={handleNativePasteImages}
1251 + onNativePasteText={handleNativePasteText}
1252 + onRemoveDraftImage={flow.removeAttachment}
1253 + onStopThread={() => {}}
1254 + onResumeQueue={null}
1255 + onSendMessage={handleStart}
1256 + onReconnectEnvironment={() => onReconnectEnvironment(selectedProject.environmentId)}
1257 + canSwitchThreadProvider
1258 + onUpdateThreadModelSelection={(selection) =>
1259 + flow.setSelectedModelKey(`${selection.instanceId}:${selection.model}`, selection.options)
1260 + }
1261 + onUpdateThreadRuntimeMode={flow.setRuntimeMode}
1262 + onUpdateThreadInteractionMode={flow.planModeEnabled ? flow.setInteractionMode : undefined}
1263 + onRespondToApproval={async () => {}}
1264 + onSelectUserInputOption={() => {}}
1265 + onChangeUserInputCustomAnswer={() => {}}
1266 + onSubmitUserInput={async () => {}}
1267 + onDismissUserInput={async () => {}}
1268 />
1851 - <SheetHeader
1852 - title="New thread"
1853 - onCancel={closeNewTask}
1854 - accessibilityLabel="Cancel new task"
1855 - />
1856 -
1857 - {heroViewport}
1858 - <KeyboardStickyView
1859 - pointerEvents="box-none"
1860 - style={{ position: "absolute", top: 0, bottom: 0, left: 0, right: 0 }}
1861 - offset={{ closed: 0, opened: keyboardOpenedOffset }}
1862 - >
1863 - <Animated.View
1864 - layout={COMPOSER_LAYOUT_TRANSITION}
1865 - pointerEvents="box-none"
1866 - style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
1867 - >
1868 - {composerDock}
1869 - </Animated.View>
1870 - </KeyboardStickyView>
1871 - </View>
1269 + </>
1270 );
1271 }
apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
+52 -46
@@ -1,3 +1,4 @@
1 +import { isDraftThreadRoute } from "./thread-route-state";
2 import * as Dialog from "../../components/ui/Dialog";
3 import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
4 import { NavigationRow } from "../../components/ui/NavigationRow";
@@ -31,7 +32,7 @@ import { useAtomCommand } from "../../state/use-atom-command";
32 import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
33 import type { WorkspaceState } from "../../state/workspaceModel";
34 import { useWorkspaceState } from "../../state/workspace";
34 -import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
35 +
36 import { usePromptLinkResolver } from "../prompt-links/usePromptLinkResolver";
37 import { useIncomingShare } from "../sharing/IncomingShareProvider";
38 import { useNewTaskFlow } from "./new-task-flow-provider";
@@ -113,36 +114,37 @@ function NewTaskHeader(props: {
114 readonly onSearchTextChange: (text: string) => void;
115 }) {
116 const navigation = useNavigation();
116 - const { layout } = useAdaptiveWorkspaceLayout();
117 + const goBack = () => {
118 + if (navigation.canGoBack()) navigation.goBack();
119 + else navigation.getParent()?.goBack();
120 + };
121 return (
118 - <AppBar
119 - title={props.title}
120 - subtitle={props.subtitle ?? undefined}
121 - sidebar={false}
122 - backInSplitView={{
123 - accessibilityLabel: "Go back",
124 - icon: "chevron.left",
125 - }}
126 - options={{ headerBackVisible: !layout.usesSplitView }}
127 - hideBottomBorder
128 - onBack={() => navigation.goBack()}
129 - actions={
130 - props.canAddProject
131 - ? [
132 - {
133 - accessibilityLabel: "Add project",
134 - icon: "plus",
135 - onPress: () => navigation.dispatch(StackActions.push("AddProject")),
136 - },
137 - ]
138 - : []
139 - }
140 - search={{
141 - value: props.searchText,
142 - onChangeText: props.onSearchTextChange,
143 - placeholder: "Search projects",
144 - }}
145 - />
122 + <>
123 + <AppBar
124 + title={props.title}
125 + subtitle={props.subtitle ?? undefined}
126 + sidebar={false}
127 + options={{ headerBackVisible: true }}
128 + hideBottomBorder
129 + onBack={goBack}
130 + actions={
131 + props.canAddProject
132 + ? [
133 + {
134 + accessibilityLabel: "Add project",
135 + icon: "plus",
136 + onPress: () => navigation.dispatch(StackActions.push("AddProject")),
137 + },
138 + ]
139 + : []
140 + }
141 + search={{
142 + value: props.searchText,
143 + onChangeText: props.onSearchTextChange,
144 + placeholder: "Search projects",
145 + }}
146 + />
147 + </>
148 );
149 }
150
@@ -219,22 +221,23 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
221 return;
222 }
223 }
222 - const state = navigation.getState();
223 - const previousRoute = state?.routes[state.index - 1];
224 - if (previousRoute?.name === "NewTaskDraft") {
224 + const root = navigation.getState()?.routeNames.includes("NewTaskProject")
225 + ? navigation
226 + : navigation.getParent();
227 + const rootState = root?.getState();
228 + const threadRoute = rootState?.routes[rootState.index - 1];
229 + if (isDraftThreadRoute(threadRoute)) {
230 setProject(project);
226 - navigation.goBack();
231 + root?.goBack();
232 return;
233 }
229 -
230 - navigation.dispatch(
231 - StackActions.push("NewTaskDraft", {
232 - environmentId: project.environmentId,
233 - projectId: project.id,
234 - title: project.title,
234 + root?.navigate("Thread", {
235 + draft: {
236 + environmentId: String(project.environmentId),
237 + projectId: String(project.id),
238 incomingShareId: incomingShare?.id,
236 - }),
237 - );
239 + },
240 + });
241 }
242
243 async function startScratch(): Promise<void> {
@@ -280,14 +283,17 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
283 return;
284 }
285 resumedDestinationKeyRef.current = destinationKey;
283 - navigation.dispatch(
284 - StackActions.push("NewTaskDraft", {
286 + (navigation.getState()?.routeNames.includes("NewTaskProject")
287 + ? navigation
288 + : navigation.getParent()
289 + )?.navigate("Thread", {
290 + draft: {
291 environmentId: reservedDestinationProject.environmentId,
292 projectId: reservedDestinationProject.id,
293 title: reservedDestinationProject.title,
294 incomingShareId: incomingShare.id,
289 - }),
290 - );
295 + },
296 + });
297 }, [incomingShare, isFocused, navigation, reservedDestinationProject]);
298
299 return (
apps/mobile/src/features/threads/ThreadComposer.tsx
+236 -183
@@ -1,3 +1,4 @@
1 +import { useSidebarWorkspaceTabs } from "../workspace/useSystemWorkspaceTabBar";
2 import { Button } from "../../components/ui/Button";
3 import * as Dialog from "../../components/ui/Dialog";
4 import type { ComposerTextPaste } from "../../native/T3ComposerEditor.types";
@@ -139,9 +140,95 @@ function collapsedEditorInset(text: ScaledTextRole): number {
140 return Math.max(0, Math.round(COLLAPSED_EDITOR_DEFAULT_INSET - shift));
141 }
142
142 -export const COMPOSER_EXPANDED_CHROME = 156;
143 +export function useCompactComposerEditor(text: ScaledTextRole, value: string) {
144 + const [contentSize, setContentSize] = useState({ width: 0, height: 0 });
145 + const [compactWidth, setCompactWidth] = useState(0);
146 + const contentHeight = contentSize.height;
147 + const rowWidth = useSharedValue(0);
148 + const editorX = useSharedValue(0);
149 + const editorWidth = useSharedValue(0);
150 + const inset = Platform.OS === "android" ? 0 : collapsedEditorInset(text);
151 + const minimum = Math.max(INLINE_EDITOR_HEIGHT, Math.ceil(text.lineHeight) + 2 * inset);
152 + const height = Math.max(
153 + minimum,
154 + Math.min(text.lineHeight * 4 + 2 * inset, contentHeight + 2 * inset),
155 + );
156 + // A line that fits the expanded editor may still overflow its compact slot.
157 + // Compare its measured width too so widening cannot trigger a collapse loop.
158 + const isExpanded =
159 + value.length > 0 &&
160 + (contentHeight > text.lineHeight * 1.5 ||
161 + (compactWidth > 0 && contentSize.width > compactWidth));
162 + const compactRowHeight = Math.max(44, minimum);
163 + const animatedHeight = useSharedValue(height);
164 + const surfaceHeight = useSharedValue(compactRowHeight);
165 + const targetSurfaceHeight = isExpanded ? height + 52 : compactRowHeight;
166 + const expansion = useSharedValue(0);
167 + useLayoutEffect(() => {
168 + const config = { duration: 180, reduceMotion: ReduceMotion.System };
169 + if (Platform.OS === "android") {
170 + animatedHeight.set(height);
171 + surfaceHeight.set(targetSurfaceHeight);
172 + expansion.set(Number(isExpanded));
173 + return;
174 + }
175 + // Resolve wrapping at the destination width before animating vertically.
176 + // Intermediate widths otherwise produce taller measurements mid-transition.
177 + let nextFrame: number | undefined;
178 + const frame = requestAnimationFrame(() => {
179 + nextFrame = requestAnimationFrame(() => {
180 + animatedHeight.set(withTiming(height, config));
181 + surfaceHeight.set(withTiming(targetSurfaceHeight, config));
182 + expansion.set(withTiming(Number(isExpanded), config));
183 + });
184 + });
185 + return () => {
186 + cancelAnimationFrame(frame);
187 + if (nextFrame !== undefined) cancelAnimationFrame(nextFrame);
188 + };
189 + }, [animatedHeight, expansion, height, isExpanded, surfaceHeight, targetSurfaceHeight]);
190 + const containerStyle = useAnimatedStyle(() => ({
191 + height: surfaceHeight.value,
192 + }));
193 + const editorStyle = useAnimatedStyle(() => ({
194 + position: "absolute",
195 + overflow: "hidden",
196 + height: animatedHeight.value,
197 + left: isExpanded ? 14 : editorX.value + 4,
198 + right: isExpanded ? 14 : rowWidth.value - editorX.value - editorWidth.value + 4,
199 + bottom:
200 + (compactRowHeight - minimum) / 2 + expansion.value * (52 - (compactRowHeight - minimum) / 2),
201 + }));
202 + return {
203 + isExpanded,
204 + containerStyle,
205 + editorStyle,
206 + onRowLayout: (event: { nativeEvent: { layout: { width: number } } }) => {
207 + rowWidth.set(event.nativeEvent.layout.width);
208 + },
209 + onEditorLayout: (event: { nativeEvent: { layout: { x: number; width: number } } }) => {
210 + // The expanded toolbar gives this slot to the model control. Keep the
211 + // compact geometry for the return transition, rather than recording zero.
212 + if (!isExpanded) {
213 + editorX.set(event.nativeEvent.layout.x);
214 + editorWidth.set(event.nativeEvent.layout.width);
215 + setCompactWidth(Math.max(0, event.nativeEvent.layout.width - 8));
216 + }
217 + },
218 + editorProps: {
219 + singleLineCentered: false,
220 + scrollEnabled: Platform.OS === "android" || contentHeight >= text.lineHeight * 4,
221 + contentInsetVertical: inset,
222 + onContentSizeChange: (size: { width: number; height: number }) => {
223 + setContentSize(size);
224 + },
225 + style: { flex: 1 },
226 + },
227 + };
228 +}
229
230 export interface ThreadComposerProps {
231 + readonly isDraft?: boolean;
232 readonly canOperateThread: boolean;
233 readonly placeholder: string;
234 readonly contentMaxWidth?: number;
@@ -159,6 +246,7 @@ export interface ThreadComposerProps {
246 readonly environmentId: EnvironmentId;
247 readonly projectCwd: string | null;
248 readonly sendBlockedReason?: string | null;
249 + readonly interactionLocked?: boolean;
250 readonly draftKey?: string;
251 readonly queuedEdit?: {
252 readonly existingAttachments: ReadonlyArray<ChatAttachment>;
@@ -187,9 +275,8 @@ export interface ThreadComposerProps {
275 readonly canSwitchProvider: boolean;
276 readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
277 readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
190 - readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
191 - /** True while the draft is stacked above the controls rather than in the one-row capsule. */
192 - readonly onExpandedChange?: (expanded: boolean) => void;
278 + readonly onUpdateInteractionMode?: (interactionMode: ProviderInteractionMode) => void;
279 + readonly onHeightChange?: (height: number) => void;
280 readonly onEditorFocusChange?: (focused: boolean) => void;
281 }
282
@@ -224,8 +311,6 @@ export const COMPOSER_LAYOUT_TRANSITION =
311 Platform.OS === "android" ? undefined : composerHeightTransition;
312 // Share of the one-row composer the draft keeps; a long model name truncates first.
313 const INLINE_EDITOR_MIN_WIDTH = "40%";
227 -// The one-row editor's horizontal padding plus room for the caret.
228 -const INLINE_EDITOR_TEXT_SLACK = 10;
314 const INLINE_EDITOR_HEIGHT = 36;
315
316 const COMPOSER_ATTACHMENT_ENTERING =
@@ -248,6 +333,7 @@ const FOLLOW_UP_ACTION_SUBTITLE = {
333 } as const;
334
335 function SendActionButton(props: {
336 + readonly size?: "regular" | "large";
337 readonly accessibilityLabel: string;
338 readonly presentation: ComposerSendPresentation;
339 readonly disabled: boolean;
@@ -257,6 +343,7 @@ function SendActionButton(props: {
343 const button = (
344 <ComposerActionButton
345 accessibilityLabel={props.accessibilityLabel}
346 + size={props.size}
347 icon={presentation.icon}
348 variant="primary"
349 disabled={props.disabled}
@@ -306,8 +393,10 @@ export function ComposerSurface(props: {
393 })
394 : targetBorderRadius;
395 }, [animatedBorderRadius, shouldAnimate, targetBorderRadius]);
396 + const borderCurve = props.style.borderCurve;
397 const animatedShapeStyle = useAnimatedStyle(() => ({
398 borderRadius: animatedBorderRadius.value,
399 + ...(borderCurve ? { borderCurve } : {}),
400 }));
401 const layoutTransition = shouldAnimate ? COMPOSER_LAYOUT_TRANSITION : undefined;
402
@@ -373,7 +462,6 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
462 const settingsRoutePresentedRef = useRef(false);
463 const wasExpandedBeforePreviewRef = useRef(false);
464 const inFlightThreadIdsRef = useRef(new Set<string>());
376 - const { onExpandedChange } = props;
465
466 const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
467 const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
@@ -480,7 +568,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
568 pullRequestRepository: project?.repositoryIdentity?.displayName ?? null,
569 threadPullRequests: props.selectedThread.pullRequests,
570 selectedProviderStatus,
483 - hasThread: true,
571 + hasThread: !props.isDraft,
572 hasCompactableConversation: props.hasCompactableConversation,
573 onChangeDraftMessage: props.onChangeDraftMessage,
574 onUpdateInteractionMode:
@@ -500,7 +588,8 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
588 onChangeDraftMessage: (text) => setComposerDraftText(composerDraftKey, text),
589 onChangeSelection: composerMenu.onSelectionChange,
590 });
503 - const isSubmissionLocked = queuedEdit?.saving === true || voiceInput.blocksSubmission;
591 + const isSubmissionLocked =
592 + props.interactionLocked === true || queuedEdit?.saving === true || voiceInput.blocksSubmission;
593 const voicePresentation = resolveVoiceComposerPresentation(
594 voiceInput.state,
595 voiceInput.elapsedSeconds,
@@ -508,35 +597,12 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
597 const isVoiceInputPresented = voicePresentation.statusLabel !== null;
598 const isExpanded = isFocused || settingsSheetPresentation.keepsComposerExpanded;
599 const { setComposerEditing } = useAdaptiveWorkspaceLayout();
511 - // The composer stays one row, with the model picker in it, until the draft would
512 - // wrap. Then the draft stacks above the controls and returns to the row once it
513 - // fits again. The native editor reports its laid-out text size: more than one
514 - // line means the draft wrapped where it is, and the widest line is a one-line
515 - // draft's natural width, which is compared with the row's text area so a draft
516 - // laid out in the wider card still returns to the row when it fits, including
517 - // when the pane widens. The measurements live in refs and only the verdict is
518 - // state, so a keystroke that keeps the verdict costs no extra render.
519 - const draftSizeRef = useRef({ width: 0, height: 0 });
520 - const rowGeometryRef = useRef({ surfaceWidth: 0, leadingWidth: 0, trailingWidth: 0 });
521 - const [draftOverflowsRow, setDraftOverflowsRow] = useState(false);
522 - const lineHeight = bodyText.lineHeight;
523 - const updateDraftOverflow = () => {
524 - const { width, height } = draftSizeRef.current;
525 - const row = rowGeometryRef.current;
526 - const rowTextWidth =
527 - row.surfaceWidth - row.leadingWidth - row.trailingWidth - INLINE_EDITOR_TEXT_SLACK;
528 - setDraftOverflowsRow(
529 - height > lineHeight * 1.5 || (row.surfaceWidth > 0 && width > rowTextWidth),
530 - );
531 - };
532 - const measureRow = (key: keyof typeof rowGeometryRef.current, value: number) => {
533 - if (rowGeometryRef.current[key] === value) return;
534 - rowGeometryRef.current = { ...rowGeometryRef.current, [key]: value };
535 - updateDraftOverflow();
536 - };
537 - const usesCard = isExpanded && draftMessage.length > 0 && draftOverflowsRow;
538 - const showsCompactDictation = isVoiceInputPresented && !usesCard;
539 - const isToolbarVisible = usesCard || isVoiceInputPresented;
600 + const hasSidebarTabBar = useSidebarWorkspaceTabs() === "picker";
601 + const [compactRowWidth, setCompactRowWidth] = useState(0);
602 + const compactAttachmentLimit = compactRowWidth >= 500 ? 3 : 1;
603 + const compactEditor = useCompactComposerEditor(bodyText, draftMessage);
604 + const showsCompactDictation = isVoiceInputPresented;
605 + const isToolbarVisible = isVoiceInputPresented;
606 const hasEditingAttachments =
607 (queuedEdit !== null && queuedEdit.existingAttachments.length > 0) ||
608 stripAttachments.length > 0;
@@ -561,9 +627,6 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
627 sendBlockedReason === null &&
628 !modelUnavailable;
629
564 - useEffect(() => {
565 - onExpandedChange?.(usesCard);
566 - }, [usesCard, onExpandedChange]);
630 useEffect(() => () => setComposerEditing(false), [setComposerEditing]);
631
632 const onPressPreview = (source: FilePreviewSource) => {
@@ -609,6 +672,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
672 const handleSend = async (followUp?: ActiveTurnComposerAction) => {
673 if (
674 isSubmissionLocked ||
675 + sendBlockedReason !== null ||
676 pendingPastedTextAttachmentCountRef.current > 0 ||
677 pendingNativeImagePasteCountRef.current > 0
678 )
@@ -743,7 +807,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
807 <>
808 {queuedEdit !== null && queuedEdit.existingAttachments.length > 0 ? (
809 <Animated.View
746 - className="px-[14px] pb-2.5"
810 + className="px-[14px] pb-2.5 pt-2"
811 entering={COMPOSER_ATTACHMENT_ENTERING}
812 exiting={FadeOut.duration(120)}
813 >
@@ -757,7 +821,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
821 ) : null}
822 {stripAttachments.length > 0 ? (
823 <Animated.View
760 - className="px-[14px] pb-2.5"
824 + className="px-[14px] pb-2.5 pt-2"
825 entering={COMPOSER_ATTACHMENT_ENTERING}
826 exiting={FadeOut.duration(120)}
827 >
@@ -789,14 +853,16 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
853 const modelControl = (
854 <View className="min-w-0 shrink">
855 <ComposerModelControl
856 + size={hasSidebarTabBar ? "large" : "regular"}
857 modelOption={currentModelOption}
858 selection={currentModelSelection}
859 provider={selectedProviderStatus?.driver}
860 reportedSelection={props.reportedModelSelection}
861 prompt={draftMessage}
862 surfaceColor={composerPanel}
798 - iconOnly={!usesCard && draftMessage.length > 0}
799 - showSummary={usesCard}
863 + iconOnly={
864 + (draftMessage.length > 0 || stripAttachments.length > 0) && !compactEditor.isExpanded
865 + }
866 onPress={openSettings}
867 />
868 </View>
@@ -804,10 +870,11 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
870
871 return (
872 <Animated.View
873 + onLayout={(event) => props.onHeightChange?.(event.nativeEvent.layout.height)}
874 className="px-[12px]"
875 style={{
809 - paddingTop: usesCard ? 8 : 6,
810 - paddingBottom: (props.bottomInset ?? 0) + (usesCard ? 8 : THREAD_COMPOSER_BOTTOM_GUTTER),
876 + paddingTop: 6,
877 + paddingBottom: (props.bottomInset ?? 0) + THREAD_COMPOSER_BOTTOM_GUTTER,
878 backgroundColor:
879 Platform.OS === "android" ? themeColorWithAlpha(composerPanel, 1) : undefined,
880 }}
@@ -826,7 +893,6 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
893 <Animated.View
894 className="relative w-full self-center"
895 style={{ maxWidth: props.contentMaxWidth }}
829 - onLayout={(event) => measureRow("surfaceWidth", event.nativeEvent.layout.width)}
896 >
897 {!isSubmissionLocked &&
898 composerMenu.trigger &&
@@ -872,29 +938,28 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
938 ) : null}
939
940 <ComposerSurface
875 - style={
876 - usesCard
877 - ? {
878 - borderRadius: 26,
879 - overflow: "hidden" as const,
880 - paddingBottom: 6,
881 - paddingTop: 14,
882 - }
883 - : {
884 - borderRadius: 27,
885 - overflow: "hidden" as const,
886 - paddingVertical: 2,
887 - }
888 - }
941 + animateLayout={false}
942 + style={{
943 + borderRadius: hasSidebarTabBar ? 31 : 27,
944 + borderCurve: "circular",
945 + overflow: "hidden",
946 + paddingVertical: hasSidebarTabBar ? 9 : 2,
947 + }}
948 >
890 - {isExpanded && !usesCard ? editingAttachments : null}
891 - <ComposerDictationDraftContent
892 - className={usesCard ? undefined : "flex-row items-center"}
893 - compact={!usesCard}
894 - hidden={showsCompactDictation}
949 + {isExpanded ? editingAttachments : null}
950 + <View
951 + onLayout={(event) => {
952 + compactEditor.onRowLayout(event);
953 + setCompactRowWidth(event.nativeEvent.layout.width);
954 + }}
955 >
896 - {!usesCard ? (
956 + <ComposerDictationDraftContent
957 + className="flex-row items-end"
958 + compact
959 + hidden={showsCompactDictation}
960 + >
961 <ComposerAttachmentButton
962 + size={hasSidebarTabBar ? "large" : "regular"}
963 disabled={isSubmissionLocked}
964 supportsFiles={Boolean(
965 props.serverConfig?.environment.capabilities.fileAttachments,
@@ -902,17 +967,91 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
967 onPickMedia={props.onPickDraftMedia}
968 onPickFiles={props.onPickDraftFiles}
969 />
905 - ) : null}
906 - {usesCard ? editingAttachments : null}
970 + <Animated.View
971 + className="min-w-0 flex-1"
972 + onLayout={compactEditor.onEditorLayout}
973 + style={[
974 + {
975 + minWidth:
976 + compactEditor.isExpanded || stripAttachments.length > 0
977 + ? 0
978 + : INLINE_EDITOR_MIN_WIDTH,
979 + },
980 + compactEditor.containerStyle,
981 + compactEditor.isExpanded ? { flex: 0, width: 0 } : undefined,
982 + ]}
983 + ></Animated.View>
984 + {!isExpanded && stripAttachments.length > 0 ? (
985 + <View className="h-[44px] shrink-0 flex-row items-center gap-1 pl-1">
986 + {stripAttachments.slice(0, compactAttachmentLimit).map((attachment) => (
987 + <ComposerAttachmentThumbnail
988 + environmentId={props.environmentId}
989 + key={attachment.id}
990 + attachment={attachment}
991 + size={30}
992 + borderRadius={8}
993 + compact
994 + onPressPreview={isSubmissionLocked ? undefined : onPressPreview}
995 + onPressVideo={isSubmissionLocked ? undefined : onPressVideo}
996 + />
997 + ))}
998 + {stripAttachments.length > compactAttachmentLimit ? (
999 + <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
1000 + <Text className="text-foreground-muted text-2xs font-t3-bold">
1001 + +{stripAttachments.length - compactAttachmentLimit}
1002 + </Text>
1003 + </View>
1004 + ) : null}
1005 + </View>
1006 + ) : null}
1007 + <View
1008 + className="min-w-0 shrink flex-row items-center"
1009 + style={
1010 + compactEditor.isExpanded ? { flex: 1, justifyContent: "flex-end" } : undefined
1011 + }
1012 + >
1013 + {modelControl}
1014 + <ComposerDictationStartAction
1015 + size={hasSidebarTabBar ? "large" : "regular"}
1016 + state={voiceInput.state}
1017 + isAvailable={voiceInput.isAvailable}
1018 + disabled={isSubmissionLocked}
1019 + onStart={voiceInput.start}
1020 + onCancel={voiceInput.cancel}
1021 + />
1022 + {showStopAction ? (
1023 + <ComposerActionButton
1024 + size={hasSidebarTabBar ? "large" : "regular"}
1025 + accessibilityLabel="Stop agent"
1026 + icon="stop.fill"
1027 + variant="danger"
1028 + disabled={!props.canOperateThread}
1029 + onPress={props.onStopThread}
1030 + />
1031 + ) : showResumeAction ? (
1032 + <ComposerActionButton
1033 + size={hasSidebarTabBar ? "large" : "regular"}
1034 + accessibilityLabel="Resume queue"
1035 + icon="play"
1036 + disabled={!props.canOperateThread || resumingQueue}
1037 + onPress={() => void handleResumeQueue()}
1038 + />
1039 + ) : (
1040 + <SendActionButton
1041 + size={hasSidebarTabBar ? "large" : "regular"}
1042 + accessibilityLabel={sendBlockedReason ?? sendLabel}
1043 + presentation={sendPresentation}
1044 + disabled={!canSend}
1045 + onSend={handleSend}
1046 + />
1047 + )}
1048 + </View>
1049 + </ComposerDictationDraftContent>
1050 <Animated.View
908 - className={usesCard ? "px-[14px]" : "min-w-0 flex-1 px-[4px]"}
909 - style={usesCard ? undefined : { minWidth: INLINE_EDITOR_MIN_WIDTH }}
910 - layout={COMPOSER_LAYOUT_TRANSITION}
911 - onLayout={
912 - usesCard
913 - ? undefined
914 - : (event) => measureRow("leadingWidth", event.nativeEvent.layout.x)
915 - }
1051 + style={[
1052 + compactEditor.editorStyle,
1053 + showsCompactDictation ? { display: "none" } : undefined,
1054 + ]}
1055 >
1056 <ComposerEditor
1057 hidden={props.hidden}
@@ -920,11 +1059,19 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
1059 environmentId={props.environmentId}
1060 onOpenMention={(path) => {
1061 Keyboard.dismiss();
923 - navigation.navigate("ThreadFile", {
924 - environmentId: String(props.environmentId),
925 - threadId: String(props.selectedThread.id),
926 - path: fileRoutePathSegments(path),
927 - });
1062 + if (props.isDraft) {
1063 + navigation.navigate("NewTaskFile", {
1064 + environmentId: String(props.environmentId),
1065 + cwd: props.projectCwd ?? undefined,
1066 + path: fileRoutePathSegments(path),
1067 + });
1068 + } else {
1069 + navigation.navigate("ThreadFile", {
1070 + environmentId: String(props.environmentId),
1071 + threadId: String(props.selectedThread.id),
1072 + path: fileRoutePathSegments(path),
1073 + });
1074 + }
1075 }}
1076 onOpenAttachment={openDraftDocument}
1077 chipsInert={!isExpanded}
@@ -1034,117 +1181,20 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
1181 ? sendPresentation.label
1182 : FOLLOW_UP_ACTION_LABEL[sendPresentation.alternate]
1183 }
1037 - scrollEnabled={isExpanded}
1038 - singleLineCentered={!usesCard}
1039 - contentInsetVertical={
1040 - usesCard || Platform.OS === "android" ? 0 : collapsedEditorInset(bodyText)
1041 - }
1042 - onContentSizeChange={(size) => {
1043 - draftSizeRef.current = size;
1044 - updateDraftOverflow();
1045 - }}
1046 - style={
1047 - usesCard
1048 - ? {
1049 - // A stacked draft shows two to four lines, then scrolls.
1050 - minHeight: lineHeight * 2 + 8,
1051 - maxHeight: lineHeight * 4 + 8,
1052 - paddingVertical: 4,
1053 - }
1054 - : {
1055 - // Large text sizes need room for one full line plus the iOS inset.
1056 - height: Math.max(
1057 - INLINE_EDITOR_HEIGHT,
1058 - Math.ceil(lineHeight) +
1059 - (Platform.OS === "android" ? 0 : 2 * collapsedEditorInset(bodyText)),
1060 - ),
1061 - }
1062 - }
1184 + {...compactEditor.editorProps}
1185 textStyle={{
1186 ...bodyText,
1187 color: foregroundColor,
1188 }}
1189 />
1190 </Animated.View>
1069 - {!isExpanded && stripAttachments.length > 0 ? (
1070 - <View className="flex-row gap-1 pl-1">
1071 - {stripAttachments.slice(0, 3).map((attachment) => (
1072 - <ComposerAttachmentThumbnail
1073 - environmentId={props.environmentId}
1074 - key={attachment.id}
1075 - attachment={attachment}
1076 - size={30}
1077 - borderRadius={8}
1078 - compact
1079 - onPressPreview={isSubmissionLocked ? undefined : onPressPreview}
1080 - onPressVideo={isSubmissionLocked ? undefined : onPressVideo}
1081 - />
1082 - ))}
1083 - {stripAttachments.length > 3 ? (
1084 - <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
1085 - <Text className="text-foreground-muted text-2xs font-t3-bold">
1086 - +{stripAttachments.length - 3}
1087 - </Text>
1088 - </View>
1089 - ) : null}
1090 - </View>
1091 - ) : null}
1092 - {!usesCard ? (
1093 - <View
1094 - className="min-w-0 shrink flex-row items-center"
1095 - onLayout={(event) => measureRow("trailingWidth", event.nativeEvent.layout.width)}
1096 - >
1097 - {modelControl}
1098 - <ComposerDictationStartAction
1099 - state={voiceInput.state}
1100 - isAvailable={voiceInput.isAvailable}
1101 - disabled={isSubmissionLocked}
1102 - onStart={voiceInput.start}
1103 - onCancel={voiceInput.cancel}
1104 - />
1105 - {showStopAction ? (
1106 - <ComposerActionButton
1107 - accessibilityLabel="Stop agent"
1108 - icon="stop.fill"
1109 - variant="danger"
1110 - disabled={!props.canOperateThread}
1111 - onPress={props.onStopThread}
1112 - />
1113 - ) : showResumeAction ? (
1114 - <ComposerActionButton
1115 - accessibilityLabel="Resume queue"
1116 - icon="play"
1117 - disabled={!props.canOperateThread || resumingQueue}
1118 - onPress={() => void handleResumeQueue()}
1119 - />
1120 - ) : (
1121 - <SendActionButton
1122 - accessibilityLabel={sendBlockedReason ?? sendLabel}
1123 - presentation={sendPresentation}
1124 - disabled={!canSend}
1125 - onSend={handleSend}
1126 - />
1127 - )}
1128 - </View>
1129 - ) : null}
1130 - {usesCard ? <View className="h-1" /> : null}
1131 - </ComposerDictationDraftContent>
1191 + </View>
1192 <Animated.View
1193 accessibilityElementsHidden={!isToolbarVisible}
1194 collapsable={false}
1195 importantForAccessibility={isToolbarVisible ? "auto" : "no-hide-descendants"}
1136 - layout={COMPOSER_LAYOUT_TRANSITION}
1196 pointerEvents={isToolbarVisible ? "auto" : "none"}
1138 - style={
1139 - usesCard
1140 - ? undefined
1141 - : {
1142 - position: "absolute",
1143 - bottom: 2,
1144 - left: 0,
1145 - right: 0,
1146 - }
1147 - }
1197 + style={{ position: "absolute", bottom: hasSidebarTabBar ? 9 : 2, left: 0, right: 0 }}
1198 >
1199 <ComposerDictationToolbar
1200 showsDictation={isVoiceInputPresented}
@@ -1157,6 +1207,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
1207 style={{ gap: 0 }}
1208 >
1209 <ComposerDictationCancelAction
1210 + size={hasSidebarTabBar ? "large" : "regular"}
1211 presentation={voicePresentation}
1212 onCancel={voiceInput.cancel}
1213 />
@@ -1171,6 +1222,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
1222 ) : (
1223 <View className="min-w-0 flex-1 flex-row items-center justify-between">
1224 <ComposerAttachmentButton
1225 + size={hasSidebarTabBar ? "large" : "regular"}
1226 disabled={isSubmissionLocked}
1227 supportsFiles={Boolean(
1228 props.serverConfig?.environment.capabilities.fileAttachments,
@@ -1183,6 +1235,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
1235 )}
1236 <View className="shrink-0 flex-row items-center">
1237 <ComposerDictationPrimaryAction
1238 + size={hasSidebarTabBar ? "large" : "regular"}
1239 state={voiceInput.state}
1240 presentation={voicePresentation}
1241 isAvailable={voiceInput.isAvailable}
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+67 -31
@@ -1,3 +1,4 @@
1 +import { useSidebarWorkspaceTabs } from "../workspace/useSystemWorkspaceTabBar";
2 import {
3 isAtomCommandInterrupted,
4 settlePromise,
@@ -106,6 +107,7 @@ import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspace
107 import {
108 useDuoBottomBarInset,
109 useNativeColumnLayoutMetrics,
110 + useNativeLayoutMetrics,
111 } from "../../native/native-layout-metrics";
112 import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
113 import { collectProviderUsageLimits } from "@t3tools/shared/usageLimits";
@@ -160,9 +162,6 @@ import {
162 } from "./pendingUserInputLayout";
163 import {
164 COMPOSER_COLLAPSED_CHROME,
163 - COMPOSER_EXPANDED_CHROME,
164 - COMPOSER_LAYOUT_TRANSITION,
165 - COMPOSER_TRANSITION_DURATION_MS,
165 THREAD_COMPOSER_BOTTOM_GUTTER,
166 ThreadComposer,
167 } from "./ThreadComposer";
@@ -176,6 +175,18 @@ import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow";
175 import { useGlobalVoiceInput } from "../voice-input/VoiceInputProvider";
176
177 export interface ThreadDetailScreenProps {
178 + readonly header?: React.ReactNode;
179 + readonly draftMode?: {
180 + readonly content: (
181 + headerInset: number,
182 + bottomInset: number,
183 + availableHeight: number,
184 + ) => React.ReactNode;
185 + readonly controls: React.ReactNode;
186 + readonly editorRef: React.RefObject<ComposerEditorHandle | null>;
187 + readonly sendBlockedReason: string | null;
188 + readonly interactionLocked: boolean;
189 + };
190 readonly worktreeSetup?: WorktreeSetupCardProps | null;
191 readonly setupWorkingStartedAt?: string | null;
192 readonly canOperateThread: boolean;
@@ -253,7 +264,7 @@ export interface ThreadDetailScreenProps {
264 readonly canSwitchThreadProvider: boolean;
265 readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
266 readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
256 - readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
267 + readonly onUpdateThreadInteractionMode?: (interactionMode: ProviderInteractionMode) => void;
268 readonly onRespondToApproval: ApprovalResponder;
269 readonly onSelectUserInputOption: (
270 requestId: RuntimeRequestId,
@@ -457,7 +468,8 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
468 const browserTabs = useThreadServerBrowserTabs({
469 environmentId: props.environmentId,
470 threadId: props.selectedThread.id,
460 - enabled: props.serverConfig?.environment.capabilities.serverBrowser === true,
471 + enabled:
472 + !props.draftMode && props.serverConfig?.environment.capabilities.serverBrowser === true,
473 });
474 const openBrowserPreview = (tabId?: string) => {
475 Keyboard.dismiss();
@@ -505,6 +517,7 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
517 const navigationHeaderHeight = useContext(HeaderHeightContext) ?? insets.top + 44;
518 const [screenMetrics, setScreenMetrics] = useState<NativeLayoutMetrics | null>(null);
519 const columnMetrics = useNativeColumnLayoutMetrics();
520 + const windowMetrics = useNativeLayoutMetrics();
521 const nativeMetrics = usesNativeWorkspaceColumns ? columnMetrics : screenMetrics;
522 const controlInsets = deriveBottomControlInsets(nativeMetrics);
523 const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
@@ -517,38 +530,43 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
530 const queuedCount = useThreadQueuedCount(props.selectedThreadDetailRef);
531 const turnSubagents = useThreadTurnSubagents(props.selectedThreadDetailRef);
532 const agentsSegment = resolveSubagentPillSegment(turnSubagents);
520 - const composerEditorRef = useRef<ComposerEditorHandle>(null);
533 + const defaultComposerEditorRef = useRef<ComposerEditorHandle>(null);
534 + const composerEditorRef = props.draftMode?.editorRef ?? defaultComposerEditorRef;
535 const isProviderSubagent = isProviderNativeSubagentThread(props.selectedThread.source);
536 const editingRunId = props.queuedRunEdit?.runId ?? null;
537 useEffect(() => {
538 if (editingRunId === null) return;
539 const frame = requestAnimationFrame(() => composerEditorRef.current?.focus());
540 return () => cancelAnimationFrame(frame);
527 - }, [editingRunId]);
541 + }, [editingRunId, composerEditorRef]);
542 const composerOverlayRef = useRef<ViewInstance>(null);
543 const listRef = useRef<LegendListRef>(null);
544 const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
545 const selectedThreadKeyRef = useRef(selectedThreadKey);
546 const lastScrolledSubmittedMessageIdRef = useRef<MessageId | null>(null);
533 - const [composerExpanded, setComposerExpanded] = useState(false);
547 + const [composerHeight, setComposerHeight] = useState<number | null>(null);
548 const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
549 const [submittedMessageId, setSubmittedMessageId] = useState<MessageId | null>(null);
550 const [endFollowEnabled, setEndFollowEnabled] = useState(true);
537 - // Android Back hides the keyboard without blurring. Keep its safe-area padding
538 - // fixed through the animation and cancel it with matching composer/list offsets.
551 + // Keep the bottom padding fixed while the keyboard animates. Changing it at
552 + // keyboardDidHide makes the composer land low, then jump back above the safe area.
553 const bottomBarInset = useDuoBottomBarInset();
554 + const hasSidebarTabBar = useSidebarWorkspaceTabs() === "picker";
555 + // A pushed screen temporarily inherits the outgoing tab bar's safe area.
556 + // Use the window edge so hiding that bar cannot move the composer mid-push.
557 + const bottomSafeArea =
558 + Platform.OS === "ios" ? (windowMetrics?.safeArea.bottom ?? insets.bottom) : insets.bottom;
559 // The pill already adds its own gutter; iPad and Duo align its edge with the native bar.
560 const alignedBottomInset =
561 bottomBarInset ??
543 - (Platform.OS === "ios" && Platform.isPad ? Math.max(insets.bottom, 12) : undefined);
544 - // A hardware keyboard can focus the editor without occupying any screen height.
562 + (Platform.OS === "ios" && Platform.isPad
563 + ? Math.max(bottomSafeArea, 12) - (hasSidebarTabBar ? 5 : 0)
564 + : undefined);
565 const composerBottomInset =
546 - Platform.OS === "ios" && (composerExpanded || liveKeyboardHeight > 0)
547 - ? 0
548 - : alignedBottomInset !== undefined
549 - ? Math.max(0, alignedBottomInset - THREAD_COMPOSER_BOTTOM_GUTTER)
550 - : Math.max(insets.bottom, 12);
551 - const composerKeyboardOffset = Platform.OS === "android" ? composerBottomInset : 0;
566 + alignedBottomInset !== undefined
567 + ? Math.max(0, alignedBottomInset - THREAD_COMPOSER_BOTTOM_GUTTER)
568 + : Math.max(bottomSafeArea, 12);
569 + const composerKeyboardOffset = composerBottomInset;
570 const contentPresentationKind = props.contentPresentation.kind;
571 const realThreadSyncLabel = (() => {
572 switch (props.threadSyncStatus) {
@@ -664,7 +682,7 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
682 environmentLabel: props.environmentLabel,
683 onReconnect: props.onReconnectEnvironment,
684 });
667 - if (connectionStatus !== null) {
685 + if (connectionStatus !== null && !props.draftMode) {
686 return connectionStatus;
687 }
688 if (props.activePendingApproval !== null || props.activePendingUserInput !== null) {
@@ -789,8 +807,8 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
807 ) ||
808 (props.historyControls?.hasMoreHistory === true &&
809 props.selectedThread.latestUserMessageAt !== null);
792 - const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
793 - const composerOverlapHeight = composerChrome + composerBottomInset;
810 + const composerOverlapHeight =
811 + composerHeight ?? COMPOSER_COLLAPSED_CHROME + (hasSidebarTabBar ? 14 : 0) + composerBottomInset;
812 const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
813 useState<RuntimeRequestId | null>(null);
814 const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
@@ -873,7 +891,9 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
891 composerOverlayRef,
892 Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
893 -nativeInsetOvercount,
876 - Platform.OS === "ios" ? COMPOSER_TRANSITION_DURATION_MS : 0,
894 + // The composer already reports its animated height on each layout.
895 + // Easing these samples again makes the feed trail behind it.
896 + 0,
897 );
898 // Android lays the screen out below its opaque header and reports a zero
899 // header height, so the window height overstates the room by the header.
@@ -1207,6 +1227,7 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1227 hasStartedTurn: props.selectedThread.latestRun !== null,
1228 hasUserMessage,
1229 queuedMessageCount: props.selectedThreadQueueCount,
1230 + deliveryDeferred: props.connectionStateLabel !== "connected",
1231 }),
1232 );
1233 composerEditorRef.current?.blur();
@@ -1253,7 +1274,8 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1274 });
1275 };
1276
1256 - const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
1277 + const showScrollToEndButton =
1278 + !props.draftMode && contentPresentationKind === "ready" && !endFollowEnabled;
1279 const { themeAppearance } = useAppearancePreferences();
1280 const isDarkMode = themeAppearance === "dark";
1281
@@ -1293,9 +1315,19 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1315 <ThreadVisitWatermark
1316 environmentId={props.environmentId}
1317 selectedThread={props.selectedThread}
1296 - showContent={showContent}
1318 + showContent={showContent && !props.draftMode}
1319 />
1298 - {showContent ? (
1320 + {props.draftMode ? (
1321 + props.draftMode.content(
1322 + navigationHeaderHeight,
1323 + liveKeyboardHeight + estimatedOverlayHeight + 24,
1324 + screenAreaHeight -
1325 + navigationHeaderHeight -
1326 + liveKeyboardHeight -
1327 + estimatedOverlayHeight -
1328 + 24,
1329 + )
1330 + ) : showContent ? (
1331 <View
1332 style={{ flex: 1 }}
1333 onTouchStart={handleFeedTouchStart}
@@ -1393,7 +1425,6 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1425 coordinate space. Its top and height can then animate together
1426 instead of the auto-sized host jumping to Yoga's destination. */}
1427 <Animated.View
1396 - layout={COMPOSER_LAYOUT_TRANSITION}
1428 pointerEvents="box-none"
1429 style={[
1430 {
@@ -1603,7 +1634,9 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1634 </View>
1635 ) : (
1636 <>
1637 + {props.draftMode?.controls}
1638 <ThreadComposer
1639 + isDraft={Boolean(props.draftMode)}
1640 canOperateThread={props.canOperateThread}
1641 reportedModelSelection={reportedModelSelection}
1642 editorRef={composerEditorRef}
@@ -1629,11 +1662,14 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1662 // the draft: queueing them against a thread id the server may
1663 // still reject would strand them in the outbox.
1664 sendBlockedReason={
1632 - props.creationState?.kind === "preparing" &&
1633 - !props.creationState.serverOwned
1634 - ? "Starting the task…"
1635 - : null
1665 + props.draftMode
1666 + ? props.draftMode.sendBlockedReason
1667 + : props.creationState?.kind === "preparing" &&
1668 + !props.creationState.serverOwned
1669 + ? "Starting the task…"
1670 + : null
1671 }
1672 + interactionLocked={props.draftMode?.interactionLocked}
1673 draftKey={props.composerDraftKey ?? undefined}
1674 followUpBehavior={
1675 props.activePendingApprovals.length > 0 &&
@@ -1667,7 +1703,7 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1703 onUpdateModelSelection={props.onUpdateThreadModelSelection}
1704 onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
1705 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
1670 - onExpandedChange={setComposerExpanded}
1706 + onHeightChange={setComposerHeight}
1707 onEditorFocusChange={handleOwnedInputFocusChange}
1708 />
1709 </>
apps/mobile/src/features/threads/ThreadGitControls.tsx
+28 -6
@@ -86,6 +86,7 @@ export type ThreadGitMenuProps = {
86 readonly environmentId: EnvironmentId | string;
87 readonly threadId: ThreadId | string;
88 readonly currentBranch: string | null;
89 + readonly hasThread?: boolean;
90 readonly gitStatus: VcsStatusResult | null;
91 readonly gitOperationLabel: string | null;
92 readonly onOpenFilesInspector?: () => void;
@@ -190,6 +191,13 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {
191 !input.featureBranch &&
192 requiresDefaultBranchConfirmation(input.action, isDefaultRef)
193 ) {
194 + if (props.hasThread === false) {
195 + Dialog.alert(
196 + "Choose a feature branch",
197 + "Switch branches before publishing changes from this draft.",
198 + );
199 + return;
200 + }
201 navigation.navigate("GitConfirm", {
202 environmentId: String(environmentId),
203 threadId: String(threadId),
@@ -360,8 +368,11 @@ function useThreadGitHeaderActionItems(props: ThreadGitControlsProps): ThreadGit
368 type: "action",
369 },
370 {
363 - description: "Turn diffs and worktree changes",
364 - disabled: !model.isRepo,
371 + description:
372 + props.hasThread === false
373 + ? "Available after the first message"
374 + : "Turn diffs and worktree changes",
375 + disabled: !model.isRepo || props.hasThread === false,
376 icon: { name: "text.bubble", type: "sfSymbol" },
377 label: "Review changes",
378 onPress: model.openReview,
@@ -379,7 +390,11 @@ function useThreadGitHeaderActionItems(props: ThreadGitControlsProps): ThreadGit
390 ]
391 : []),
392 {
382 - description: "Commit, files, branches",
393 + description:
394 + props.hasThread === false
395 + ? "Available after the first message"
396 + : "Commit, files, branches",
397 + disabled: props.hasThread === false,
398 icon: { name: "ellipsis", type: "sfSymbol" },
399 label: "More",
400 onPress: model.openGitInspector,
@@ -540,15 +555,22 @@ function threadGitMenuDefinition(
555 id: "git-review",
556 title: "Review changes",
557 icon: "text.bubble",
543 - disabled: !model.isRepo,
544 - subtitle: "Turn diffs and worktree changes",
558 + disabled: !model.isRepo || props.hasThread === false,
559 + subtitle:
560 + props.hasThread === false
561 + ? "Available after the first message"
562 + : "Turn diffs and worktree changes",
563 onPress: model.openReview,
564 },
565 {
566 id: "git-more",
567 title: "More",
568 icon: "ellipsis",
551 - subtitle: "Commit, files, branches",
569 + disabled: props.hasThread === false,
570 + subtitle:
571 + props.hasThread === false
572 + ? "Available after the first message"
573 + : "Commit, files, branches",
574 onPress: model.openGitInspector,
575 },
576 ],
apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+21 -4
@@ -1,3 +1,4 @@
1 +import { useActiveNewTask } from "../../state/active-new-task";
2 import { ThreadUndoNotice } from "../home/ThreadUndoNotice";
3 import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";
4 import { resolveScratchProjectScopeKey } from "@t3tools/client-runtime/state/project-grouping";
@@ -11,7 +12,8 @@ import {
12 threadSearchMatchKey,
13 type EnvironmentThreadSearchMatch,
14 } from "@t3tools/client-runtime/state/thread-search";
14 -import { LegendList } from "@legendapp/list/react-native";
15 +import { AnimatedLegendList } from "@legendapp/list/reanimated";
16 +import { THREAD_SIDEBAR_ROW_LAYOUT } from "./threadListAnimations";
17 import type { MenuAction } from "@react-native-menu/menu";
18 import { useAtomValue } from "@effect/atom-react";
19 import { useEffect, useMemo, useRef, useState } from "react";
@@ -156,6 +158,7 @@ function ThreadNavigationSidebarPane(
158 regenerateThreadTitle,
159 } = useThreadListActions();
160 const pendingTasks = usePendingNewTasks();
161 + const activeNewTask = useActiveNewTask();
162 const queuedThreadKeys = useQueuedThreadKeys();
163 const { confirmDeletePendingTask } = usePendingTaskListActions();
164 const environments = Object.values(savedConnectionsById)
@@ -527,6 +530,7 @@ function ThreadNavigationSidebarPane(
530 // clock deliberately stays out: its per-row text lives on the items, so a
531 // tick only re-renders rows whose displayed text actually moved.
532 const listExtraData = {
533 + activeNewTask,
534 selectedThreadKey: props.selectedThreadKey ?? "",
535 projectByKey,
536 projectTitleByProjectKey,
@@ -573,6 +577,14 @@ function ThreadNavigationSidebarPane(
577 return (
578 <ThreadListV2PendingRow
579 pendingTask={item.pendingTask}
580 + selected={
581 + activeNewTask?.pendingKey === item.pendingTask.key ||
582 + (item.pendingTask.kind === "pending" &&
583 + scopedThreadKey(
584 + item.pendingTask.environmentId,
585 + item.pendingTask.message.threadId,
586 + ) === props.selectedThreadKey)
587 + }
588 project={projectByKey.get(pendingScopeKey) ?? null}
589 projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}
590 environmentLabel={
@@ -625,7 +637,10 @@ function ThreadNavigationSidebarPane(
637 )}
638 searchQuery={props.searchQuery}
639 pane="sidebar"
628 - selected={scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey}
640 + selected={
641 + !activeNewTask &&
642 + scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
643 + }
644 fullSwipeWidth={props.width - 20}
645 onSelectThread={handleSelectThread}
646 onOpenThreadPullRequests={handleOpenThreadPullRequests}
@@ -771,7 +786,8 @@ function ThreadNavigationSidebarPane(
786 <View className="flex-1">
787 <SwipeableScrollGateProvider enabled={swipeEnabled}>
788 <GestureDetector gesture={sidebarScrollGesture}>
774 - <LegendList
789 + <AnimatedLegendList
790 + itemLayoutAnimation={THREAD_SIDEBAR_ROW_LAYOUT}
791 data={listItems}
792 drawDistance={500}
793 estimatedItemSize={64}
@@ -839,7 +855,8 @@ function ThreadNavigationSidebarPane(
855 ) : (
856 <SwipeableScrollGateProvider enabled={swipeEnabled}>
857 <GestureDetector gesture={sidebarScrollGesture}>
842 - <LegendList
858 + <AnimatedLegendList
859 + itemLayoutAnimation={THREAD_SIDEBAR_ROW_LAYOUT}
860 data={listItems}
861 drawDistance={500}
862 estimatedItemSize={64}
apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+56 -39
@@ -28,7 +28,7 @@ import {
28 projectScriptTerminalInput,
29 resolveProjectScripts,
30 } from "@t3tools/shared/projectScripts";
31 -import { Platform, ScrollView, View } from "react-native";
31 +import { Platform, ScrollView } from "react-native";
32 import { useSafeAreaInsets } from "react-native-safe-area-context";
33 import { useConnectionsReady } from "../../state/workspace";
34 import { useEnvironmentShellReadiness } from "../../state/shell";
@@ -64,7 +64,10 @@ import {
64 stagePendingTerminalLaunch,
65 } from "../terminal/terminalLaunchContext";
66 import { terminalDebugLog } from "../terminal/terminalDebugLog";
67 -import { ThreadDetailScreen, type ThreadDetailScreenProps } from "./ThreadDetailScreen";
67 +import type { ThreadDetailScreenProps } from "./ThreadDetailScreen";
68 +import { ThreadScreenBinding, ThreadScreenFallback, ThreadScreenHost } from "./ThreadScreenHost";
69 +import { draftRouteIdentity } from "./thread-route-state";
70 +import { NewTaskDraftRouteScreen, type NewTaskDraftRouteParams } from "./NewTaskDraftRouteScreen";
71 import { GitOverviewSheet } from "./git/GitOverviewSheet";
72 import { useAtomCommand } from "../../state/use-atom-command";
73 import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
@@ -110,19 +113,12 @@ function firstRouteParam(value: string | string[] | undefined): string | null {
113 return first === undefined || first.trim().length === 0 ? null : first;
114 }
115
113 -function ThreadPane(props: { readonly children: ReactNode }) {
114 - return (
115 - <View className="flex-1 bg-screen android:overflow-hidden android:rounded-t-[28px] android:bg-thread-canvas">
116 - {props.children}
117 - </View>
118 - );
119 -}
120 -
116 function ThreadRouteFallbackLayout(props: { readonly children: ReactNode }) {
117 const goBack = useWorkspaceBackNavigation("threads");
118 const { layout } = useAdaptiveWorkspaceLayout();
119 const { themeVariables } = useAppearancePreferences();
125 - if (Platform.OS !== "android") return props.children;
120 + if (Platform.OS !== "android")
121 + return <ThreadScreenFallback>{props.children}</ThreadScreenFallback>;
122
123 return (
124 <>
@@ -132,7 +128,7 @@ function ThreadRouteFallbackLayout(props: { readonly children: ReactNode }) {
128 onBack={layout.usesSplitView ? undefined : goBack}
129 hideBottomBorder
130 />
135 - <ThreadPane>{props.children}</ThreadPane>
131 + <ThreadScreenFallback>{props.children}</ThreadScreenFallback>
132 </>
133 );
134 }
@@ -150,8 +146,9 @@ function OpeningThreadLoadingScreen() {
146 }
147
148 type ThreadRouteScreenRouteProps = StaticScreenProps<{
153 - readonly environmentId: string;
154 - readonly threadId: string;
149 + readonly environmentId?: string;
150 + readonly threadId?: string;
151 + readonly draft?: NewTaskDraftRouteParams;
152 readonly prompt?: string | string[];
153 }>;
154
@@ -188,11 +185,26 @@ function ThreadUnavailableScreen(props: {
185 }
186
187 export function ThreadRouteScreen(props: ThreadRouteScreenProps) {
188 + return (
189 + <ThreadScreenHost>
190 + {props.route.params?.draft ? (
191 + <NewTaskDraftRouteScreen
192 + key={draftRouteIdentity(props.route.params.draft)}
193 + route={{ ...props.route, params: props.route.params.draft }}
194 + />
195 + ) : (
196 + <LiveThreadRouteController {...props} />
197 + )}
198 + </ThreadScreenHost>
199 + );
200 +}
201 +
202 +function LiveThreadRouteController(props: ThreadRouteScreenProps) {
203 useAndroidWorkspaceBack("threads");
204 const connectionsReady = useConnectionsReady();
205 const { connectionState } = useRemoteConnectionStatus();
206 const { selectedThread } = useThreadSelection();
195 - const params = props.route.params;
207 + const params = props.route.params ?? {};
208 const environmentIdRaw = firstRouteParam(params.environmentId);
209 const threadIdRaw = firstRouteParam(params.threadId);
210 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
@@ -349,7 +361,7 @@ function ThreadRouteContent(
361 threadId: mergeBackTargetThreadId,
362 });
363 };
352 - const params = props.route.params;
364 + const params = props.route.params ?? {};
365 const environmentIdRaw = firstRouteParam(params.environmentId);
366 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
367 const threadId = firstRouteParam(params.threadId);
@@ -517,7 +529,7 @@ function ThreadRouteContent(
529 <GitOverviewSheet
530 headerInset={inspectorHeaderInset}
531 presentation="inspector"
520 - route={{ params: props.route.params }}
532 + route={{ params: { environmentId: environmentId!, threadId: threadId! } }}
533 />
534 );
535 const FilesInspector = () =>
@@ -750,9 +762,8 @@ function ThreadRouteContent(
762 }
763 clearPendingThreadCreationOutcome(routeThreadIdentity);
764 navigation.dispatch(
753 - StackActions.replace("NewTaskSheet", {
754 - screen: "NewTaskDraft",
755 - params: {
765 + StackActions.replace("Thread", {
766 + draft: {
767 draftId: restoredNewTaskDraftKey(creation.messageId),
768 environmentId: String(creation.environmentId),
769 projectId: String(creation.creation.projectId),
@@ -886,8 +897,25 @@ function ThreadRouteContent(
897 onOpenPullRequest={openPullRequest}
898 />
899
889 - <ThreadPane>
890 - <ThreadDetailScreen
900 + <>
901 + <ThreadScreenBinding
902 + header={
903 + <ThreadHeader
904 + title={selectedThread.title}
905 + subtitle={headerSubtitle}
906 + headerColor={headerColor}
907 + usesNativeHeaderGlass={usesNativeHeaderGlass}
908 + gitControls={threadGitControlProps}
909 + hasThreadCwd={selectedThreadCwd !== null}
910 + hasWorkspaceRoot={Boolean(selectedThreadProject?.workspaceRoot)}
911 + fileInspectorSupported={fileInspector.supported}
912 + inspectorMode={inspectorMode}
913 + onToggleInspector={handleToggleInspector}
914 + onOpenGitInspector={handleOpenGitInspector}
915 + onOpenFilesInspector={handleOpenFilesInspector}
916 + onReturnToThread={props.onReturnToThread}
917 + />
918 + }
919 canOperateThread={canOperateThread}
920 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
921 selectedThreadDetailRef={selectedThreadDetailRef}
@@ -954,7 +982,11 @@ function ThreadRouteContent(
982 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
983 threadCwd={selectedThreadCwd}
984 selectedThreadQueueCount={composer.selectedThreadQueueCount}
957 - queuedMessages={composer.selectedThreadQueuedMessages}
985 + queuedMessages={
986 + selectedThreadCreation && selectedThreadCreation.outcome?.kind !== "delivered"
987 + ? [selectedThreadCreation.message, ...composer.selectedThreadQueuedMessages]
988 + : composer.selectedThreadQueuedMessages
989 + }
990 dispatchingMessageId={composer.dispatchingQueuedMessageId}
991 layoutVariant={layout.variant}
992 usesAutomaticContentInsets={usesNativeHeaderGlass}
@@ -980,28 +1012,13 @@ function ThreadRouteContent(
1012 onSubmitUserInput={requests.onSubmitUserInput}
1013 onDismissUserInput={requests.onDismissUserInput}
1014 />
983 - </ThreadPane>
1015 + </>
1016 </>
1017 );
1018
1019 return (
1020 <>
1021 {activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
990 - <ThreadHeader
991 - title={selectedThread.title}
992 - subtitle={headerSubtitle}
993 - headerColor={headerColor}
994 - usesNativeHeaderGlass={usesNativeHeaderGlass}
995 - gitControls={threadGitControlProps}
996 - hasThreadCwd={selectedThreadCwd !== null}
997 - hasWorkspaceRoot={Boolean(selectedThreadProject?.workspaceRoot)}
998 - fileInspectorSupported={fileInspector.supported}
999 - inspectorMode={inspectorMode}
1000 - onToggleInspector={handleToggleInspector}
1001 - onOpenGitInspector={handleOpenGitInspector}
1002 - onOpenFilesInspector={handleOpenFilesInspector}
1003 - onReturnToThread={props.onReturnToThread}
1004 - />
1022
1023 {renderThreadRouteBody()}
1024 </>
apps/mobile/src/features/threads/ThreadScreenHost.tsx new
+77
@@ -0,0 +1,77 @@
1 +import {
2 + createContext,
3 + useContext,
4 + useLayoutEffect,
5 + useState,
6 + useSyncExternalStore,
7 + type ReactNode,
8 +} from "react";
9 +import { View } from "react-native";
10 +import { ThreadDetailScreen, type ThreadDetailScreenProps } from "./ThreadDetailScreen";
11 +
12 +type ThreadScreenContent =
13 + | { readonly props: ThreadDetailScreenProps }
14 + | { readonly fallback: ReactNode };
15 +
16 +function createThreadScreenStore() {
17 + let current: ThreadScreenContent | null = null;
18 + const listeners = new Set<() => void>();
19 + return {
20 + getSnapshot: () => current,
21 + subscribe: (listener: () => void) => {
22 + listeners.add(listener);
23 + return () => {
24 + listeners.delete(listener);
25 + };
26 + },
27 + publish: (content: ThreadScreenContent) => {
28 + current = content;
29 + for (const listener of listeners) listener();
30 + },
31 + };
32 +}
33 +const ThreadScreenContext = createContext<ReturnType<typeof createThreadScreenStore> | null>(null);
34 +
35 +function ThreadScreenOutlet() {
36 + const store = useContext(ThreadScreenContext)!;
37 + const content = useSyncExternalStore(store.subscribe, store.getSnapshot);
38 + if (content === null) return null;
39 + return "props" in content ? (
40 + <>
41 + {content.props.header}
42 + <ThreadDetailScreen {...content.props} />
43 + </>
44 + ) : (
45 + content.fallback
46 + );
47 +}
48 +
49 +// Controllers can change from draft to live without replacing the native screen,
50 +// the keyboard host, or the editor. Publish before paint to avoid an intermediate frame.
51 +export function ThreadScreenHost({ children }: { readonly children: ReactNode }) {
52 + const [store] = useState(createThreadScreenStore);
53 + return (
54 + <ThreadScreenContext.Provider value={store}>
55 + {children}
56 + <View className="flex-1 bg-screen android:overflow-hidden android:rounded-t-[28px] android:bg-thread-canvas">
57 + <ThreadScreenOutlet />
58 + </View>
59 + </ThreadScreenContext.Provider>
60 + );
61 +}
62 +
63 +export function ThreadScreenBinding(props: ThreadDetailScreenProps) {
64 + const store = useContext(ThreadScreenContext)!;
65 + useLayoutEffect(() => {
66 + store.publish({ props });
67 + });
68 + return null;
69 +}
70 +
71 +export function ThreadScreenFallback({ children }: { readonly children: ReactNode }) {
72 + const store = useContext(ThreadScreenContext)!;
73 + useLayoutEffect(() => {
74 + store.publish({ fallback: children });
75 + });
76 + return null;
77 +}
apps/mobile/src/features/threads/composerSendPresentation.test.ts
+7
@@ -11,6 +11,13 @@ const idle = {
11 } as const;
12
13 describe("resolveComposerSendPresentation", () => {
14 + it("shows the outbox action when delivery is deferred", () => {
15 + const presentation = resolveComposerSendPresentation({ ...idle, deliveryDeferred: true });
16 + expect(presentation.label).toBe("Queue");
17 + expect(presentation.icon).toBe("tray.and.arrow.up");
18 + expect(resolveComposerSendPresentation(idle).icon).toBe("arrow.up");
19 + });
20 +
21 it("never promises steering the provider cannot do", () => {
22 const presentation = resolveComposerSendPresentation({
23 ...idle,
apps/mobile/src/features/threads/composerSendPresentation.ts
+7 -2
@@ -7,7 +7,12 @@ import type { FollowUpBehavior } from "../../lib/followUpBehavior";
7
8 export interface ComposerSendPresentation {
9 readonly label: string;
10 - readonly icon: "arrow.up" | "checkmark" | "list.number" | "arrow.turn.left.up";
10 + readonly icon:
11 + | "arrow.up"
12 + | "tray.and.arrow.up"
13 + | "checkmark"
14 + | "list.number"
15 + | "arrow.turn.left.up";
16 readonly action: ActiveTurnComposerAction | null;
17 readonly alternate: ActiveTurnComposerAction | null;
18 readonly offersFollowUpChoice: boolean;
@@ -38,7 +43,7 @@ export function resolveComposerSendPresentation(input: {
43 if (!input.running) {
44 return {
45 label: input.deliveryDeferred ? "Queue" : "Send",
41 - icon: "arrow.up",
46 + icon: input.deliveryDeferred ? "tray.and.arrow.up" : "arrow.up",
47 action: null,
48 alternate: null,
49 offersFollowUpChoice: false,
apps/mobile/src/features/threads/draft-thread-shell.ts new
+64
@@ -0,0 +1,64 @@
1 +import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
2 +import type {
3 + EnvironmentId,
4 + ThreadId,
5 + ProjectId,
6 + ModelSelection,
7 + RuntimeMode,
8 + ProviderInteractionMode,
9 +} from "@t3tools/contracts";
10 +import * as DateTime from "effect/DateTime";
11 +
12 +export function draftThreadShell(input: {
13 + readonly environmentId: EnvironmentId;
14 + readonly threadId: ThreadId;
15 + readonly projectId: ProjectId;
16 + readonly modelSelection: ModelSelection;
17 + readonly runtimeMode: RuntimeMode;
18 + readonly interactionMode: ProviderInteractionMode;
19 + readonly branch: string | null;
20 + readonly worktreePath: string | null;
21 + readonly createdAt: string;
22 +}) {
23 + const timestamp = DateTime.makeUnsafe(input.createdAt);
24 + return presentThreadShell(input.environmentId, {
25 + id: input.threadId,
26 + projectId: input.projectId,
27 + title: "New thread",
28 + providerInstanceId: input.modelSelection.instanceId,
29 + modelSelection: input.modelSelection,
30 + runtimeMode: input.runtimeMode,
31 + interactionMode: input.interactionMode,
32 + branch: input.branch,
33 + pullRequests: [],
34 + worktreePath: input.worktreePath,
35 + linkedPullRequest: null,
36 + branchPullRequest: null,
37 + lineage: { rootThreadId: input.threadId, parentThreadId: null, relationshipToParent: null },
38 + forkedFrom: null,
39 + createdBy: "user",
40 + creationSource: "mobile",
41 + activeProviderThreadId: null,
42 + latestRunId: null,
43 + activeRunId: null,
44 + status: "idle",
45 + pendingRuntimeRequest: null,
46 + latestVisibleMessage: null,
47 + latestUserMessageAt: timestamp,
48 + hasActionableProposedPlan: false,
49 + itemCount: 0,
50 + visibleItemCount: 0,
51 + createdAt: timestamp,
52 + updatedAt: timestamp,
53 + archivedAt: null,
54 + settledOverride: null,
55 + settledAt: null,
56 + unsettledAt: null,
57 + snoozedUntil: null,
58 + snoozedAt: null,
59 + pinnedAt: null,
60 + pinOrderKey: null,
61 + activeOrderKey: null,
62 + deletedAt: null,
63 + });
64 +}
apps/mobile/src/features/threads/new-task-flow-provider.tsx
+41 -7
@@ -1,8 +1,9 @@
1 +import { ActiveNewTaskContext } from "../../state/active-new-task";
2 import * as Dialog from "../../components/ui/Dialog";
3 import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
4 import { useEnvironmentPresentation } from "../../state/presentation";
5 import { environmentSession } from "../../state/session";
5 -import React, { useEffect, useRef, useState } from "react";
6 +import React, { useCallback, useEffect, useRef, useState } from "react";
7
8 import type {
9 EnvironmentId,
@@ -165,6 +166,7 @@ export function branchBadgeLabel(input: {
166 }
167
168 type NewTaskFlowContextValue = {
169 + readonly activeNewTask: { readonly pendingKey: string | null } | null;
170 readonly projectScopes: ReadonlyArray<HomeProjectScope>;
171 readonly selectedEnvironmentId: EnvironmentId | null;
172 readonly selectedProjectKey: string | null;
@@ -255,7 +257,13 @@ type NewTaskFlowContextValue = {
257
258 const NewTaskFlowContext = React.createContext<NewTaskFlowContextValue | null>(null);
259
258 -export function NewTaskFlowProvider(props: React.PropsWithChildren) {
260 +export function NewTaskFlowProvider(
261 + props: React.PropsWithChildren<{
262 + active?: boolean;
263 + routeDraftId?: string;
264 + routePendingTaskId?: string;
265 + }>,
266 +) {
267 const projects = useProjects();
268 const threads = useThreadShells();
269 const { savedConnectionsById } = useSavedRemoteConnections();
@@ -294,7 +302,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
302 const editingPendingTaskRef = useRef<QueuedThreadMessage | null>(null);
303 const editingRevisionRef = useRef(Promise.resolve(0));
304
297 - const reset = () => {
305 + const reset = useCallback(() => {
306 setSelectedEnvironmentId(null);
307 setSelectedProjectKey(null);
308 setActiveDraftKey(null);
@@ -311,7 +319,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
319 }
320 releaseEditingQueuedMessage(editing.messageId);
321 }
314 - };
322 + }, []);
323
324 const projectsForEnvironment = pipe(
325 projects,
@@ -425,7 +433,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
433 ? activeDraftKey
434 : null;
435 useEffect(() => {
428 - if (activeDraftKey !== null || editingPendingTask !== null || selectedProject === null) {
436 + if (
437 + props.active === false ||
438 + activeDraftKey !== null ||
439 + editingPendingTask !== null ||
440 + selectedProject === null
441 + ) {
442 return;
443 }
444 setActiveDraftKey(
@@ -434,7 +447,23 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
447 projectId: selectedProject.id,
448 }),
449 );
437 - }, [activeDraftKey, editingPendingTask, selectedProject]);
450 + }, [activeDraftKey, editingPendingTask, selectedProject, props.active]);
451 + const activePendingKey =
452 + props.active === false
453 + ? null
454 + : props.routePendingTaskId
455 + ? `pending-task:${props.routePendingTaskId}`
456 + : props.routeDraftId
457 + ? `draft-task:${props.routeDraftId}`
458 + : editingPendingTask
459 + ? `pending-task:${editingPendingTask.messageId}`
460 + : selectedProjectDraftKey
461 + ? `draft-task:${selectedProjectDraftKey}`
462 + : null;
463 + const activeNewTask = React.useMemo(
464 + () => (props.active === false ? null : { pendingKey: activePendingKey }),
465 + [props.active, activePendingKey],
466 + );
467 const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
468 const prompt = selectedProjectDraft.text;
469 const attachments = selectedProjectDraft.attachments;
@@ -1143,6 +1172,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
1172 );
1173
1174 const value = {
1175 + activeNewTask,
1176 projectScopes,
1177 selectedEnvironmentId,
1178 selectedProjectKey,
@@ -1209,7 +1239,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
1239 setExpandedProvider,
1240 } satisfies NewTaskFlowContextValue;
1241
1212 - return <NewTaskFlowContext.Provider value={value}>{props.children}</NewTaskFlowContext.Provider>;
1242 + return (
1243 + <ActiveNewTaskContext value={activeNewTask}>
1244 + <NewTaskFlowContext.Provider value={value}>{props.children}</NewTaskFlowContext.Provider>
1245 + </ActiveNewTaskContext>
1246 + );
1247 }
1248
1249 export function useNewTaskFlow() {
apps/mobile/src/features/threads/new-task-project-selection.test.ts
+26
@@ -4,6 +4,7 @@ import { describe, expect, it } from "vite-plus/test";
4 import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
5 import type { HomeProjectScope } from "../home/homeThreadList";
6 import {
7 + newTaskDestination,
8 resolveDraftProjectSelection,
9 resolveEnvironmentProjectMatch,
10 } from "./new-task-project-selection";
@@ -112,3 +113,28 @@ describe("resolveDraftProjectSelection", () => {
113 });
114 });
115 });
116 +
117 +describe("newTaskDestination", () => {
118 + it("opens the current thread's project directly in split view", () => {
119 + const projects = [makeProject("first"), makeProject("current", "other-environment")];
120 + expect(newTaskDestination(true, projects, projects[1], "request")).toEqual({
121 + draft: { requestId: "request", environmentId: "other-environment", projectId: "current" },
122 + });
123 + });
124 + it("uses an available project when split view has no current project", () => {
125 + expect(newTaskDestination(true, [makeProject("first")], undefined, "request")).toEqual({
126 + draft: { requestId: "request", environmentId: "environment", projectId: "first" },
127 + });
128 + });
129 + it("keeps the picker when there are no projects", () => {
130 + expect(newTaskDestination(true, [], undefined, "request")).toEqual({
131 + draft: { requestId: "request" },
132 + });
133 + });
134 + it("opens the same draft route in compact view", () => {
135 + const project = makeProject("current");
136 + expect(newTaskDestination(false, [project], project, "request")).toEqual({
137 + draft: { requestId: "request", environmentId: "environment", projectId: "current" },
138 + });
139 + });
140 +});
apps/mobile/src/features/threads/new-task-project-selection.ts
+23
@@ -105,3 +105,26 @@ export function resolveDraftProjectSelection(
105 const onlyProject = getOnlySelectableProject(projectScopes);
106 return onlyProject ? { kind: "select", project: onlyProject } : { kind: "pick" };
107 }
108 +
109 +export function newTaskDestination(
110 + _usesSplitView: boolean,
111 + projects: ReadonlyArray<EnvironmentProject>,
112 + currentProject: Pick<EnvironmentProject, "environmentId" | "id"> | undefined,
113 + requestId: string,
114 +) {
115 + const project =
116 + projects.find(
117 + (candidate) =>
118 + candidate.environmentId === currentProject?.environmentId &&
119 + candidate.id === currentProject.id,
120 + ) ?? projects[0];
121 + return project
122 + ? {
123 + draft: {
124 + requestId,
125 + environmentId: String(project.environmentId),
126 + projectId: String(project.id),
127 + },
128 + }
129 + : { draft: { requestId } };
130 +}
apps/mobile/src/features/threads/pending-thread-feed.test.ts
+19
@@ -4,6 +4,7 @@ import {
4 ComposerContextId,
5 EnvironmentId,
6 MessageId,
7 + ProjectId,
8 ThreadId,
9 } from "@t3tools/contracts";
10 import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
@@ -20,6 +21,24 @@ const pending = (id: string): QueuedThreadMessage => ({
21 });
22
23 describe("pending timeline messages", () => {
24 + it("marks the synthetic creation prompt pending without duplicating it", () => {
25 + const queued = {
26 + ...pending("creation"),
27 + creation: {
28 + projectId: ProjectId.make("project"),
29 + workspaceMode: "local" as const,
30 + branch: "main",
31 + worktreePath: null,
32 + },
33 + };
34 + const prompt = appendPendingThreadMessages([], [], [queued])[0]!;
35 + const synthetic = { ...prompt, pendingMessage: undefined };
36 + const result = appendPendingThreadMessages([synthetic], [synthetic], [queued]);
37 + expect(result).toHaveLength(1);
38 + expect(result[0]?.pendingMessage).toEqual(queued);
39 + expect(result[0]?.acknowledged).toBe(false);
40 + });
41 +
42 it("retains context records while a message is waiting for delivery", () => {
43 const record = {
44 version: 1 as const,
apps/mobile/src/features/threads/pending-thread-feed.ts
+6 -1
@@ -16,7 +16,12 @@ export function appendPendingThreadMessages(
16 feed.flatMap((entry) => (entry.type === "message" ? [entry.message.id] : [])),
17 );
18 return [
19 - ...presentedFeed,
19 + ...presentedFeed.map((entry): PendingThreadFeedEntry => {
20 + const pendingMessage = queuedMessages.find(
21 + (message) => message.creation !== undefined && message.messageId === entry.id,
22 + );
23 + return pendingMessage ? { ...entry, pendingMessage, acknowledged: false } : entry;
24 + }),
25 ...queuedMessages
26 .filter((message) => !deliveredIds.has(message.messageId))
27 .map((pendingMessage): PendingThreadFeedEntry => ({
apps/mobile/src/features/threads/thread-feed-live-follow.test.ts
+17
@@ -77,6 +77,19 @@ describe("tool-group append following", () => {
77 });
78
79 describe("resolveThreadFeedSubmissionAnchor", () => {
80 + it("keeps an offline first message at the end", () => {
81 + expect(
82 + resolveThreadFeedSubmissionAnchor({
83 + currentAnchorMessageId: null,
84 + submittedMessageId: "offline-first",
85 + hasStartedTurn: false,
86 + hasUserMessage: false,
87 + queuedMessageCount: 0,
88 + deliveryDeferred: true,
89 + }),
90 + ).toBeNull();
91 + });
92 +
93 it("anchors the first user message in a thread", () => {
94 expect(
95 resolveThreadFeedSubmissionAnchor({
@@ -84,6 +97,7 @@ describe("resolveThreadFeedSubmissionAnchor", () => {
97 submittedMessageId: "first-message",
98 hasStartedTurn: false,
99 hasUserMessage: false,
100 + deliveryDeferred: false,
101 queuedMessageCount: 0,
102 }),
103 ).toBe("first-message");
@@ -96,6 +110,7 @@ describe("resolveThreadFeedSubmissionAnchor", () => {
110 submittedMessageId: "second-message",
111 hasStartedTurn: false,
112 hasUserMessage: false,
113 + deliveryDeferred: false,
114 queuedMessageCount: 1,
115 }),
116 ).toBe("first-message");
@@ -108,6 +123,7 @@ describe("resolveThreadFeedSubmissionAnchor", () => {
123 submittedMessageId: "second-message",
124 hasStartedTurn: false,
125 hasUserMessage: true,
126 + deliveryDeferred: false,
127 queuedMessageCount: 0,
128 }),
129 ).toBeNull();
@@ -121,6 +137,7 @@ describe("resolveThreadFeedSubmissionAnchor", () => {
137 submittedMessageId: "second-message",
138 hasStartedTurn: true,
139 hasUserMessage: false,
140 + deliveryDeferred: false,
141 queuedMessageCount: 0,
142 }),
143 ).toBeNull();
apps/mobile/src/features/threads/thread-feed-live-follow.ts
+2 -1
@@ -55,8 +55,9 @@ export function resolveThreadFeedSubmissionAnchor<AnchorId>(input: {
55 readonly hasStartedTurn: boolean;
56 readonly hasUserMessage: boolean;
57 readonly queuedMessageCount: number;
58 + readonly deliveryDeferred: boolean;
59 }): AnchorId | null {
59 - if (input.hasStartedTurn || input.hasUserMessage) {
60 + if (input.deliveryDeferred || input.hasStartedTurn || input.hasUserMessage) {
61 return null;
62 }
63
apps/mobile/src/features/threads/thread-header-appearance.ts new
+21
@@ -0,0 +1,21 @@
1 +import { Platform } from "react-native";
2 +import {
3 + nativeHeaderScrollEdgeEffects,
4 + type AppNativeStackNavigationOptions,
5 +} from "../../native/StackHeader";
6 +
7 +export function threadHeaderAppearance(
8 + usesNativeHeaderGlass: boolean,
9 +): AppNativeStackNavigationOptions {
10 + return {
11 + headerShown: true,
12 + headerTransparent: usesNativeHeaderGlass,
13 + headerStyle: usesNativeHeaderGlass ? { backgroundColor: "transparent" } : undefined,
14 + headerShadowVisible: false,
15 + scrollEdgeEffects: usesNativeHeaderGlass
16 + ? nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version)
17 + : undefined,
18 + headerTitleStyle: usesNativeHeaderGlass ? { fontSize: 17, fontWeight: "800" } : undefined,
19 + contentStyle: undefined,
20 + };
21 +}
apps/mobile/src/features/threads/thread-list-v2-items.tsx
+7 -14
@@ -146,8 +146,6 @@ const LEGACY_MENU_ACTIONS: MenuAction[] = [
146 { id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
147 ];
148
149 -const SIDEBAR_V2_ROW_RADIUS = 12;
150 -
149 function ThreadListV2Section(props: {
150 readonly label: string;
151 readonly pane?: "screen" | "sidebar";
@@ -316,6 +314,7 @@ const DRAFT_TASK_MENU_ACTIONS: MenuAction[] = [
314
315 export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props: {
316 readonly pendingTask: PendingNewTask;
317 + readonly selected?: boolean;
318 readonly project: EnvironmentProject | null;
319 readonly projectTitle?: string;
320 readonly environmentLabel: string | null;
@@ -336,7 +335,7 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
335 const dormant = useSwipeRowDormant(props.activationKey);
336 const theme = useUniwindTheme();
337 const sidebarPane = props.pane === "sidebar";
339 - const rowAppearance = getThreadListV2RowAppearance(theme, sidebarPane, false);
338 + const rowAppearance = getThreadListV2RowAppearance(theme, sidebarPane, props.selected ?? false);
339 const isDraft = pendingTask.kind === "draft";
340 const deleteLabel = isDraft ? "Discard" : "Delete";
341 const handleDelete = useCallback(
@@ -497,19 +496,13 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
496 }
497 accessibilityLabel={pendingTask.title}
498 accessibilityRole="button"
499 + accessibilityState={{ selected: props.selected ?? false }}
500 key={pendingTask.key}
501 - className={sidebarPane ? "bg-drawer" : "bg-screen"}
502 - interactionClassName={sidebarPane ? "bg-thread-hover" : "bg-row-hover"}
501 + className={rowAppearance.className}
502 + interactionClassName={rowAppearance.interactionClassName}
503 + interactionOpacity={rowAppearance.interactionOpacity}
504 onPress={() => onSelectPendingTask(pendingTask)}
504 - style={
505 - sidebarPane
506 - ? {
507 - borderRadius: SIDEBAR_V2_ROW_RADIUS,
508 - paddingHorizontal: 12,
509 - paddingVertical: 10,
510 - }
511 - : undefined
512 - }
505 + style={rowAppearance.cardStyle}
506 >
507 {sidebarPane ? (
508 rowContent
apps/mobile/src/features/threads/thread-route-state.test.ts new
+116
@@ -0,0 +1,116 @@
1 +import * as NodeModule from "node:module";
2 +import { describe, expect, it } from "vite-plus/test";
3 +import {
4 + draftRouteIdentity,
5 + isDraftThreadRoute,
6 + submittedThreadParams,
7 +} from "./thread-route-state";
8 +
9 +const requireNavigation = NodeModule.createRequire(
10 + NodeModule.createRequire(import.meta.url).resolve("@react-navigation/native/package.json"),
11 +);
12 +const { StackRouter, CommonActions, StackActions } = requireNavigation(
13 + "@react-navigation/routers",
14 +) as {
15 + StackRouter: typeof import("@react-navigation/native").StackRouter;
16 + CommonActions: typeof import("@react-navigation/native").CommonActions;
17 + StackActions: typeof import("@react-navigation/native").StackActions;
18 +};
19 +
20 +describe("draft thread handoff", () => {
21 + it("submits in the existing route and stops suppressing the live thread selection", () => {
22 + const router = StackRouter({});
23 + const options = { routeNames: ["Home", "Thread"], routeParamList: {}, routeGetIdList: {} };
24 + const initial = router.getInitialState(options);
25 + const draft = router.getStateForAction(
26 + initial,
27 + CommonActions.navigate("Thread", { draft: { projectId: "project" } }),
28 + options,
29 + )!;
30 + if (!draft || draft.stale !== false) throw new Error("Draft route was not initialized");
31 + expect(isDraftThreadRoute(draft.routes.at(-1))).toBe(true);
32 + const submitted = router.getStateForAction(
33 + draft,
34 + CommonActions.setParams(submittedThreadParams("environment", "thread")),
35 + options,
36 + )!;
37 + expect(submitted.routes.map((route) => route.key)).toEqual(
38 + draft.routes.map((route) => route.key),
39 + );
40 + expect(submitted.index).toBe(draft.index);
41 + expect(submitted.routes.at(-1)?.params).toEqual({
42 + draft: undefined,
43 + environmentId: "environment",
44 + threadId: "thread",
45 + });
46 + expect(isDraftThreadRoute(submitted.routes.at(-1))).toBe(false);
47 + });
48 +});
49 +
50 +describe("missing shared-content project recovery", () => {
51 + it("replaces the stale draft before selecting the replacement project", () => {
52 + const router = StackRouter({});
53 + const options = {
54 + routeNames: ["Home", "Thread", "NewTaskProject"],
55 + routeParamList: {},
56 + routeGetIdList: {},
57 + };
58 + const initial = router.getInitialState(options);
59 + const staleDraft = router.getStateForAction(
60 + initial,
61 + CommonActions.navigate("Thread", {
62 + draft: { environmentId: "environment", projectId: "deleted", incomingShareId: "share" },
63 + }),
64 + options,
65 + )!;
66 + if (staleDraft.stale !== false) throw new Error("Draft route was not initialized");
67 + const picker = router.getStateForAction(
68 + staleDraft,
69 + StackActions.replace("NewTaskProject", { incomingShareId: "share" }),
70 + options,
71 + )!;
72 + if (picker.stale !== false) throw new Error("Project picker was not initialized");
73 + expect(picker.routes.some(isDraftThreadRoute)).toBe(false);
74 + expect(picker.routes.at(-1)?.params).toEqual({ incomingShareId: "share" });
75 + const recovered = router.getStateForAction(
76 + picker,
77 + CommonActions.navigate("Thread", {
78 + draft: { environmentId: "environment", projectId: "replacement", incomingShareId: "share" },
79 + }),
80 + options,
81 + )!;
82 + expect(recovered.routes.filter(isDraftThreadRoute)).toHaveLength(1);
83 + expect(recovered.routes.at(-1)?.params).toEqual({
84 + draft: { environmentId: "environment", projectId: "replacement", incomingShareId: "share" },
85 + });
86 + });
87 +});
88 +
89 +describe("draft route identity", () => {
90 + it("changes when a reused Thread route selects another draft or starts a new one", () => {
91 + const draft = { environmentId: "env", projectId: "project", draftId: "a" };
92 + expect(draftRouteIdentity(draft)).not.toBe(draftRouteIdentity({ ...draft, draftId: "b" }));
93 + expect(draftRouteIdentity(draft)).not.toBe(
94 + draftRouteIdentity({ ...draft, draftId: undefined }),
95 + );
96 + expect(draftRouteIdentity(draft)).not.toBe(
97 + draftRouteIdentity({ ...draft, projectId: "other" }),
98 + );
99 + expect(draftRouteIdentity(draft)).not.toBe(
100 + draftRouteIdentity({ ...draft, incomingShareId: "share" }),
101 + );
102 + });
103 +
104 + it("normalizes link parameters without resetting for display metadata", () => {
105 + expect(
106 + draftRouteIdentity({ environmentId: ["env"], projectId: ["project"], title: "Old" }),
107 + ).toBe(draftRouteIdentity({ environmentId: "env", projectId: "project", title: "New" }));
108 + });
109 +});
110 +
111 +it("starts a fresh controller for repeated new-task requests in the same project", () => {
112 + const project = { environmentId: "env", projectId: "project" };
113 + expect(draftRouteIdentity({ ...project, requestId: "first" })).not.toBe(
114 + draftRouteIdentity({ ...project, requestId: "second" }),
115 + );
116 +});
apps/mobile/src/features/threads/thread-route-state.ts new
+43
@@ -0,0 +1,43 @@
1 +export type NewTaskDraftRouteParams = {
2 + readonly requestId?: string;
3 + readonly environmentId?: string | string[];
4 + readonly projectId?: string | string[];
5 + readonly branch?: string | null;
6 + readonly worktreePath?: string | null;
7 + readonly title?: string | string[];
8 + readonly cloning?: string | string[];
9 + readonly pendingTaskId?: string | string[];
10 + readonly draftId?: string | string[];
11 + readonly incomingShareId?: string | string[];
12 +};
13 +
14 +export function isDraftThreadRoute(
15 + route:
16 + | {
17 + readonly name: string;
18 + readonly params?: object;
19 + }
20 + | undefined,
21 +) {
22 + return (
23 + route?.name === "Thread" && Boolean((route.params as { draft?: unknown } | undefined)?.draft)
24 + );
25 +}
26 +
27 +export function submittedThreadParams(environmentId: string, threadId: string) {
28 + return { draft: undefined, environmentId, threadId };
29 +}
30 +
31 +export function draftRouteIdentity(draft: NewTaskDraftRouteParams): string {
32 + const first = (value: string | string[] | undefined) => (Array.isArray(value) ? value[0] : value);
33 + return JSON.stringify([
34 + draft.requestId,
35 + first(draft.pendingTaskId),
36 + first(draft.draftId),
37 + first(draft.environmentId),
38 + first(draft.projectId),
39 + draft.branch ?? null,
40 + draft.worktreePath ?? null,
41 + first(draft.incomingShareId),
42 + ]);
43 +}
apps/mobile/src/features/threads/threadListAnimations.ts new
+5
@@ -0,0 +1,5 @@
1 +import { LinearTransition, ReduceMotion } from "react-native-reanimated";
2 +
3 +export const THREAD_SIDEBAR_ROW_LAYOUT = LinearTransition.duration(180).reduceMotion(
4 + ReduceMotion.System,
5 +);
apps/mobile/src/features/threads/useThreadHeaderOptions.tsx
+10 -32
@@ -1,5 +1,7 @@
1 +import { useWorkspaceSidebarHeaderItem } from "../layout/useWorkspaceSidebarHeaderItem";
2 import { StackActions, useNavigation } from "@react-navigation/native";
3 import { useMemo } from "react";
4 +import { threadHeaderAppearance } from "./thread-header-appearance";
5 import { isDuoDevice } from "../../lib/device-type";
6 import type { AppNativeStackNavigationOptions } from "../../native/StackHeader";
7 import { useDeviceType } from "../../native/native-layout-metrics";
@@ -21,12 +23,14 @@ export function useThreadHeaderOptions(props: {
23 readonly usesNativeHeaderGlass: boolean;
24 readonly gitControls: Parameters<typeof ThreadGitControls>[0];
25 readonly onReturnToThread?: () => void;
26 + readonly draft?: boolean;
27 }) {
28 const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();
29 const deviceType = useDeviceType();
30 const usesDuoHeader = usesNativeWorkspaceColumns && isDuoDevice(deviceType);
31 const navigation = useNavigation();
29 - const { layout, panes, togglePrimarySidebar } = useAdaptiveWorkspaceLayout();
32 + const { layout, startNewTask } = useAdaptiveWorkspaceLayout();
33 + const sidebarHeaderItem = useWorkspaceSidebarHeaderItem();
34 const threadCenterHeaderItems = useThreadGitCenterHeaderItems(props.gitControls);
35 const compactRightHeaderItems = useThreadGitRightHeaderItems(props.gitControls);
36 const splitLeftHeaderItems = useMemo<NativeHeaderItems>(
@@ -50,41 +54,21 @@ export function useThreadHeaderOptions(props: {
54 }),
55 ]
56 : []),
53 - withNativeGlassHeaderItem({
54 - axisBehavior: usesNativeWorkspaceColumns ? "horizontalOnly" : undefined,
55 - accessibilityLabel: panes.primarySidebarVisible
56 - ? "Maximize content"
57 - : "Show thread sidebar",
58 - icon: {
59 - name: panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left",
60 - type: "sfSymbol" as const,
61 - },
62 - identifier: "thread-left-sidebar",
63 - label: panes.primarySidebarVisible ? "Maximize content" : "Show thread sidebar",
64 - onPress: togglePrimarySidebar,
65 - type: "button" as const,
66 - }),
67 - ...(!usesDuoHeader
57 + sidebarHeaderItem,
58 + ...(!usesDuoHeader && !props.draft
59 ? [
60 withNativeGlassHeaderItem({
61 accessibilityLabel: "New task",
62 icon: { name: "square.and.pencil", type: "sfSymbol" as const },
63 identifier: "thread-left-new-task",
64 label: "New task",
74 - onPress: () => navigation.navigate("NewTaskSheet", { screen: "NewTask" }),
65 + onPress: startNewTask,
66 type: "button" as const,
67 }),
68 ]
69 : []),
70 ],
80 - [
81 - panes.primarySidebarVisible,
82 - props.onReturnToThread,
83 - navigation,
84 - togglePrimarySidebar,
85 - usesDuoHeader,
86 - usesNativeWorkspaceColumns,
87 - ],
71 + [sidebarHeaderItem, props.onReturnToThread, props.draft, startNewTask, usesDuoHeader],
72 );
73 const canGoBack = navigation.canGoBack();
74 const compactHomeHeaderItems = useMemo<NativeHeaderItems>(
@@ -101,14 +85,8 @@ export function useThreadHeaderOptions(props: {
85 );
86
87 const options: AppNativeStackNavigationOptions = {
104 - headerShown: true,
88 + ...threadHeaderAppearance(props.usesNativeHeaderGlass),
89 headerTitle: props.title,
106 - headerTitleStyle: props.usesNativeHeaderGlass
107 - ? {
108 - fontSize: 17,
109 - fontWeight: "800",
110 - }
111 - : undefined,
90 title: props.title,
91 headerBackVisible: !layout.usesSplitView,
92 unstable_headerLeftItems: layout.usesSplitView
apps/mobile/src/features/voice-input/ComposerDictationControl.tsx
+14 -16
@@ -1,16 +1,8 @@
1 import type { VoiceInputPhase, VoiceInputState } from "@t3tools/client-runtime/voice-input";
2 import { memo, useCallback, useLayoutEffect, useState, type ReactNode } from "react";
3 -import {
4 - Linking,
5 - Platform,
6 - Pressable,
7 - Text as SystemText,
8 - View,
9 - type LayoutChangeEvent,
10 -} from "react-native";
3 +import { Linking, Pressable, Text as SystemText, View, type LayoutChangeEvent } from "react-native";
4 import Animated, {
5 Easing,
13 - LinearTransition,
6 ReduceMotion,
7 useAnimatedStyle,
8 useReducedMotion,
@@ -32,10 +24,6 @@ const DICTATION_TIMING = {
24 easing: Easing.out(Easing.cubic),
25 reduceMotion: ReduceMotion.System,
26 } as const;
35 -const DICTATION_LAYOUT =
36 - Platform.OS === "android"
37 - ? undefined
38 - : LinearTransition.duration(DICTATION_TIMING.duration).reduceMotion(ReduceMotion.System);
27 const TOOLBAR_FLIP_TIMING = {
28 duration: 260,
29 easing: Easing.inOut(Easing.cubic),
@@ -122,7 +110,6 @@ export function ComposerDictationDraftContent(props: {
110 importantForAccessibility={props.hidden ? "no-hide-descendants" : "auto"}
111 collapsable={false}
112 className={props.className}
125 - layout={DICTATION_LAYOUT}
113 pointerEvents={props.hidden ? "none" : "auto"}
114 style={[animatedStyle, { backfaceVisibility: "hidden" }]}
115 >
@@ -268,6 +255,7 @@ export function DictationElapsedTime(props: {
255 }
256
257 function VoiceActionButton(props: {
258 + readonly size?: "regular" | "large";
259 readonly accessibilityLabel: string;
260 readonly disabled?: boolean;
261 readonly icon: AppSymbolName;
@@ -295,7 +283,11 @@ function VoiceActionButton(props: {
283 <View
284 className={cn(
285 "items-center justify-center",
298 - variant === "primary" ? "size-[30px] rounded-full bg-subtle" : "size-[44px]",
286 + variant === "primary"
287 + ? props.size === "large"
288 + ? "size-[44px] rounded-full bg-subtle"
289 + : "size-[30px] rounded-full bg-subtle"
290 + : "size-[44px]",
291 )}
292 >
293 {variant === "primary" ? (
@@ -310,7 +302,7 @@ function VoiceActionButton(props: {
302 ) : (
303 <SymbolView
304 name={props.icon}
313 - size={variant === "primary" ? 16 : 20}
305 + size={props.size === "large" ? 24 : variant === "primary" ? 16 : 20}
306 weight={variant === "primary" ? "semibold" : "regular"}
307 tintColorClassName={
308 variant === "primary" ? "accent-primary-foreground" : "accent-icon"
@@ -395,12 +387,14 @@ export function ComposerDictationStatus(props: {
387 }
388
389 export function ComposerDictationCancelAction(props: {
390 + readonly size?: "regular" | "large";
391 readonly presentation: VoiceComposerPresentation;
392 readonly onCancel: () => void;
393 }) {
394 if (props.presentation.leadingAction !== "cancel") return null;
395 return (
396 <VoiceActionButton
397 + size={props.size}
398 accessibilityLabel="Cancel dictation"
399 icon="xmark"
400 onPress={props.onCancel}
@@ -409,6 +403,7 @@ export function ComposerDictationCancelAction(props: {
403 }
404
405 export function ComposerDictationPrimaryAction(props: {
406 + readonly size?: "regular" | "large";
407 readonly state: VoiceInputState;
408 readonly presentation: VoiceComposerPresentation;
409 readonly isAvailable: boolean;
@@ -420,6 +415,7 @@ export function ComposerDictationPrimaryAction(props: {
415 if (props.presentation.trailingAction === "confirm") {
416 return (
417 <VoiceActionButton
418 + size={props.size}
419 accessibilityLabel={
420 props.presentation.confirmationEnabled
421 ? "Finish dictation"
@@ -438,6 +434,7 @@ export function ComposerDictationPrimaryAction(props: {
434 }
435
436 export function ComposerDictationStartAction(props: {
437 + readonly size?: "regular" | "large";
438 readonly state: VoiceInputState;
439 readonly isAvailable: boolean;
440 readonly disabled?: boolean;
@@ -448,6 +445,7 @@ export function ComposerDictationStartAction(props: {
445 const openSettings = props.state.phase === "error" && props.state.errorAction === "settings";
446 return (
447 <VoiceActionButton
448 + size={props.size}
449 accessibilityLabel={openSettings ? "Open microphone settings" : "Start dictation"}
450 disabled={props.disabled}
451 icon="mic"
apps/mobile/src/features/workspace/AndroidWorkspaceNavigation.android.tsx
+2 -1
@@ -55,6 +55,7 @@ function nativeColor(value: string) {
55 }
56
57 export function AndroidWorkspaceNavigation(props: {
58 + readonly onNewThread: () => void;
59 readonly rail?: boolean;
60 readonly onSelect?: () => void;
61 /** The rail needs the whole workspace while it widens over the list. */
@@ -117,7 +118,7 @@ export function AndroidWorkspaceNavigation(props: {
118 }}
119 onNewThread={() => {
120 Keyboard.dismiss();
120 - navigation.navigate("NewTaskSheet", { screen: "NewTask" });
121 + props.onNewThread();
122 }}
123 onOverlayChange={(event) => props.onOverlayChange?.(event.nativeEvent.overlay)}
124 style={rail ? { flex: 1 } : { height: 80 * Math.max(1, scale) }}
apps/mobile/src/features/workspace/AndroidWorkspaceNavigation.tsx
+1
@@ -1,4 +1,5 @@
1 export function AndroidWorkspaceNavigation(_props: {
2 + readonly onNewThread: () => void;
3 readonly rail?: boolean;
4 readonly onSelect?: () => void;
5 readonly onOverlayChange?: (overlay: boolean) => void;
apps/mobile/src/features/workspace/AndroidWorkspaceSettings.tsx
+2 -2
@@ -6,7 +6,7 @@ import { AndroidWorkspaceNavigation } from "./AndroidWorkspaceNavigation";
6
7 /** Settings keeps its existing stack inside the full workspace, above compact navigation. */
8 export function AndroidWorkspaceSettings(props: { readonly children: ReactNode }) {
9 - const { layout } = useAdaptiveWorkspaceLayout();
9 + const { layout, startNewTask } = useAdaptiveWorkspaceLayout();
10 const insets = useSafeAreaInsets();
11 if (Platform.OS !== "android") return props.children;
12 return (
@@ -14,7 +14,7 @@ export function AndroidWorkspaceSettings(props: { readonly children: ReactNode }
14 <SafeAreaInsetsContext value={layout.usesSplitView ? insets : { ...insets, bottom: 0 }}>
15 <View className="flex-1">{props.children}</View>
16 </SafeAreaInsetsContext>
17 - {layout.usesSplitView ? null : <AndroidWorkspaceNavigation />}
17 + {layout.usesSplitView ? null : <AndroidWorkspaceNavigation onNewThread={startNewTask} />}
18 </View>
19 );
20 }
apps/mobile/src/features/workspace/WorkspaceRootScreen.android.tsx
+2 -2
@@ -19,7 +19,7 @@ import type { WorkspaceTab } from "./workspace-tabs-state";
19 const TABS: readonly WorkspaceTab[] = ["threads", "pullRequests"];
20
21 export function WorkspaceRootScreen() {
22 - const { layout } = useAdaptiveWorkspaceLayout();
22 + const { layout, startNewTask } = useAdaptiveWorkspaceLayout();
23 const workspace = useWorkspaceTabs()!;
24 const insets = useSafeAreaInsets();
25 const { fabClearance } = useAndroidControlSizing();
@@ -80,7 +80,7 @@ export function WorkspaceRootScreen() {
80 }
81 />
82 </SafeAreaInsetsContext>
83 - <AndroidWorkspaceNavigation />
83 + <AndroidWorkspaceNavigation onNewThread={startNewTask} />
84 </View>
85 </WorkspaceTabsContext>
86 );
apps/mobile/src/features/workspace/WorkspaceRootScreen.tsx
+6 -7
@@ -56,7 +56,7 @@ function WorkspaceRootTitle(props: {
56 function WorkspaceRootContent() {
57 const navigation = useNavigation();
58 const { width: windowWidth } = useWindowDimensions();
59 - const { layout } = useAdaptiveWorkspaceLayout();
59 + const { layout, startNewTask } = useAdaptiveWorkspaceLayout();
60 const primaryColumn = use(NativePrimaryColumnContext);
61 const columnMetrics = useNativeColumnLayoutMetrics();
62 const nativeMetrics = useNativeLayoutMetrics();
@@ -98,7 +98,9 @@ function WorkspaceRootContent() {
98 : Platform.OS === "ios"
99 ? Math.max(insets.bottom, keyboardHeight) +
100 (systemTabBar || sidebarTabs || tab.searchMode !== "resting"
101 - ? 16
101 + ? sidebarPicker
102 + ? 80
103 + : 16
104 : WORKSPACE_DOCK.height + WORKSPACE_DOCK.bottomGap + 16)
105 : keyboardHeight > 0 && tab.searchMode !== "resting"
106 ? keyboardHeight + 64
@@ -146,14 +148,11 @@ function WorkspaceRootContent() {
148 ]}
149 />
150 )}
149 - {sidebarPicker ? <WorkspaceSidebarTabs /> : null}
151 <SafeAreaInsetsContext value={sidebarPicker ? { ...insets, top: 0 } : insets}>
152 {state.selectedTab === "threads" ? <HomeRouteScreen /> : <PullRequestsScreen />}
153 </SafeAreaInsetsContext>
153 - <WorkspaceToolbar
154 - sidebar={sidebarNavigation}
155 - onNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
156 - />
154 + {sidebarPicker ? <WorkspaceSidebarTabs /> : null}
155 + <WorkspaceToolbar sidebar={sidebarNavigation} onNewTask={startNewTask} />
156 </View>
157 </WorkspaceTabsContext>
158 );
apps/mobile/src/features/workspace/WorkspaceSidebarTabs.ios.tsx
+24 -14
@@ -1,23 +1,33 @@
1 -import { View } from "react-native";
2 -import { SegmentedControl } from "../../components/ui/SegmentedControl";
1 +import { requireNativeView } from "expo";
2 +import type { NativeSyntheticEvent, ViewProps } from "react-native";
3 +import { useSafeAreaInsets } from "react-native-safe-area-context";
4 +import { useControlTheme } from "../../components/ui/useControlTheme";
5 import { useWorkspaceTabs } from "./WorkspaceTabsContext";
4 -import type { WorkspaceTab } from "./workspace-tabs-state";
6 import { useSelectWorkspaceTab } from "./useSelectWorkspaceTab";
7
8 +const NativeSidebarTabBar = requireNativeView<
9 + ViewProps & {
10 + selectedIndex: number;
11 + selectedColor: string;
12 + appearance: string;
13 + onSelectionChange: (event: NativeSyntheticEvent<{ index: number }>) => void;
14 + }
15 +>("T3NativeControls", "SidebarTabBar");
16 +
17 export function WorkspaceSidebarTabs() {
18 const workspace = useWorkspaceTabs()!;
19 const selectTab = useSelectWorkspaceTab();
20 + const insets = useSafeAreaInsets();
21 + const { colors, colorScheme } = useControlTheme();
22 return (
11 - <View className="px-4 pb-3 pt-2">
12 - <SegmentedControl
13 - role="tab"
14 - options={[
15 - { value: "threads", label: "Threads" },
16 - { value: "pullRequests", label: "Pull requests" },
17 - ]}
18 - selected={workspace.state.selectedTab}
19 - onSelect={(tab: WorkspaceTab) => selectTab(tab)}
20 - />
21 - </View>
23 + <NativeSidebarTabBar
24 + selectedIndex={workspace.state.selectedTab === "threads" ? 0 : 1}
25 + selectedColor={colors["--color-primary"]}
26 + appearance={colorScheme}
27 + onSelectionChange={({ nativeEvent }) =>
28 + selectTab(nativeEvent.index === 0 ? "threads" : "pullRequests")
29 + }
30 + style={{ position: "absolute", bottom: 0, left: 0, right: 0, height: 64 + insets.bottom }}
31 + />
32 );
33 }
apps/mobile/src/features/workspace/WorkspaceToolbar.ios.tsx
+4 -1
@@ -1,3 +1,4 @@
1 +import { useActiveNewTask } from "../../state/active-new-task";
2 import { Toolbar } from "../../components/ui/Toolbar";
3 import { useFocusEffect, useNavigation } from "@react-navigation/native";
4 import { use, useCallback, useEffect, useRef, type ReactNode } from "react";
@@ -59,6 +60,7 @@ export function WorkspaceToolbar(props: {
60 readonly sidebar?: boolean;
61 }) {
62 const workspace = useWorkspaceTabs()!;
63 + const activeNewTask = useActiveNewTask();
64 const navigation = useNavigation();
65 const deviceType = useDeviceType();
66 const sidebarTabs = useSidebarWorkspaceTabs();
@@ -68,7 +70,8 @@ export function WorkspaceToolbar(props: {
70 const nativeToolbarCompose =
71 Platform.OS === "ios" &&
72 deviceType === "duo-folded" &&
71 - workspace.state.selectedTab === "threads";
73 + workspace.state.selectedTab === "threads" &&
74 + activeNewTask === null;
75 // The Duo searches from a field at the bottom of the list in every pose. UIKit has no such
76 // placement once the vertical bar holds the toolbar, and re-placing its search controller on
77 // each fold replaces the search field.
apps/mobile/src/lib/adaptive-navigation.test.ts
+29
@@ -6,6 +6,15 @@ import {
6 } from "./adaptive-navigation";
7
8 describe("resolveThreadSelectionNavigationAction", () => {
9 + it("retains the draft screen despite its query-shaped path", () => {
10 + expect(
11 + resolveThreadSelectionNavigationAction({
12 + usesSplitView: true,
13 + pathname: "/threads?draft=local",
14 + workspaceRouteName: "Thread",
15 + }),
16 + ).toBe("set-params");
17 + });
18 it("replaces nested thread content when a persistent sidebar selects a peer", () => {
19 expect(
20 resolveThreadSelectionNavigationAction({
@@ -82,3 +91,23 @@ describe("resolveThreadSelectionOverlayState", () => {
91 },
92 );
93 });
94 +
95 +it("replacing a draft underneath an overlay removes its draft identity", () => {
96 + const result = resolveThreadSelectionOverlayState({
97 + state: {
98 + key: "root",
99 + type: "stack",
100 + stale: false,
101 + routeNames: ["Thread", "SettingsSheet"],
102 + index: 1,
103 + routes: [
104 + { key: "draft", name: "Thread", params: { draft: { draftId: "old" } } },
105 + { key: "settings", name: "SettingsSheet" },
106 + ],
107 + },
108 + workspaceRouteKey: "draft",
109 + action: "set-params",
110 + params: { environmentId: "env", threadId: "live" },
111 + });
112 + expect(result?.routes[0]?.params).toEqual({ environmentId: "env", threadId: "live" });
113 +});
apps/mobile/src/lib/adaptive-navigation.ts
+6 -3
@@ -5,7 +5,7 @@ export type AdaptiveNavigationAction = "push" | "replace" | "set-params";
5 const BASE_THREAD_ROUTE_PATTERN = /^\/threads\/[^/]+\/[^/]+\/?$/;
6
7 export function isBaseThreadRoute(pathname: string): boolean {
8 - return BASE_THREAD_ROUTE_PATTERN.test(pathname);
8 + return BASE_THREAD_ROUTE_PATTERN.test(pathname) || /^\/new\/draft\/?$/.test(pathname);
9 }
10
11 /**
@@ -15,12 +15,15 @@ export function isBaseThreadRoute(pathname: string): boolean {
15 export function resolveThreadSelectionNavigationAction(input: {
16 readonly usesSplitView: boolean;
17 readonly pathname: string;
18 + readonly workspaceRouteName?: string;
19 }): AdaptiveNavigationAction {
20 if (!input.usesSplitView || input.pathname === "/") {
21 return "push";
22 }
23
23 - return isBaseThreadRoute(input.pathname) ? "set-params" : "replace";
24 + return input.workspaceRouteName === "Thread" || isBaseThreadRoute(input.pathname)
25 + ? "set-params"
26 + : "replace";
27 }
28
29 export function resolveThreadSelectionOverlayState(input: {
@@ -43,7 +46,7 @@ export function resolveThreadSelectionOverlayState(input: {
46 routes: [
47 ...routes,
48 input.action === "set-params" && workspaceRoute?.name === "Thread"
46 - ? { ...workspaceRoute, params: { ...workspaceRoute.params, ...input.params } }
49 + ? { ...workspaceRoute, params: input.params }
50 : { name: "Thread", params: input.params },
51 ],
52 };
apps/mobile/src/lib/android-workspace-navigation.ts
+2 -1
@@ -82,12 +82,13 @@ export function parentThreadIsBelow(
82 state: NavigationState,
83 parent: ReactNavigation.RootParamList["Thread"],
84 ) {
85 + if (!parent?.environmentId || !parent.threadId) return false;
86 const previous = state.routes[state.index - 1];
87 const params = previous?.params as ReactNavigation.RootParamList["Thread"] | undefined;
88 return (
89 previous?.name === "Thread" &&
90 params?.environmentId === parent.environmentId &&
90 - params.threadId === parent.threadId
91 + params?.threadId === parent.threadId
92 );
93 }
94
apps/mobile/src/lib/appLinking.test.ts
+41 -1
@@ -1,6 +1,6 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import { shouldHandleAppLink } from "./appLinking";
3 +import { shouldHandleAppLink, restoreDraftLinkState } from "./appLinking";
4
5 describe("shouldHandleAppLink", () => {
6 it.each(["t3code://", "t3code:///", "t3code-dev://", "t3code-preview://"])(
@@ -25,3 +25,43 @@ describe("shouldHandleAppLink", () => {
25 },
26 );
27 });
28 +
29 +describe("draft deep links", () => {
30 + it("opens the old draft URL on the thread screen with its draft identity", () => {
31 + const draft = { projectId: "project-1", environmentId: "env-1", draftId: "draft-1" };
32 + expect(
33 + restoreDraftLinkState(
34 + { routes: [{ name: "Home" }, { name: "Thread", params: draft }] },
35 + "/new/draft?draftId=draft-1",
36 + ),
37 + ).toEqual({
38 + index: 1,
39 + routes: [{ name: "Home" }, { name: "Thread", params: { draft } }],
40 + });
41 + });
42 +
43 + it.each([
44 + ["environment", "NewTaskEnvironment"],
45 + ["branch", "NewTaskBranch"],
46 + ["files", "NewTaskFiles"],
47 + ["files/src/index.ts", "NewTaskFile"],
48 + ["attachments/attachment-1", "NewTaskAttachment"],
49 + ["settings", "NewTaskThreadSettings"],
50 + ])("restores a draft beneath its %s screen", (path, name) => {
51 + const params = { environmentId: "env-1", projectId: "project-1" };
52 + const target = { name, params };
53 + expect(
54 + restoreDraftLinkState({ routes: [{ name: "Home" }, target] }, `/new/draft/${path}`),
55 + ).toEqual({
56 + index: 2,
57 + routes: [{ name: "Home" }, { name: "Thread", params: { draft: params } }, target],
58 + });
59 + });
60 +
61 + it("leaves live-thread and project-selection links unchanged", () => {
62 + const state = { routes: [{ name: "Thread", params: { threadId: "thread-1" } }] };
63 + expect(restoreDraftLinkState(state, "/threads/env-1/thread-1")).toBe(state);
64 + expect(restoreDraftLinkState(state, "/new")).toBe(state);
65 + expect(restoreDraftLinkState(undefined, "/new/draft")).toBeUndefined();
66 + });
67 +});
apps/mobile/src/lib/appLinking.ts
+18
@@ -1,3 +1,5 @@
1 +import type { NavigationState, PartialState } from "@react-navigation/native";
2 +
3 /**
4 * The Expo dev client launches the app via
5 * <scheme>://expo-development-client/?url=<packager> — that URL addresses
@@ -11,3 +13,19 @@ export function shouldHandleAppLink(url: string): boolean {
13 !/^t3code(-dev|-preview)?:\/*$/.test(url)
14 );
15 }
16 +
17 +/** Keep the published draft URLs while using the root thread screen. */
18 +export function restoreDraftLinkState(
19 + state: PartialState<NavigationState> | undefined,
20 + path: string,
21 +) {
22 + const pathname = path.split("?")[0]?.replace(/^\/+|\/+$/g, "");
23 + if (!state || !pathname || !/^new\/draft(?:\/|$)/.test(pathname)) return state;
24 + const target = state.routes.at(-1);
25 + if (!target) return state;
26 + const draft = target.params ?? {};
27 + const routes = state.routes.slice(0, -1);
28 + routes.push({ name: "Thread", params: { draft } });
29 + if (pathname !== "new/draft") routes.push(target);
30 + return { ...state, index: routes.length - 1, routes };
31 +}
apps/mobile/src/native/createV5StackNavigator.ios.tsx
+1 -2
@@ -260,8 +260,7 @@ export function V5StackView(props: V5StackViewProps) {
260 const groups = partitionStackPresentations(props.state.routes, (route) => {
261 const presentation = props.descriptors[route.key]?.options.presentation;
262 return (
263 - ["SettingsSheet", "NewTaskSheet"].includes(route.name) ||
264 - (presentation !== undefined && presentation !== "card")
263 + route.name === "SettingsSheet" || (presentation !== undefined && presentation !== "card")
264 );
265 });
266 const routes = groups.map((group) => group[0]!);
apps/mobile/src/native/native-layout-metrics.tsx
+5 -2
@@ -45,6 +45,9 @@ export function useDeviceType() {
45 */
46 export function useDuoBottomBarInset() {
47 const deviceType = useDeviceType();
48 - const inset = use(NativeColumnLayoutMetricsContext)?.bottomBarInset;
49 - return isDuoDevice(deviceType) ? inset : undefined;
48 + const metrics = use(NativeColumnLayoutMetricsContext);
49 + // Sheets have no rail to align with and can report zero for the bar region.
50 + // Their controls must keep using the sheet's bottom safe area.
51 + const inset = metrics?.bottomBarInset;
52 + return isDuoDevice(deviceType) && inset !== undefined && inset > 0 ? inset : undefined;
53 }
apps/mobile/src/native/workspace-stack-projection.test.ts
+1 -1
@@ -42,7 +42,7 @@ function history(
42
43 describe("workspace router projection", () => {
44 it("keeps workspace flows beside Home and restores them after a modal closes", () => {
45 - const draft = { key: "draft", name: "NewTaskSheet" };
45 + const draft = { key: "draft", name: "Thread", params: { draft: {} } };
46 const modal = { key: "connect", name: "ConnectOnboarding" };
47 const routes = [home, thread, draft, settings, legal];
48 const isOverlay = (route: { name: string }) => route.name === "ConnectOnboarding";
apps/mobile/src/state/active-new-task.ts new
+9
@@ -0,0 +1,9 @@
1 +import { createContext, use } from "react";
2 +
3 +export const ActiveNewTaskContext = createContext<{ readonly pendingKey: string | null } | null>(
4 + null,
5 +);
6 +
7 +export function useActiveNewTask() {
8 + return use(ActiveNewTaskContext);
9 +}
apps/mobile/src/state/thread-task-permissions.test.ts
+1
@@ -60,6 +60,7 @@ const state = vi.hoisted(() => ({
60 vi.mock("react", () => ({
61 useCallback: <A>(callback: A) => callback,
62 useEffect: () => {},
63 + useLayoutEffect: () => {},
64 useRef: <A>(current: A) => ({ current }),
65 useMemo: <A>(factory: () => A) => factory(),
66 useState: <A>(initial: A | (() => A)) => [
apps/mobile/src/state/use-composer-attachment-actions.ts new
+136
@@ -0,0 +1,136 @@
1 +import * as Dialog from "../components/ui/Dialog";
2 +import { useLayoutEffect, useRef } from "react";
3 +import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, type ServerConfig } from "@t3tools/contracts";
4 +import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
5 +import { nextPastedTextFileName } from "@t3tools/client-runtime/text-paste";
6 +import type { ComposerTextPaste } from "../components/ComposerEditor";
7 +import {
8 + convertPastedImagesToAttachments,
9 + createPastedTextComposerAttachment,
10 + pickComposerFiles,
11 + pickComposerMedia,
12 + removePersistedComposerAttachmentFile,
13 + type DraftComposerAttachment,
14 +} from "../lib/composerImages";
15 +import {
16 + appendComposerDraftAttachments,
17 + captureComposerDraftInsertion,
18 + countComposerDraftAttachmentsAfterSelection,
19 + getComposerDraftSnapshot,
20 + type ComposerDraftInsertion,
21 +} from "./use-composer-drafts";
22 +
23 +export function useComposerAttachmentActions(props: {
24 + readonly draftKey: string | null;
25 + readonly serverConfig: ServerConfig | null | undefined;
26 + readonly locked?: boolean;
27 +}) {
28 + const currentKey = useRef(props.draftKey);
29 + const reservedNames = useRef(new Map<string, Set<string>>());
30 + useLayoutEffect(() => {
31 + currentKey.current = props.draftKey;
32 + return () => {
33 + currentKey.current = null;
34 + };
35 + }, [props.draftKey]);
36 + const capabilities = props.serverConfig?.environment.capabilities;
37 + const append = async (
38 + key: string,
39 + attachments: ReadonlyArray<DraftComposerAttachment>,
40 + insertion: ComposerDraftInsertion,
41 + ) => {
42 + // A picker may finish after selecting another draft or sending this one.
43 + if (currentKey.current !== key) {
44 + await Promise.all(
45 + attachments.flatMap((item) =>
46 + item.fileUri ? [removePersistedComposerAttachmentFile(item.fileUri)] : [],
47 + ),
48 + );
49 + return 0;
50 + }
51 + return appendComposerDraftAttachments(key, attachments, { appendReference: true, insertion });
52 + };
53 + const report = (title: string, error: string | null | undefined, rejected: number) => {
54 + const problems = [
55 + ...(error ? [error] : []),
56 + ...(rejected
57 + ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`]
58 + : []),
59 + ];
60 + if (problems.length) Dialog.alert(title, problems.join("\n\n"));
61 + };
62 + const onPickDraftMedia = async () => {
63 + const key = props.draftKey;
64 + if (!key || props.locked) return;
65 + const insertion = captureComposerDraftInsertion(key);
66 + const result = await pickComposerMedia({
67 + existingCount: countComposerDraftAttachmentsAfterSelection(key, insertion),
68 + maxVideoBytes: capabilities?.attachmentUploads
69 + ? capabilities.fileAttachments?.maxUploadBytes
70 + : undefined,
71 + });
72 + report(
73 + "Could not attach photo or video",
74 + result.error,
75 + await append(key, result.attachments, insertion),
76 + );
77 + };
78 + const onPickDraftFiles = async () => {
79 + const key = props.draftKey;
80 + if (!key || props.locked) return;
81 + const maxBytes = capabilities?.fileAttachments?.maxUploadBytes;
82 + if (maxBytes === undefined) {
83 + Dialog.alert("Could not attach file", "This server does not support file attachments.");
84 + return;
85 + }
86 + const insertion = captureComposerDraftInsertion(key);
87 + const result = await pickComposerFiles({
88 + existingCount: countComposerDraftAttachmentsAfterSelection(key, insertion),
89 + maxBytes,
90 + });
91 + report("Could not attach file", result.error, await append(key, result.files, insertion));
92 + };
93 + const onNativePasteImages = async (uris: ReadonlyArray<string>) => {
94 + const key = props.draftKey;
95 + if (!key || props.locked || !uris.length) return;
96 + const insertion = captureComposerDraftInsertion(key);
97 + try {
98 + const images = await convertPastedImagesToAttachments({
99 + uris,
100 + existingCount: countComposerDraftAttachmentsAfterSelection(key, insertion),
101 + });
102 + report("Could not paste images", null, await append(key, images, insertion));
103 + } catch (error) {
104 + Dialog.alert("Could not paste images", error instanceof Error ? error.message : "Try again.");
105 + }
106 + };
107 + const onNativePasteText = async (paste: ComposerTextPaste) => {
108 + const key = props.draftKey;
109 + if (!key || props.locked) return;
110 + const maxBytes = capabilities?.attachmentUploads
111 + ? capabilities.fileAttachments?.maxUploadBytes
112 + : undefined;
113 + if (maxBytes === undefined) return;
114 + const names = reservedNames.current.get(key) ?? new Set<string>();
115 + reservedNames.current.set(key, names);
116 + for (const attachment of getComposerDraftSnapshot(key).attachments) names.add(attachment.name);
117 + const name = nextPastedTextFileName([...names]);
118 + names.add(name);
119 + try {
120 + const attachment = await createPastedTextComposerAttachment({
121 + text: paste.text,
122 + name,
123 + maxBytes: clampFileAttachmentUploadBytes(maxBytes),
124 + });
125 + const rejected = await append(key, [attachment], { text: paste.value, ...paste.selection });
126 + if (rejected) await removePersistedComposerAttachmentFile(attachment.fileUri);
127 + report("Could not attach pasted text", null, rejected);
128 + } catch (error) {
129 + Dialog.alert(
130 + "Could not attach pasted text",
131 + error instanceof Error ? error.message : "Try again.",
132 + );
133 + }
134 + };
135 + return { onPickDraftMedia, onPickDraftFiles, onNativePasteImages, onNativePasteText };
136 +}
apps/mobile/src/state/use-thread-composer-state.ts
+5 -129
@@ -1,7 +1,7 @@
1 +import { useComposerAttachmentActions } from "./use-composer-attachment-actions";
2 import * as Dialog from "../components/ui/Dialog";
3 import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
4 import { readEnvironmentScope } from "./session";
4 -import type { ComposerTextPaste } from "../native/T3ComposerEditor.types";
5 import { useAtomValue } from "@effect/atom-react";
6 import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
7 import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
@@ -27,7 +27,6 @@ import {
27 type RuntimeMode,
28 type ThreadId,
29 } from "@t3tools/contracts";
30 -import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
30 import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
31 import { nextPastedTextFileName, pastedTextDisposition } from "@t3tools/client-runtime/text-paste";
32 import {
@@ -47,11 +46,8 @@ import {
46 } from "../lib/modelOptions";
47 import { resolveProviderInteractionMode } from "./legacy-plan-mode";
48 import {
50 - convertPastedImagesToAttachments,
49 createPastedTextComposerAttachment,
50 pasteComposerClipboard,
53 - pickComposerFiles,
54 - pickComposerMedia,
51 removePersistedComposerAttachmentFile,
52 } from "../lib/composerImages";
53 import type { DraftComposerImageAttachment } from "../lib/composerImages";
@@ -741,68 +737,11 @@ export function useThreadComposerState() {
737 setComposerDraftText(threadKey, value);
738 };
739
744 - const onPickDraftMedia = async () => {
745 - if (!selectedThreadShell) {
746 - return;
747 - }
748 -
749 - const threadKey = activeComposerDraftKey(selectedThreadShell);
750 - const insertion = captureComposerDraftInsertion(threadKey);
751 - const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
752 - const result = await pickComposerMedia({
753 - existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
754 - maxVideoBytes:
755 - capabilities?.attachmentUploads === true
756 - ? capabilities.fileAttachments?.maxUploadBytes
757 - : undefined,
740 + const { onPickDraftMedia, onPickDraftFiles, onNativePasteImages, onNativePasteText } =
741 + useComposerAttachmentActions({
742 + draftKey: selectedThreadShell ? activeComposerDraftKey(selectedThreadShell) : null,
743 + serverConfig: selectedEnvironmentRuntime?.serverConfig,
744 });
759 - const rejectedCount = appendComposerDraftAttachments(threadKey, result.attachments, {
760 - appendReference: true,
761 - insertion,
762 - });
763 - const problems = [
764 - ...(result.error ? [result.error] : []),
765 - ...(rejectedCount > 0
766 - ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`]
767 - : []),
768 - ];
769 - if (problems.length > 0) {
770 - Dialog.alert("Could not attach photo or video", problems.join("\n\n"));
771 - }
772 - };
773 -
774 - const onPickDraftFiles = async () => {
775 - if (!selectedThreadShell) {
776 - return;
777 - }
778 - const maxBytes =
779 - selectedEnvironmentRuntime?.serverConfig?.environment.capabilities.fileAttachments
780 - ?.maxUploadBytes;
781 - if (maxBytes === undefined) {
782 - Dialog.alert("Could not attach file", "This server does not support file attachments.");
783 - return;
784 - }
785 -
786 - const threadKey = activeComposerDraftKey(selectedThreadShell);
787 - const insertion = captureComposerDraftInsertion(threadKey);
788 - const result = await pickComposerFiles({
789 - existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
790 - maxBytes,
791 - });
792 - const rejectedCount = appendComposerDraftAttachments(threadKey, result.files, {
793 - appendReference: true,
794 - insertion,
795 - });
796 - const problems = [
797 - ...(result.error ? [result.error] : []),
798 - ...(rejectedCount > 0
799 - ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`]
800 - : []),
801 - ];
802 - if (problems.length > 0) {
803 - Dialog.alert("Could not attach file", problems.join("\n\n"));
804 - }
805 - };
745
746 const onPasteIntoDraft = async () => {
747 if (!selectedThreadShell) {
@@ -893,69 +832,6 @@ export function useThreadComposerState() {
832 }
833 };
834
896 - const onNativePasteImages = async (uris: ReadonlyArray<string>) => {
897 - if (!selectedThreadShell || uris.length === 0) {
898 - return;
899 - }
900 -
901 - const threadKey = activeComposerDraftKey(selectedThreadShell);
902 - const insertion = captureComposerDraftInsertion(threadKey);
903 - try {
904 - const images = await convertPastedImagesToAttachments({
905 - uris,
906 - existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
907 - });
908 - if (images.length > 0) {
909 - appendComposerDraftAttachments(threadKey, images, { appendReference: true, insertion });
910 - }
911 - } catch (error) {
912 - console.error("[native paste] error converting images", {
913 - environmentId: selectedThreadShell.environmentId,
914 - threadId: selectedThreadShell.id,
915 - uriCount: uris.length,
916 - ...safeErrorLogAttributes(error),
917 - });
918 - }
919 - };
920 -
921 - const onNativePasteText = async (paste: ComposerTextPaste) => {
922 - if (!selectedThreadShell) return;
923 - const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
924 - const advertisedMax =
925 - capabilities?.attachmentUploads === true
926 - ? capabilities.fileAttachments?.maxUploadBytes
927 - : undefined;
928 - if (advertisedMax === undefined) return;
929 -
930 - const threadKey = activeComposerDraftKey(selectedThreadShell);
931 - const insertion = { text: paste.value, ...paste.selection };
932 - const currentAttachments = getComposerDraftSnapshot(threadKey).attachments;
933 - try {
934 - const attachment = await createPastedTextComposerAttachment({
935 - text: paste.text,
936 - name: reservePastedTextFileName(
937 - threadKey,
938 - currentAttachments.map((item) => item.name),
939 - ),
940 - maxBytes: clampFileAttachmentUploadBytes(advertisedMax),
941 - });
942 - const rejectedCount = appendComposerDraftAttachments(threadKey, [attachment], {
943 - appendReference: true,
944 - insertion,
945 - });
946 - if (rejectedCount > 0) {
947 - await removePersistedComposerAttachmentFile(attachment.fileUri);
948 - setPendingConnectionError(
949 - `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
950 - );
951 - }
952 - } catch (error) {
953 - setPendingConnectionError(
954 - error instanceof Error ? error.message : "Could not attach pasted text.",
955 - );
956 - }
957 - };
958 -
835 const onRemoveDraftImage = (imageId: string) => {
836 if (!selectedThreadShell) {
837 return;
apps/mobile/src/state/use-thread-selection.ts
+4 -6
@@ -157,13 +157,11 @@ function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefin
157 const message = queued ?? outcome?.message ?? null;
158 return message === null ? null : { message, outcome };
159 })();
160 - // Until the creation is delivered the server has no thread to subscribe
161 - // to. Every detail reader must use this ref, not the route id: an earlier
162 - // read gets a definitive not-found, which the thread state keeps as deleted.
160 + // The shell can arrive before creation is acknowledged. Wait for delivery
161 + // before subscribing: an early not-found is cached as a deleted thread.
162 + // Every detail reader must use this ref, not the route id.
163 const selectedThreadDetailRef =
164 - selectedThreadShell !== null ||
165 - pendingCreation === null ||
166 - pendingCreation.outcome?.kind === "delivered"
164 + pendingCreation === null || pendingCreation.outcome?.kind === "delivered"
165 ? selectedThreadRef
166 : null;
167 const [previousCreation, setPreviousCreation] = useState<PendingThreadCreation | null>(null);