diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml index 65cfa08321c87..516a0a7785a95 100644 --- a/.github/workflows/release-desktop.yml +++ b/.github/workflows/release-desktop.yml @@ -253,18 +253,13 @@ jobs: if [[ "${{ inputs.version }}" =~ -nightly\.[0-9]{8}\.[0-9]+$ ]]; then brand=nightly; fi node scripts/apply-web-brand-assets.ts "$brand" apps/server/dist/client - # The single-executable is built with a Node that supports --build-sea - # (25.7+); the repo itself stays on the engines.node version. A native - # build injects into the runner's own Node; a Windows target downloads its - # node.exe. + # Setup Vite+ selects the exact engines.node version from package.json. + # Native builds embed that executable; cross-target builds download the + # same version for their target. - name: Build CLI single-executable if: inputs.cli_archive shell: bash env: - # The exact version, not a major: vp downloads it from nodejs.org/dist on - # the runner, and only exact versions have a dist directory. Keep in - # step with SEA_NODE_VERSION in apps/server/vite.config.ts. - VP_NODE_VERSION: "26.8.2" # The executable bundles the server again, so it needs the same stamp # as release.yml's JS bundle. T3CODE_TELEMETRY_CHANNEL: ${{ github.repository == 'pingdotgg/t3code' && inputs.release_channel || 'dev' }} diff --git a/apps/mobile/deps/react-native-screens-5.0.0-t3.30.tgz b/apps/mobile/deps/react-native-screens-5.0.0-t3.30.tgz deleted file mode 100644 index 581307cf91be1..0000000000000 Binary files a/apps/mobile/deps/react-native-screens-5.0.0-t3.30.tgz and /dev/null differ diff --git a/apps/mobile/deps/react-native-screens-5.0.0-t3.36.tgz b/apps/mobile/deps/react-native-screens-5.0.0-t3.36.tgz new file mode 100644 index 0000000000000..071a4022a7b3f Binary files /dev/null and b/apps/mobile/deps/react-native-screens-5.0.0-t3.36.tgz differ diff --git a/apps/mobile/modules/t3-native-controls/ios/T3LayoutMetricsView.swift b/apps/mobile/modules/t3-native-controls/ios/T3LayoutMetricsView.swift index 936efe7676e95..b970936b1fe8f 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3LayoutMetricsView.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3LayoutMetricsView.swift @@ -69,6 +69,7 @@ final class T3LayoutMetricsView: ExpoView { } var verticalBarEdge = "none" var regions: [[String: Any]] = [] + var bottomBarInset: CGFloat? #if canImport(UIKit, _version: 9127.0.85) if #available(iOS 27.1, *) { let rtl = effectiveUserInterfaceLayoutDirection == .rightToLeft @@ -77,6 +78,8 @@ final class T3LayoutMetricsView: ExpoView { case .trailing: verticalBarEdge = rtl ? "left" : "right" default: break } + // Where UIKit floats a bar as tall as the app's bottom controls, level with its tab bar. + bottomBarInset = edgeInsets(for: .bar(onEdge: UIRectEdge.bottom, extent: 48)).bottom for kind in [UIView.ReservedRegion.Kind.division, .occlusion] { for region in reservedRegions(kind: kind) where region.isActive { let frame = region.frame.intersection(bounds) @@ -90,7 +93,7 @@ final class T3LayoutMetricsView: ExpoView { } } #endif - let metrics: [String: Any] = [ + var metrics: [String: Any] = [ "width": bounds.width, "height": bounds.height, "hasHinge": hasHinge, "horizontalSizeClass": traitCollection.horizontalSizeClass == .regular ? "regular" : "compact", @@ -101,6 +104,7 @@ final class T3LayoutMetricsView: ExpoView { ], "reservedRegions": regions, ] + metrics["bottomBarInset"] = bottomBarInset let next = metrics as NSDictionary guard lastMetrics?.isEqual(next) != true else { return } lastMetrics = next diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 78e935bfe9339..f6c4357575485 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -135,7 +135,7 @@ "react-native-pdf-jsi": "5.0.0", "react-native-reanimated": "4.7.1", "react-native-safe-area-context": "~5.10.1", - "react-native-screens": "file:deps/react-native-screens-5.0.0-t3.30.tgz", + "react-native-screens": "file:deps/react-native-screens-5.0.0-t3.36.tgz", "react-native-shiki-engine": "^0.3.12", "react-native-svg": "15.16.0", "react-native-webrtc": "124.0.8", diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 95149dfff3ab7..c62d05c9e8b9a 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -151,7 +151,7 @@ import { NATIVE_LIQUID_GLASS_SUPPORTED } from "./native/native-glass"; import { deriveLayout } from "./lib/layout"; import { useNativeLayoutMetrics } from "./native/native-layout-metrics"; import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader"; -import { FORM_SHEET_PRESENTATION_OPTIONS } from "./native/sheet-surface"; +import { HORIZONTAL_FORM_SHEET_OPTIONS, formSheetDetents } from "./native/sheet-surface"; import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain"; import { useComposerAttachmentUploadWorker } from "./state/composer-attachment-uploads"; @@ -212,6 +212,15 @@ const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = { const NESTED_NAVIGATOR_OPTIONS = { nativeContentInsetHorizontally: false, headerShown: false }; +// Thread settings keep the Duo's vertical bar so cancel, search, filter and confirm sit in the +// rail. The picker stack spans the sheet so its header reaches the rail, and insets its content. +const THREAD_SETTINGS_SHEET_OPTIONS = { + presentation: "formSheet" as const, + sheetAllowedDetents: [1], + sheetGrabberVisible: true, + nativeContentInsetHorizontally: false, +}; + const SettingsContentStack = createV5SheetStackNavigator({ initialRouteName: "Settings", screenOptions: { @@ -370,9 +379,7 @@ const SettingsContentStack = createV5SheetStackNavigator({ ...(Platform.OS === "android" ? { presentation: "card" as const } : { - ...FORM_SHEET_PRESENTATION_OPTIONS, - sheetAllowedDetents: [1], - sheetGrabberVisible: true, + ...THREAD_SETTINGS_SHEET_OPTIONS, }), }, }), @@ -515,9 +522,7 @@ const NewTaskSheetStack = createNativeStackNavigator({ ...(Platform.OS === "android" ? { presentation: "card" as const } : { - ...FORM_SHEET_PRESENTATION_OPTIONS, - sheetAllowedDetents: [1], - sheetGrabberVisible: true, + ...THREAD_SETTINGS_SHEET_OPTIONS, }), }, }), @@ -742,8 +747,8 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: PullRequestFilesSheet, options: { ...(Platform.OS === "ios" ? SHEET_GLASS_HEADER_OPTIONS : undefined), - ...FORM_SHEET_PRESENTATION_OPTIONS, - sheetAllowedDetents: [0.6, 0.92], + ...HORIZONTAL_FORM_SHEET_OPTIONS, + sheetAllowedDetents: formSheetDetents(0.6), sheetGrabberVisible: true, sheetCornerRadius: Platform.OS === "android" ? 28 : undefined, }, @@ -752,8 +757,8 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: PullRequestReviewersScreen, options: { ...DETAIL_HEADER_OPTIONS, - ...FORM_SHEET_PRESENTATION_OPTIONS, - sheetAllowedDetents: [0.75, 0.92], + ...HORIZONTAL_FORM_SHEET_OPTIONS, + sheetAllowedDetents: formSheetDetents(0.75), sheetGrabberVisible: true, headerBackVisible: false, }, @@ -767,8 +772,8 @@ const RootStackConfig = createWorkspaceStackNavigator({ options: { ...(Platform.OS === "android" ? { presentation: "fullScreenModal" as const } - : { ...SHEET_GLASS_HEADER_OPTIONS, ...FORM_SHEET_PRESENTATION_OPTIONS }), - sheetAllowedDetents: Platform.OS === "android" ? undefined : [0.75, 0.92], + : { ...SHEET_GLASS_HEADER_OPTIONS, ...HORIZONTAL_FORM_SHEET_OPTIONS }), + sheetAllowedDetents: Platform.OS === "android" ? undefined : formSheetDetents(0.75), sheetGrabberVisible: Platform.OS !== "android", }, }), @@ -776,8 +781,8 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: PullRequestReviewSheet, options: { ...(Platform.OS === "ios" ? SHEET_GLASS_HEADER_OPTIONS : undefined), - ...FORM_SHEET_PRESENTATION_OPTIONS, - sheetAllowedDetents: [0.75, 0.92], + ...HORIZONTAL_FORM_SHEET_OPTIONS, + sheetAllowedDetents: formSheetDetents(0.75), sheetGrabberVisible: true, }, }), @@ -824,8 +829,8 @@ const RootStackConfig = createWorkspaceStackNavigator({ // formSheet; use a full-screen modal there instead. ...(Platform.OS === "android" ? { presentation: "fullScreenModal" as const } - : FORM_SHEET_PRESENTATION_OPTIONS), - sheetAllowedDetents: Platform.OS === "android" ? undefined : [0.55, 0.92], + : HORIZONTAL_FORM_SHEET_OPTIONS), + sheetAllowedDetents: Platform.OS === "android" ? undefined : formSheetDetents(0.55), sheetGrabberVisible: Platform.OS !== "android", }, }), @@ -838,7 +843,7 @@ const RootStackConfig = createWorkspaceStackNavigator({ ...(Platform.OS === "android" ? { presentation: "fullScreenModal" as const } : { - ...FORM_SHEET_PRESENTATION_OPTIONS, + ...HORIZONTAL_FORM_SHEET_OPTIONS, sheetAllowedDetents: [0.65, 0.95], sheetInitialDetentIndex: 1, sheetGrabberVisible: true, @@ -880,36 +885,34 @@ const RootStackConfig = createWorkspaceStackNavigator({ ...(Platform.OS === "android" ? { presentation: "card" as const } : { - ...FORM_SHEET_PRESENTATION_OPTIONS, - sheetAllowedDetents: [1], - sheetGrabberVisible: true, + ...THREAD_SETTINGS_SHEET_OPTIONS, }), }, }), ThreadQueue: createNativeStackScreen({ screen: ThreadQueueSheet, options: { - ...FORM_SHEET_PRESENTATION_OPTIONS, + ...HORIZONTAL_FORM_SHEET_OPTIONS, headerShown: false, - sheetAllowedDetents: [0.65, 0.95], + sheetAllowedDetents: formSheetDetents(0.65, 0.95), sheetGrabberVisible: true, }, }), ThreadBackgroundWork: createNativeStackScreen({ screen: ThreadBackgroundWorkSheet, options: { - ...FORM_SHEET_PRESENTATION_OPTIONS, + ...HORIZONTAL_FORM_SHEET_OPTIONS, headerShown: false, - sheetAllowedDetents: [0.5, 0.9], + sheetAllowedDetents: formSheetDetents(0.5, 0.9), sheetGrabberVisible: true, }, }), ThreadAgents: createNativeStackScreen({ screen: ThreadAgentsSheet, options: { - ...FORM_SHEET_PRESENTATION_OPTIONS, + ...HORIZONTAL_FORM_SHEET_OPTIONS, headerShown: false, - sheetAllowedDetents: [0.5, 0.9], + sheetAllowedDetents: formSheetDetents(0.5, 0.9), sheetGrabberVisible: true, }, }), @@ -917,8 +920,9 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: GitOverviewSheet, linking: `${THREAD_LINKING_PREFIX}/git`, options: { - ...FORM_SHEET_PRESENTATION_OPTIONS, - sheetAllowedDetents: [0.55, 0.92], + ...(Platform.OS === "ios" ? SHEET_GLASS_HEADER_OPTIONS : undefined), + ...HORIZONTAL_FORM_SHEET_OPTIONS, + sheetAllowedDetents: formSheetDetents(0.55), sheetGrabberVisible: true, }, }), @@ -926,8 +930,9 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: ThreadPullRequestsSheet, linking: `${THREAD_LINKING_PREFIX}/pull-requests`, options: { - ...FORM_SHEET_PRESENTATION_OPTIONS, - sheetAllowedDetents: [0.55, 0.92], + ...(Platform.OS === "ios" ? SHEET_GLASS_HEADER_OPTIONS : undefined), + ...HORIZONTAL_FORM_SHEET_OPTIONS, + sheetAllowedDetents: formSheetDetents(0.55), sheetGrabberVisible: true, }, }), @@ -936,8 +941,8 @@ const RootStackConfig = createWorkspaceStackNavigator({ linking: `${THREAD_LINKING_PREFIX}/git/commit`, options: { ...(Platform.OS === "ios" ? SHEET_GLASS_HEADER_OPTIONS : undefined), - ...FORM_SHEET_PRESENTATION_OPTIONS, - sheetAllowedDetents: [0.8, 0.92], + ...HORIZONTAL_FORM_SHEET_OPTIONS, + sheetAllowedDetents: formSheetDetents(0.8), sheetGrabberVisible: true, }, }), @@ -945,8 +950,9 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: GitBranchesSheet, linking: `${THREAD_LINKING_PREFIX}/git/branches`, options: { - ...FORM_SHEET_PRESENTATION_OPTIONS, - sheetAllowedDetents: [0.55, 0.92], + ...(Platform.OS === "ios" ? SHEET_GLASS_HEADER_OPTIONS : undefined), + ...HORIZONTAL_FORM_SHEET_OPTIONS, + sheetAllowedDetents: formSheetDetents(0.55), sheetGrabberVisible: true, }, }), @@ -954,8 +960,8 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: GitConfirmSheet, linking: `${THREAD_LINKING_PREFIX}/git-confirm`, options: { - ...FORM_SHEET_PRESENTATION_OPTIONS, - sheetAllowedDetents: [0.45, 0.7], + ...HORIZONTAL_FORM_SHEET_OPTIONS, + sheetAllowedDetents: [0.55, 0.7], sheetGrabberVisible: true, }, }), @@ -988,8 +994,8 @@ const RootStackConfig = createWorkspaceStackNavigator({ ...(Platform.OS === "android" ? { headerShown: false } : SHEET_SOLID_HEADER_OPTIONS), title: "Set up T3 Connect", gestureEnabled: true, - ...FORM_SHEET_PRESENTATION_OPTIONS, - sheetAllowedDetents: [0.6, 0.95], + ...HORIZONTAL_FORM_SHEET_OPTIONS, + sheetAllowedDetents: formSheetDetents(0.6, 0.95), sheetGrabberVisible: true, }, }), @@ -1001,7 +1007,7 @@ const RootStackConfig = createWorkspaceStackNavigator({ ...(Platform.OS === "android" ? { presentation: "card" as const, headerShown: false } : { - ...FORM_SHEET_PRESENTATION_OPTIONS, + ...HORIZONTAL_FORM_SHEET_OPTIONS, sheetAllowedDetents: [0.55, 0.7], sheetGrabberVisible: true, }), @@ -1015,7 +1021,7 @@ const RootStackConfig = createWorkspaceStackNavigator({ // native header stack mounts without remounting the pairing form. ...(Platform.OS === "ios" ? SHEET_GLASS_HEADER_OPTIONS : undefined), title: "Add Environment", - ...FORM_SHEET_PRESENTATION_OPTIONS, + ...HORIZONTAL_FORM_SHEET_OPTIONS, sheetAllowedDetents: [0.55, 0.7], sheetGrabberVisible: true, }, @@ -1033,6 +1039,7 @@ const RootStackConfig = createWorkspaceStackNavigator({ ), options: { ...NESTED_NAVIGATOR_OPTIONS, + sheetPrefersHorizontalBars: true, gestureEnabled: true, headerShown: false, }, @@ -1090,8 +1097,8 @@ export const RootStack = RootStackConfig.with(function AdaptiveRootStack({ Navig return usesWorkspaceFlowScreens ? { presentation: "card" } : { - ...FORM_SHEET_PRESENTATION_OPTIONS, - sheetAllowedDetents: [0.92], + presentation: "formSheet", + sheetAllowedDetents: [1], sheetGrabberVisible: true, }; }} diff --git a/apps/mobile/src/components/ui/Sheet.tsx b/apps/mobile/src/components/ui/Sheet.tsx index 21ee41a5c5569..56994803b4ab8 100644 --- a/apps/mobile/src/components/ui/Sheet.tsx +++ b/apps/mobile/src/components/ui/Sheet.tsx @@ -4,6 +4,7 @@ import { FormSheet, ScreenStack } from "react-native-screens"; import { useResolveClassNames } from "uniwind"; import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader"; +import { formSheetDetents } from "../../native/sheet-surface"; import { NativeHeader, NativeScreen } from "../../native/ThemedScreenStack"; const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version); @@ -21,8 +22,10 @@ export function Sheet(props: SheetProps) { return ( void; }) { const insets = useSafeAreaInsets(); + // NativeColumnContent already insets the sides, so only a book fold moves the reveal handle. + const handleBounds = deriveBottomControlInsets(useNativeColumnLayoutMetrics()); const { themeVariables } = useAppearancePreferences(); const focused = useIsFocused(); const [foreground, setForeground] = useState(AppState.currentState !== "background"); @@ -318,7 +322,10 @@ function DevicePreviewScreen({ accessibilityHint="Shaking the phone also shows them" hitSlop={12} className="absolute h-6 w-16 items-center justify-center self-center" - style={{ top: Math.max(insets.top - 18, 4) }} + style={{ + top: Math.max(insets.top - 18, 4), + transform: [{ translateX: (handleBounds.left - handleBounds.right) / 2 }], + }} onPress={() => setControlsVisible(true)} > diff --git a/apps/mobile/src/features/files/thread-file-navigator-pane.tsx b/apps/mobile/src/features/files/thread-file-navigator-pane.tsx index 901024a27827a..5f3deb6089c4b 100644 --- a/apps/mobile/src/features/files/thread-file-navigator-pane.tsx +++ b/apps/mobile/src/features/files/thread-file-navigator-pane.tsx @@ -21,6 +21,7 @@ import { useEnvironmentQuery } from "../../state/query"; import { useEnvironmentPresentation } from "../../state/presentation"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; import { FileTreeBrowser } from "./FileTreeBrowser"; +import { NativeInspectorContent } from "../../native/NativeInspectorContent"; import { useFileTreeEntries } from "./useFileTreeEntries"; import { preloadWorkspaceFileContents } from "./preload-workspace-file"; import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout"; @@ -120,7 +121,7 @@ export function ThreadFileNavigatorPane(props: { scrollEdgeEffects={headerScrollEdgeEffects} style={{ backgroundColor: sheetColor, flex: 1 }} > - {fileTree} + {fileTree} >(); - const { layout, panes, togglePrimarySidebar } = useAdaptiveWorkspaceLayout(); - const usesNativeMailSearchToolbar = useNativeMailSearchToolbar(); - const deviceType = useDeviceType(); - const primaryColumn = use(NativePrimaryColumnContext); - const sidebarHeader = - Platform.OS === "ios" && - primaryColumn !== null && - (deviceType === "pad" || !usesNativeMailSearchToolbar); - const showsCompactCompose = deviceType === "pad" && !layout.usesSplitView; - const searchBarRef = useRef(null); - const focusAfterReveal = useRef(false); - useEffect( - () => - navigation.addListener("transitionEnd", (event) => { - if (focusAfterReveal.current && !event.data.closing) { - focusAfterReveal.current = false; - searchBarRef.current?.focus(); - } - }), - [navigation], - ); - const iconColor = useUniwindTheme()["--color-icon"]; - const hasCustomListOptions = - props.selectedEnvironmentId !== null || props.selectedProjectKey !== null; - const focusSearch = useCallback(() => { - if (primaryColumn && !panes.primarySidebarVisible) { - focusAfterReveal.current = true; - togglePrimarySidebar(); - return true; - } - searchBarRef.current?.focus(); - return searchBarRef.current !== null; - }, [primaryColumn, panes.primarySidebarVisible, togglePrimarySidebar]); - useHardwareKeyboardCommand("focusSearch", focusSearch); - const filterMenu = buildHomeListFilterMenu(props); - const { onOpenVoiceSession } = props; - const voiceSessionItems = - onOpenVoiceSession === null - ? [] - : [ - withNativeGlassHeaderItem({ - accessibilityLabel: "Talk to the orchestrator", - icon: { name: "waveform", type: "sfSymbol" } as const, - identifier: "home-voice-session", - label: "", - onPress: onOpenVoiceSession, - type: "button", - }), - ]; - - if (props.usesWorkspaceToolbar) { - return deviceType === "duo-unfolded" ? ( - - ) : null; - } - - return ( - <> - - sidebarHeader - ? [ - ...createSidebarHeaderItems({ - filterIcon: hasCustomListOptions - ? "line.3.horizontal.decrease.circle.fill" - : "line.3.horizontal.decrease.circle", - filterMenu, - onOpenSettings: props.onOpenSettings, - }), - ...voiceSessionItems, - ...(showsCompactCompose - ? [ - withNativeGlassHeaderItem({ - accessibilityLabel: "New task", - axisBehavior: "horizontalOnly", - icon: { name: "square.and.pencil", type: "sfSymbol" } as const, - identifier: "home-new-task", - label: "", - onPress: props.onStartNewTask, - type: "button", - }), - ] - : []), - ] - : [ - withNativeGlassHeaderItem({ - accessibilityLabel: "Open settings", - icon: { name: "ellipsis", type: "sfSymbol" } as const, - identifier: "home-settings", - label: "", - onPress: props.onOpenSettings, - type: "button", - }), - ...voiceSessionItems, - ], - // The keys below are set per-branch (not `undefined`) so a later - // reapply cannot clobber options owned by Toolbar. - ...(sidebarHeader - ? { - headerSearchBarOptions: { - ref: searchBarRef, - autoCapitalize: "none" as const, - hideNavigationBar: false, - hideWhenScrolling: false, - obscureBackground: false, - placement: "stacked" as const, - allowToolbarIntegration: false, - placeholder: "Search", - onCancelButtonPress: () => props.onSearchQueryChange(""), - onChangeText: (event) => props.onSearchQueryChange(event.nativeEvent.text), - }, - unstable_headerToolbarItems: () => [], - } - : usesNativeMailSearchToolbar - ? { - headerSearchBarOptions: { - ref: searchBarRef, - autoCapitalize: "none" as const, - onCancelButtonPress: () => props.onSearchQueryChange(""), - }, - unstable_headerToolbarItems: () => [ - createNativeMailSearchToolbarItem({ - composeButtonId: "home-new-task", - composeSystemImageName: "square.and.pencil", - filterMenu, - filterButtonId: "home-filter", - filterSystemImageName: hasCustomListOptions - ? "line.3.horizontal.decrease.circle.fill" - : "line.3.horizontal.decrease", - onComposePress: props.onStartNewTask, - onSearchTextChange: props.onSearchQueryChange, - placeholder: "Search", - searchTextChangeId: "home-search-text", - showsSearchDismissButton: true, - }), - ], - } - : { - headerSearchBarOptions: { - ref: searchBarRef, - autoCapitalize: "none" as const, - hideNavigationBar: false, - placeholder: "Search", - onCancelButtonPress: () => { - props.onSearchQueryChange(""); - }, - onChangeText: (event) => { - props.onSearchQueryChange(event.nativeEvent.text); - }, - }, - }), - }} - /> - - {sidebarHeader || usesNativeMailSearchToolbar ? null : ( - - - - Environment - props.onEnvironmentChange(null)} - subtitle="Show threads from every environment" - > - All environments - - {props.environments.map((environment) => ( - props.onEnvironmentChange(environment.environmentId)} - > - {environment.label} - - ))} - - - {props.projects.length > 0 ? ( - - Project - props.onProjectChange(null)} - subtitle="Show threads from every project" - > - All projects - - {props.projects.map((project) => ( - props.onProjectChange(project.key)} - > - {project.label} - - ))} - - ) : null} - - - - - )} - - ); +/** The iOS thread list lives in the workspace, whose WorkspaceToolbar owns its header and search. */ +export function HomeHeader(_props: HomeHeaderProps) { + return null; } diff --git a/apps/mobile/src/features/home/HomeHeader.types.ts b/apps/mobile/src/features/home/HomeHeader.types.ts index ef24021d53d30..54c3c8def0b88 100644 --- a/apps/mobile/src/features/home/HomeHeader.types.ts +++ b/apps/mobile/src/features/home/HomeHeader.types.ts @@ -7,7 +7,6 @@ import type { export type HomeHeaderEnvironment = HomeListFilterMenuEnvironment; export interface HomeHeaderProps { - readonly usesWorkspaceToolbar?: boolean; readonly environments: ReadonlyArray; readonly projects: ReadonlyArray; readonly searchQuery: string; diff --git a/apps/mobile/src/features/home/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsx index ba7fe402066a1..827c417bce911 100644 --- a/apps/mobile/src/features/home/HomeRouteScreen.tsx +++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx @@ -252,7 +252,6 @@ export function HomeRouteScreen() { /> )} ) { const insets = useSafeAreaInsets(); const primaryColumn = use(NativePrimaryColumnContext); + const restingOffset = useRestingTopOffset(insets.top, props); if (Platform.OS !== "ios") return ; // v5 needs the actual content scroll view registered with its screen controller. @@ -230,6 +232,7 @@ function HomeScrollView(props: ComponentProps) { > ) { // past its edge, activating scroll-edge protection before any scroll. automaticallyAdjustContentInsets={false} contentInsetAdjustmentBehavior="never" - contentOffset={props.contentOffset ?? { x: 0, y: -insets.top }} /> ); diff --git a/apps/mobile/src/features/keyboard/CommandPalette.tsx b/apps/mobile/src/features/keyboard/CommandPalette.tsx index d264c0765bcf5..3c3fd349c2010 100644 --- a/apps/mobile/src/features/keyboard/CommandPalette.tsx +++ b/apps/mobile/src/features/keyboard/CommandPalette.tsx @@ -22,7 +22,9 @@ import { RowPressable } from "../../components/ui/RowPressable"; import { AppText as Text } from "../../components/ui/AppText"; import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol"; import { cn } from "../../lib/cn"; +import { deriveBottomControlInsets } from "../../lib/reserved-regions"; import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities"; +import { useNativeLayoutMetrics } from "../../native/native-layout-metrics"; import { T3KeyboardCommands } from "../../native/T3KeyboardCommands"; import { useProjects, useThreadShell, useThreadShells } from "../../state/entities"; import { useThreadSearch } from "../../state/queries"; @@ -156,6 +158,9 @@ export function CommandPalette(props: { const inputRef = useRef(null); const listRef = useRef>(null); const { width, height } = useWindowDimensions(); + // The palette floats above every column, so it keeps itself inside the window's side insets + // and to one side of a book fold. + const bounds = deriveBottomControlInsets(useNativeLayoutMetrics()); const searchEnvironmentIds = useMemo( () => environments @@ -423,7 +428,8 @@ export function CommandPalette(props: { void; readonly onAddConnection?: () => void; }) { + const pullRequests = props.tab === "pullRequests"; return ( - Select a thread + + {pullRequests ? "Select a pull request" : "Select a thread"} + - {Platform.OS === "android" - ? "Choose a thread from the sidebar or start a new thread." - : "Choose a thread from the sidebar or start a new task."} + {pullRequests + ? "Choose a pull request from the sidebar to review it." + : Platform.OS === "android" + ? "Choose a thread from the sidebar or start a new thread." + : "Choose a thread from the sidebar or start a new task."} - {props.onStartNewTask ? ( + {props.onStartNewTask && !pullRequests ? ( Platform.OS === "android" ? ( ) : ( diff --git a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx index c4c0946fffd02..5acc33b87035c 100644 --- a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx +++ b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx @@ -14,7 +14,6 @@ import { } from "@react-navigation/native"; import { NativeStackView, - type NativeStackHeaderItemMenu, type NativeStackNavigationEventMap, type NativeStackNavigationOptions, type NativeStackNavigatorProps, @@ -25,9 +24,10 @@ import { View } from "react-native"; import { Split, type SplitHostCommands } from "react-native-screens"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { scopedThreadKey } from "../../lib/scopedEntities"; -import { WorkspaceTabsProvider } from "../workspace/WorkspaceTabsContext"; +import { WorkspaceTabsProvider, useWorkspaceTabs } from "../workspace/WorkspaceTabsContext"; import { WorkspaceNativeTabs } from "../workspace/WorkspaceNativeTabs.ios"; -import { useNativeLayoutMetrics } from "../../native/native-layout-metrics"; +import { isDuoDevice } from "../../lib/device-type"; +import { useDeviceType, useNativeLayoutMetrics } from "../../native/native-layout-metrics"; import { useAdaptiveWorkspaceLayout } from "./AdaptiveWorkspaceLayout"; import { WorkspaceEmptyDetail } from "./WorkspaceEmptyDetail"; @@ -60,14 +60,19 @@ type ViewProps = ComponentProps; type Descriptor = ViewProps["descriptors"][string]; type Route = ViewProps["state"]["routes"][number]; +const isPullRequestRoute = (route: Route) => + route.name === "PullRequest" || + route.name === "PullRequestFile" || + route.name === "PullRequestFiles"; + function ColumnScreen(props: { readonly descriptor: Descriptor; readonly primary?: boolean; readonly selectedThreadKey?: string | null; readonly selectedPullRequestKey?: string | null; - readonly sidebarFilter?: NativeStackHeaderItemMenu; readonly onDismiss: (routeKey: string) => void; readonly onAppearance: (type: "willAppear" | "didAppear" | "willDisappear", key: string) => void; + readonly onCompose?: () => void; readonly navigation: ViewProps["navigation"]; }) { const { descriptor } = props; @@ -109,8 +114,8 @@ function ColumnScreen(props: { props.navigation.navigate("NewTaskSheet", { screen: "NewTask" }); + // The Duo keeps compose in the detail column's bar, which is its vertical bar in landscape + // and folded, so it sits with the column's other actions whichever screen is shown. Pull + // requests leave it out, including one opened from a thread; their bar is already full of + // review actions. + const detailCompose = + isDuoDevice(deviceType) && selectedTab !== "pullRequests" ? openNewTask : undefined; const inspector = use(NativeWorkspaceInspectorContext); const hostRef = useRef(null); const activeDetailKey = props.detail.at(-1)?.key; @@ -139,12 +153,7 @@ function WorkspaceColumns( const collapsed = useRef(!layout.usesSplitView); const collapsedColumn = useRef({ visible: compactColumn, leaving: null }); const threadParams = props.detail.findLast((route) => route.name === "Thread")?.params; - const pullRequestParams = props.detail.findLast( - (route) => - route.name === "PullRequest" || - route.name === "PullRequestFile" || - route.name === "PullRequestFiles", - )?.params; + const pullRequestParams = props.detail.findLast(isPullRequestRoute)?.params; const selectedPullRequestKey = pullRequestParams && "environmentId" in pullRequestParams && @@ -199,7 +208,6 @@ function WorkspaceColumns( const primary = props.descriptors[props.primary.key]; if (!primary) return null; - const sidebarFilter = (primary.options as AppNativeStackNavigationOptions).nativeSidebarFilter; return ( - props.navigation.navigate("NewTaskSheet", { screen: "NewTask" }) + tab={selectedTab} + onStartNewTask={ + // The detail bar or a visible sidebar already carries compose. + detailCompose || panes.primarySidebarVisible ? undefined : openNewTask } /> @@ -282,8 +296,8 @@ function WorkspaceColumns( descriptor={descriptor} onDismiss={handleNativeDismiss} onAppearance={followCollapsedSplit} + onCompose={isPullRequestRoute(route) ? undefined : detailCompose} navigation={props.navigation} - sidebarFilter={sidebarFilter} /> ) : null; })} @@ -291,7 +305,9 @@ function WorkspaceColumns( diff --git a/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx index 4f9b9316d434d..af471abf2c869 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx @@ -20,6 +20,7 @@ import { ScrollViewMarker } from "react-native-screens"; import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText"; import { EmptyState } from "../../components/ui/EmptyState"; import { Button } from "../../components/ui/Button"; +import { useRestingTopOffset } from "../../native/useRestingTopOffset"; import { SymbolView } from "../../components/ui/AppSymbol"; import { NativeStackScreenOptions } from "../../native/StackHeader"; import { useNativeLayoutMetrics } from "../../native/native-layout-metrics"; @@ -35,14 +36,15 @@ import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff" function ReviewerScrollView(props: ScrollViewProps) { const insets = useSafeAreaInsets(); + const restingOffset = useRestingTopOffset(insets.top, props); return ( ); diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx index 10cb2d7a37202..a513fd424ced1 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx @@ -56,6 +56,7 @@ import { View, } from "react-native"; import { NativeScrollViewMarker as ScrollViewMarker } from "../../native/NativeScrollViewMarker"; +import { useRestingTopOffset } from "../../native/useRestingTopOffset"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/ui/AppText"; @@ -117,13 +118,14 @@ const EMPTY_IDS: readonly string[] = []; function PullRequestTabScrollView(props: ScrollViewProps) { const insets = useSafeAreaInsets(); + const restingOffset = useRestingTopOffset(insets.top, props); return ( ); @@ -299,6 +301,18 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps>>({}); + // AnimatedLegendList re-attaches its handle and sets state whenever its ref changes, + // so an inline ref in the tab map loops the screen into "Maximum update depth exceeded". + const [listRefs] = useState(() => { + const listRef = (tab: typeof section) => (list: LegendListRef | null) => { + scrollViews.current[tab] = list; + }; + return { + overview: listRef("overview"), + guide: listRef("guide"), + activity: listRef("activity"), + }; + }); const selectSection = (next: typeof section) => { if (next === section) return; scrollOffsets.current[section] = currentScrollOffset.current; @@ -545,10 +559,10 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps { - scrollViews.current[tab] = list; - }} - initialScrollOffset={-insets.top} + ref={listRefs[tab]} + // The scroll view owns its resting offset. LegendList keeps the first + // initialScrollOffset it gets, and the first render has the window's top + // inset (0 on the folded iPhone Duo), not the header's. onScroll={(event) => { const offset = event.nativeEvent.contentOffset.y; scrollOffsets.current[tab] = offset; diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx index e0b97485551c2..ea287c16cf8a5 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx @@ -21,6 +21,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/ui/AppText"; import { EmptyState } from "../../components/ui/EmptyState"; +import { useRestingTopOffset } from "../../native/useRestingTopOffset"; import { NativePrimaryColumnContext } from "../../native/v5-workspace-context"; import { useWorkspaceState } from "../../state/workspace"; import { useProjects } from "../../state/entities"; @@ -46,13 +47,14 @@ import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSe function PullRequestScrollView(props: ScrollViewProps) { const insets = useSafeAreaInsets(); + const restingOffset = useRestingTopOffset(insets.top, props); return ( ); diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx index 5660301371d7d..3dd9667f9b5a5 100644 --- a/apps/mobile/src/features/review/ReviewSheet.tsx +++ b/apps/mobile/src/features/review/ReviewSheet.tsx @@ -30,6 +30,7 @@ import { } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics"; +import { NativeInspectorContent } from "../../native/NativeInspectorContent"; import { AppText as Text } from "../../components/ui/AppText"; import { SymbolView } from "../../components/ui/AppSymbol"; @@ -40,7 +41,6 @@ import { environmentCatalog } from "../../connection/catalog"; import { useEnvironmentPresentation } from "../../state/presentation"; import { useAtomCommand } from "../../state/use-atom-command"; import { useUniwindTheme } from "../../lib/useUniwindTheme"; -import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics"; import { useThreadDraftForThread } from "../../state/use-thread-composer-state"; import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; @@ -307,7 +307,6 @@ function ReviewFileNavigator({ onSelectFile, ref, }: ReviewFileNavigatorProps) { - const insets = useSafeAreaInsets(); const theme = useUniwindTheme(); const sheetColor = theme["--color-sheet"]; const foregroundColor = theme["--color-foreground"]; @@ -359,15 +358,8 @@ function ReviewFileNavigator({ data={files} extraData={selectedFileId} keyExtractor={(file) => file.id} - contentContainerStyle={{ - paddingHorizontal: 8, - paddingBottom: 8, - - paddingTop: Platform.OS === "ios" ? insets.top + IOS_NAV_BAR_HEIGHT + 8 : 8, - }} - scrollIndicatorInsets={ - Platform.OS === "ios" ? { top: insets.top + IOS_NAV_BAR_HEIGHT } : undefined - } + contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"} + contentContainerStyle={{ paddingHorizontal: 8, paddingVertical: 8 }} renderItem={renderFile} /> ); @@ -384,7 +376,7 @@ function ReviewFileNavigator({ scrollEdgeEffects={headerScrollEdgeEffects} style={{ backgroundColor: sheetColor, flex: 1 }} > - {fileList} + {fileList} [ withNativeGlassHeaderItem({ - axisBehavior: "horizontalOnly", accessibilityLabel: "Filter settings environments and projects", icon: { name: filterIcon, type: "sfSymbol" }, label: "", @@ -121,7 +120,6 @@ export function SettingsEnvironmentFilterHeader(props: { ...(closeSettings ? [ withNativeGlassHeaderItem({ - axisBehavior: "horizontalOnly", accessibilityLabel: "Close settings", icon: { name: "xmark", type: "sfSymbol" }, identifier: "settings-close", diff --git a/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx b/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx index 77ecc530b90b7..447254e2bbf28 100644 --- a/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx @@ -9,7 +9,7 @@ import { Animated, FlatList, Modal, Pressable, View } from "react-native"; import { Gesture, GestureDetector, GestureHandlerRootView } from "react-native-gesture-handler"; import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated"; import { threadDragGapOffset } from "./threadDragGap"; -import { useSafeAreaInsets } from "react-native-safe-area-context"; +import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/ui/AppText"; import { SymbolView } from "../../components/ui/AppSymbol"; @@ -149,7 +149,6 @@ function DragHandle(props: { } export function ThreadArrangementSheet(props: { onClose: () => void }) { - const insets = useSafeAreaInsets(); const threads = useAtomValue(environmentThreadShells.navigationThreadShellsAtom); const configs = useAtomValue(environmentServerConfigsAtom); const queuedThreadKeys = useAtomValue(queuedThreadKeysAtom); @@ -373,184 +372,187 @@ export function ThreadArrangementSheet(props: { onClose: () => void }) { onRequestClose={props.onClose} > - - - - Drag to reorder, pin, or settle. Changes save when you drop. - - { - geometry.current.height = event.nativeEvent.layout.height; - }} - className="flex-1" - style={{ overflow: "hidden" }} - > - row.key} - scrollEnabled={visiblePreview === null} - removeClippedSubviews={false} - onScroll={(event) => { - geometry.current.offset = event.nativeEvent.contentOffset.y; - }} - scrollEventThrottle={16} - getItemLayout={(_, index) => ({ - length: rows[index]!.height, - offset: rows[index]!.offset, - index, - })} - renderItem={({ item }) => { - const thread = item.thread; - const planner = - item.section === "pinned" || item.section === "active" - ? planners[item.section] - : null; - const capabilities = - thread && configs.get(thread.environmentId)?.environment.capabilities; - const sectionActions = thread - ? (["pinned", "active", "settled"] as const).flatMap<{ - name: "pinned" | "active" | "settled"; - label: string; - }>((section) => { - if (section === item.section) return []; - const label = threadDragAction(item.section, section); - if (!label) return []; - if (section === "settled") - return capabilities?.threadSettlement ? [{ name: section, label }] : []; - if ( - ((section === "pinned" || thread.pinnedAt != null) && - !capabilities?.threadPinning) || - (section === "active" && - item.section === "settled" && - !capabilities?.threadSettlement) || - (section === "active" && - item.section === "snoozed" && - !capabilities?.threadSnooze) - ) - return []; - return planners[section](item.key, { - section, - targetId: null, - placement: "before", - }) - ? [{ name: section, label }] - : []; - }) - : []; - return ( - + + + + + Drag to reorder, pin, or settle. Changes save when you drop. + + { + geometry.current.height = event.nativeEvent.layout.height; + }} + className="flex-1" + style={{ overflow: "hidden" }} + > + row.key} + scrollEnabled={visiblePreview === null} + removeClippedSubviews={false} + onScroll={(event) => { + geometry.current.offset = event.nativeEvent.contentOffset.y; + }} + scrollEventThrottle={16} + getItemLayout={(_, index) => ({ + length: rows[index]!.height, + offset: rows[index]!.offset, + index, + })} + renderItem={({ item }) => { + const thread = item.thread; + const planner = + item.section === "pinned" || item.section === "active" + ? planners[item.section] + : null; + const capabilities = + thread && configs.get(thread.environmentId)?.environment.capabilities; + const sectionActions = thread + ? (["pinned", "active", "settled"] as const).flatMap<{ + name: "pinned" | "active" | "settled"; + label: string; + }>((section) => { + if (section === item.section) return []; + const label = threadDragAction(item.section, section); + if (!label) return []; + if (section === "settled") + return capabilities?.threadSettlement ? [{ name: section, label }] : []; + if ( + ((section === "pinned" || thread.pinnedAt != null) && + !capabilities?.threadPinning) || + (section === "active" && + item.section === "settled" && + !capabilities?.threadSettlement) || + (section === "active" && + item.section === "snoozed" && + !capabilities?.threadSnooze) ) - : 0 - } - > - {thread ? ( - <> - - {thread.title} - - { - void moveThread(thread, { - section, - targetId: null, - placement: "before", - }); - }} - canMoveUp={planner?.(item.key, "up") != null} - canMoveDown={planner?.(item.key, "down") != null} - onStep={(direction) => { - void moveThread(thread, direction); - }} - onStart={() => start(item)} - onMove={update} - onEnd={(cancelled) => { - const current = drag.current; - if (cancelled || !current?.destination) { - stop(); - return; - } - if (frame.current !== null) cancelAnimationFrame(frame.current); - frame.current = null; - drag.current = null; - void moveThread(current.thread, current.destination).finally(stop); - }} - /> - - ) : ( - { - const section = item.section; - if (section === "snoozed" || section === "settled") - setExpanded((value) => ({ ...value, [section]: !value[section] })); - }} + return []; + return planners[section](item.key, { + section, + targetId: null, + placement: "before", + }) + ? [{ name: section, label }] + : []; + }) + : []; + return ( + - - {item.section[0]!.toUpperCase() + item.section.slice(1)} ( - {sections[item.section].length}) - - - )} - - ); - }} - /> - {visiblePreview ? ( - - - {visiblePreview.thread.title} - - {visiblePreview.destination?.section ? ( - - {threadDragAction( - visiblePreview.sourceSection, - visiblePreview.destination.section, - )} - + {thread ? ( + <> + + {thread.title} + + { + void moveThread(thread, { + section, + targetId: null, + placement: "before", + }); + }} + canMoveUp={planner?.(item.key, "up") != null} + canMoveDown={planner?.(item.key, "down") != null} + onStep={(direction) => { + void moveThread(thread, direction); + }} + onStart={() => start(item)} + onMove={update} + onEnd={(cancelled) => { + const current = drag.current; + if (cancelled || !current?.destination) { + stop(); + return; + } + if (frame.current !== null) cancelAnimationFrame(frame.current); + frame.current = null; + drag.current = null; + void moveThread(current.thread, current.destination).finally(stop); + }} + /> + + ) : ( + { + const section = item.section; + if (section === "snoozed" || section === "settled") + setExpanded((value) => ({ ...value, [section]: !value[section] })); + }} + > + + {item.section[0]!.toUpperCase() + item.section.slice(1)} ( + {sections[item.section].length}) + + + )} + + ); + }} + /> + {visiblePreview ? ( + + + {visiblePreview.thread.title} + + {visiblePreview.destination?.section ? ( + + {threadDragAction( + visiblePreview.sourceSection, + visiblePreview.destination.section, + )} + + ) : null} + ) : null} - - ) : null} + + - + ); diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 010548a1352cd..e5ef8527e5585 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -352,6 +352,9 @@ export function ComposerSurface(props: { ); } +/** Space below the composer pill, inside the bottom inset it is given. */ +export const THREAD_COMPOSER_BOTTOM_GUTTER = 6; + export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps) { const project = useProject(scopeProjectRef(props.environmentId, props.selectedThread.projectId)); const { themeVariables: materialTheme } = useAppearancePreferences(); @@ -807,7 +810,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps className="px-[12px]" style={{ paddingTop: usesCard ? 8 : 6, - paddingBottom: (props.bottomInset ?? 0) + (usesCard ? 8 : 6), + paddingBottom: (props.bottomInset ?? 0) + (usesCard ? 8 : THREAD_COMPOSER_BOTTOM_GUTTER), backgroundColor: Platform.OS === "android" ? themeColorWithAlpha(composerPanel, 1) : undefined, }} diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index dd6a969faaec8..074c24cf69fa0 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -102,7 +102,10 @@ import Animated, { import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useWorkspaceContentWidth } from "../layout/workspace-content-width"; import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns"; -import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics"; +import { + useDuoBottomBarInset, + useNativeColumnLayoutMetrics, +} from "../../native/native-layout-metrics"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; import { collectProviderUsageLimits } from "@t3tools/shared/usageLimits"; import type { ComposerEditorHandle } from "../../components/ComposerEditor"; @@ -159,6 +162,7 @@ import { COMPOSER_EXPANDED_CHROME, COMPOSER_LAYOUT_TRANSITION, COMPOSER_TRANSITION_DURATION_MS, + THREAD_COMPOSER_BOTTOM_GUTTER, ThreadComposer, } from "./ThreadComposer"; import { ComposerPopoverHost } from "./ComposerPopoverHost"; @@ -555,10 +559,13 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai const [endFollowEnabled, setEndFollowEnabled] = useState(true); // Android Back hides the keyboard without blurring. Keep its safe-area padding // fixed through the animation and cancel it with matching composer/list offsets. + const bottomBarInset = useDuoBottomBarInset(); const composerBottomInset = Platform.OS === "ios" && (composerExpanded || composerFocused) ? 0 - : Math.max(insets.bottom, 12); + : bottomBarInset !== undefined + ? bottomBarInset - THREAD_COMPOSER_BOTTOM_GUTTER + : Math.max(insets.bottom, 12); const composerKeyboardOffset = Platform.OS === "android" ? composerBottomInset : 0; const contentPresentationKind = props.contentPresentation.kind; const realThreadSyncLabel = (() => { diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 40167d8714470..dd4beb9bac53b 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -90,6 +90,7 @@ import { useCallback, useContext, useEffect, + useEffectEvent, useLayoutEffect, useMemo, useRef, @@ -202,7 +203,11 @@ import { import type { ThreadContentPresentation } from "./threadContentPresentation"; import { resolveThreadFeedLiveFollow, + resolveThreadFeedReflowAnchor, + resolveThreadFeedReflowOffset, + resolveThreadFeedReflowScroll, type ThreadFeedLiveFollowEvent, + type ThreadFeedReflowAnchor, type ThreadWorkGroupScrollPosition, } from "./thread-feed-live-follow"; import { @@ -284,6 +289,14 @@ function formatMessageTime(input: string): string { } const TURN_FOLD_HEIGHT = 42; +const FEED_PADDING_TOP = 12; +// Rows re-measure within a commit or two of a width change. LegendList also defers imperative +// scrolls for 100ms after it compensates a size change, and a deferred restore could land +// under a drag that starts meanwhile. +const FEED_REFLOW_SETTLE_MS = 200; +// A fold resizes the feed in steps about 200ms apart. Holding the place taken at the first step +// across all of them keeps a passing moment off the end from re-anchoring the rest to a row. +const FEED_REFLOW_HOLD_MS = 600; const USER_BUBBLE_HORIZONTAL_PADDING = 3.5 * 3.5; const ASSISTANT_ROW_HORIZONTAL_PADDING = 3.5; const THREAD_FEED_DISCLOSURE_ENTER_TRANSITION = FadeIn.delay( @@ -1875,6 +1888,33 @@ function ThreadFeedPlaceholder(props: { ); } +// A hook's return value is frozen to the compiler, so ThreadFeed's later +// hooks can't drag this derivation into an uncached scope. +function useThreadFeedPresentation( + props: ThreadFeedProps, + expandedTurnIds: ReadonlySet, + expandedWorkGroups: Record, +) { + const [feedCache] = useState(createThreadFeedCache); + return appendPendingThreadMessages( + deriveThreadFeedPresentation( + props.feed, + props.latestRun, + expandedTurnIds, + new Set( + Object.entries(expandedWorkGroups) + .filter(([, expanded]) => expanded) + .map(([groupId]) => groupId), + ), + props.activeWorkStartedAt, + props.runlessWorkActive ?? false, + feedCache, + ), + props.feed, + props.queuedMessages, + ); +} + export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const { listRef, onEndFollowEnabledChange, onHeaderMaterialVisibilityChange } = props; const workflowOpening = useWorkflowOpening(props.environmentId, props.threadId); @@ -1900,7 +1940,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const disclosureSettleFrameRef = useRef(null); const disclosureSettleSecondFrameRef = useRef(null); const disclosureAnchorKeyRef = useRef(null); - const [feedCache] = useState(createThreadFeedCache); const previousLatestTurnRef = useRef(props.latestRun); const userScrollSettleTimerRef = useRef | null>(null); const headerMaterialVisibleRef = useRef(false); @@ -1946,6 +1985,23 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const transitionEndFollow = (event: ThreadFeedLiveFollowEvent) => { setEndFollow(resolveThreadFeedLiveFollow(endFollowEnabledRef.current, event)); }; + // A width change re-wraps every row at once, and LegendList re-measures them over the next + // commits. Its end threshold and MVCP only see the new geometry, so the reader's place is + // taken before any row lands: the end while following, otherwise the row under the header. + // On iOS, LegendList keeps that place in the same commit as every re-measure. Android's + // list moves only while its MVCP is on, which following turns off, so it restores after. + // undefined: no reflow. null: a reflow with nothing to restore. + const reflowAnchorRef = useRef(undefined); + const reflowAnchorsSizeChanges = Platform.OS === "ios"; + const [reflowFollowsEnd, setReflowFollowsEnd] = useState(false); + const [reflowSettleRevision, setReflowSettleRevision] = useState(0); + const listHeaderSizeRef = useRef(0); + const loadedListKeyRef = useRef(null); + const cancelReflow = () => { + if (reflowAnchorRef.current === undefined) return; + reflowAnchorRef.current = undefined; + setReflowFollowsEnd(false); + }; const [interactionState, setInteractionState] = useState<{ readonly copiedRowId: string | null; readonly expandedWorkGroups: Record; @@ -2371,6 +2427,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const handleScrollBeginDrag = () => { clearUserScrollSettle(); userScrollSessionRef.current = true; + cancelReflow(); // Pause before the first scroll event. Otherwise a stream update can run // maintainScrollAtEnd between touch-down and the drag leaving its threshold. transitionEndFollow({ type: "user-scroll-begin" }); @@ -2410,47 +2467,25 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId); const workGroupScrollPositions = new Map(); - useEffect(() => { + // Only a new thread or a send resets following. Listed as dependencies, these handlers also ran + // whenever a parent passed a new follow callback, as a fold does: following re-armed under a + // reader and a width reflow lost its place mid-fold. + const resetEndFollow = useEffectEvent((_trigger: unknown) => { clearUserScrollSettle(); userScrollSessionRef.current = false; + cancelReflow(); transitionEndFollow({ type: "reset" }); - }, [clearUserScrollSettle, feedThreadKey, transitionEndFollow]); + }); + useEffect(() => resetEndFollow(feedThreadKey), [feedThreadKey]); useEffect(() => { - if (props.submittedMessageId !== null) { - clearUserScrollSettle(); - userScrollSessionRef.current = false; - transitionEndFollow({ type: "reset" }); - } - }, [clearUserScrollSettle, props.submittedMessageId, transitionEndFollow]); - - const handleViewportLayout = (event: LayoutChangeEvent) => { - const nextWidth = Math.round(event.nativeEvent.layout.width); - const nextHeight = Math.round(event.nativeEvent.layout.height); - setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current)); - setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current)); - }; + if (props.submittedMessageId !== null) resetEndFollow(props.submittedMessageId); + }, [props.submittedMessageId]); useEffect(() => { reportHeaderMaterialVisibility(false); }, [feedThreadKey, reportHeaderMaterialVisibility]); - const presentedFeed = appendPendingThreadMessages( - deriveThreadFeedPresentation( - props.feed, - props.latestRun, - expandedTurnIds, - new Set( - Object.entries(expandedWorkGroups) - .filter(([, expanded]) => expanded) - .map(([groupId]) => groupId), - ), - props.activeWorkStartedAt, - props.runlessWorkActive ?? false, - feedCache, - ), - props.feed, - props.queuedMessages, - ); + const presentedFeed = useThreadFeedPresentation(props, expandedTurnIds, expandedWorkGroups); const setupAnchorIndex = presentedFeed.findIndex( (entry) => entry.type === "message" && entry.message.role === "user", ); @@ -2466,6 +2501,67 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { } }, [listMountKey, props.contentInsetEndAdjustment, listRef]); + const reflowLayout = () => ({ + rowsTop: FEED_PADDING_TOP + listHeaderSizeRef.current, + headerInset: anchorTopInset, + }); + const beginReflow = () => { + // Until the list loads, its own initial end positioning owns the offset. + if (loadedListKeyRef.current !== listMountKey) return; + if (reflowAnchorRef.current === undefined) { + const listState = listRef.current?.getState(); + const anchor = + listState && !userScrollSessionRef.current + ? resolveThreadFeedReflowAnchor(listState, reflowLayout(), endFollowEnabledRef.current) + : null; + reflowAnchorRef.current = anchor; + if (anchor === "end" && !reflowAnchorsSizeChanges) { + // The list may already have judged the first new sizes against its own threshold, so + // pin the end once; the lifted threshold keeps it there as later rows re-measure. + setReflowFollowsEnd(true); + void listRef.current?.scrollToEnd({ animated: false }); + } + } + setReflowSettleRevision((revision) => revision + 1); + }; + const settleReflow = useEffectEvent(() => { + const anchor = reflowAnchorRef.current; + cancelReflow(); + const list = listRef.current; + if (reflowAnchorsSizeChanges || !anchor || anchor === "end" || !list) return; + if (userScrollSessionRef.current) return; + if (loadedListKeyRef.current !== listMountKey) return; + const target = resolveThreadFeedReflowScroll(anchor, list.getState(), reflowLayout()); + if (target) void list.scrollToIndex({ ...target, viewPosition: 0, animated: false }); + }); + useEffect(() => { + if (reflowSettleRevision === 0) return; + const timeout = setTimeout( + () => settleReflow(), + reflowAnchorsSizeChanges ? FEED_REFLOW_HOLD_MS : FEED_REFLOW_SETTLE_MS, + ); + return () => clearTimeout(timeout); + }, [reflowSettleRevision]); + + const holdReflowAnchor = () => { + const anchor = reflowAnchorRef.current; + if (anchor === "end") return Number.POSITIVE_INFINITY; + const list = listRef.current; + return anchor && list + ? resolveThreadFeedReflowOffset(anchor, list.getState(), reflowLayout()) + : undefined; + }; + + const handleViewportLayout = (event: LayoutChangeEvent) => { + const nextWidth = Math.round(event.nativeEvent.layout.width); + const nextHeight = Math.round(event.nativeEvent.layout.height); + // A native resize re-wraps the rows before JS hears of it. This event reaches JS ahead + // of the row measurements it caused, since layout events are sent parent first. + if (Math.abs(measuredViewportWidth - nextWidth) > 1) beginReflow(); + setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current)); + setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current)); + }; + const anchoredEndSpace = resolveChatListAnchoredEndSpace( presentedFeed, props.anchorMessageId, @@ -2573,6 +2669,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { }; const suspendEndScrollMaintenanceForDisclosure = (anchorKey: string | null) => { + cancelReflow(); disclosureAnchorKeyRef.current = anchorKey; setDisclosureToggleSettling(true); }; @@ -2717,16 +2814,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { useLayoutEffect(() => { if (previousContentWidth.current === contentWidth) return; previousContentWidth.current = contentWidth; + // Rows re-rendered at this width are measured in the next commit, after this effect. + beginReflow(); if (hasHtmlRenders) listRef.current?.clearCaches({ mode: "sizes" }); - // A reflow can grow the visible rows past LegendList's near-end threshold in one batch, and - // maintainScrollAtEnd then stops following. Pin the end the feed was following once the new - // sizes are in. - if (!endFollowEnabledRef.current || !listRef.current?.getState().isAtEnd) return; - const frame = requestAnimationFrame(() => { - if (endFollowEnabledRef.current) void listRef.current?.scrollToEnd({ animated: false }); - }); - return () => cancelAnimationFrame(frame); - }, [contentWidth, hasHtmlRenders, listRef]); + }, [beginReflow, contentWidth, hasHtmlRenders, listRef]); const renderItem = (info: { item: PendingThreadFeedEntry; index: number }) => ( { + loadedListKeyRef.current = listMountKey; + }} + // Row positions start below the header; the reflow anchor converts between them. + onMetricsChange={(metrics) => { + listHeaderSizeRef.current = metrics.headerSize; + }} onScroll={handleScroll} onScrollBeginDrag={handleScrollBeginDrag} onScrollEndDrag={handleScrollEndDrag} @@ -2943,7 +3045,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { ) : null } contentContainerStyle={{ - paddingTop: 12, + paddingTop: FEED_PADDING_TOP, paddingLeft: contentHorizontalPadding + contentLeftInset, paddingRight: contentHorizontalPadding + contentRightInset, }} diff --git a/apps/mobile/src/features/threads/ThreadPullRequestsSheet.tsx b/apps/mobile/src/features/threads/ThreadPullRequestsSheet.tsx index c9075f851ee59..dcf70291e9b74 100644 --- a/apps/mobile/src/features/threads/ThreadPullRequestsSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadPullRequestsSheet.tsx @@ -2,15 +2,14 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native" import { LegendList } from "@legendapp/list/react-native"; import { useMemo } from "react"; import { Platform, View } from "react-native"; -import { ScreenStack } from "react-native-screens"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AndroidSheetHeader } from "../../components/ui/AndroidScreenHeader"; import { AppText as Text } from "../../components/ui/AppText"; import { ScreenContent } from "../../components/ui/ScreenContent"; -import { NativeSheetContent } from "../../native/NativeSheetContent"; -import { NativeStackScreenOptions, nativeHeaderScrollEdgeEffects } from "../../native/StackHeader"; -import { NativeHeader, NativeScreen } from "../../native/ThemedScreenStack"; +import { SheetHeader } from "../../components/ui/SheetHeader"; +import { Toolbar } from "../../components/ui/Toolbar"; +import { NativeStackScreenOptions } from "../../native/StackHeader"; import { useOpenPullRequest } from "../../native/useOpenPullRequest"; import { useThreadSelection } from "../../state/use-thread-selection"; import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout"; @@ -21,7 +20,6 @@ import { } from "./LinkedPullRequestList"; import { useLinkedPullRequestActions } from "./useLinkedPullRequestActions"; -const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version); const TITLE = "Linked pull requests"; export function ThreadPullRequestsSheet( @@ -92,47 +90,19 @@ export function ThreadPullRequestsSheet( ); if (Platform.OS === "ios") { - // A plain formSheet screen never renders a stack header, so it comes from - // a nested native stack inside the sheet (same shape as the git sheet). return ( - - - {content} - navigation.goBack()} /> + {actions.canLink ? ( + + - - + + ) : null} + {content} ); } diff --git a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx index eab14dc38ed0f..19ed0b1a53354 100644 --- a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx @@ -85,6 +85,7 @@ import { createNativeMailSearchToolbarItem, NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET, } from "../layout/native-mail-search-toolbar"; +import { useNativeLayoutMetrics } from "../../native/native-layout-metrics"; import { useNativeMailSearchToolbar } from "../../native/use-native-mail-search-toolbar"; import { ModelRow, ChoiceRow } from "./ThreadSettingsRows"; import { @@ -847,10 +848,8 @@ function ThreadSettingsOptionsItem(props: { .get(session.environmentId) ?.providers.find((provider) => provider.instanceId === session.providerInstanceId) ?? null) : null; - const usesNativeMailSearchToolbar = useNativeMailSearchToolbar(); - const bottomToolbarInset = usesNativeMailSearchToolbar - ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET - : 0; + // Both iOS search layouts float a bottom toolbar over the list's last rows. + const bottomToolbarInset = Platform.OS === "ios" ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET : 0; return ( @@ -1211,11 +1210,17 @@ function useThreadSettingsPickerPresentation() { return value; } +// With a Duo vertical bar, filter and search join cancel and confirm in the rail. +function useThreadSettingsMailSearchToolbar() { + const metrics = useNativeLayoutMetrics(); + return useNativeMailSearchToolbar() && (metrics?.verticalBarEdge ?? "none") === "none"; +} + function ThreadSettingsModelsScreen() { const session = useThreadSettingsSession(); const presentation = useThreadSettingsPickerPresentation(); const navigation = useNavigation>(); - const usesNativeMailSearchToolbar = useNativeMailSearchToolbar(); + const usesNativeMailSearchToolbar = useThreadSettingsMailSearchToolbar(); const hasCustomCatalogFilter = session.providerFilter !== null || session.showLegacy; const commitAndClose = useEffectEvent(() => { if (!session.commitPendingModel()) return; @@ -1335,6 +1340,7 @@ function ThreadSettingsModelsScreen() { headerSearchBarOptions: Platform.OS === "ios" && !usesNativeMailSearchToolbar ? { + allowToolbarIntegration: true, autoCapitalize: "none", hideNavigationBar: false, obscureBackground: false, @@ -1378,7 +1384,6 @@ function ThreadSettingsModelsScreen() { ? "line.3.horizontal.decrease.circle.fill" : "line.3.horizontal.decrease.circle" } - separateBackground title="Model filters" > @@ -1414,6 +1419,7 @@ function ThreadSettingsModelsScreen() { ) : null} + ) : null} diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx index d1d39357f2fa8..4075a49e9774a 100644 --- a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx @@ -5,6 +5,7 @@ import { Platform, Pressable, ScrollView, useWindowDimensions, View } from "reac import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AndroidSheetHeader } from "../../../components/ui/AndroidScreenHeader"; +import { SheetHeader } from "../../../components/ui/SheetHeader"; import { ScreenContent } from "../../../components/ui/ScreenContent"; import { NativeStackScreenOptions } from "../../../native/StackHeader"; import { AppText as Text, AppTextInput as TextInput } from "../../../components/ui/AppText"; @@ -81,11 +82,18 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) { onBack={() => navigation.goBack()} hideBottomBorder /> - ) : null} + ) : ( + navigation.goBack()} + /> + )} - {content} + {content} - - - {content} - - - + navigation.goBack()} + /> + {content} ); } diff --git a/apps/mobile/src/features/threads/sidebar-native-header-items.ts b/apps/mobile/src/features/threads/sidebar-native-header-items.ts index c2f309a011edb..cfbaf755e89a4 100644 --- a/apps/mobile/src/features/threads/sidebar-native-header-items.ts +++ b/apps/mobile/src/features/threads/sidebar-native-header-items.ts @@ -31,30 +31,23 @@ function toNativeHeaderMenuItems(items: HomeListFilterMenu["items"]): NativeHead ); } -export function createSidebarFilterHeaderItem(input: { - readonly filterIcon: string; - readonly filterMenu: HomeListFilterMenu; -}): NativeStackHeaderItemMenu { - return withNativeGlassHeaderItem({ - type: "menu", - axisBehavior: "horizontalOnly", - label: "", - accessibilityLabel: "Filter threads", - icon: sfSymbolIcon(input.filterIcon), - menu: { - title: input.filterMenu.title, - items: toNativeHeaderMenuItems(input.filterMenu.items), - }, - }); -} - export function createSidebarHeaderItems(input: { readonly filterIcon: string; readonly filterMenu: HomeListFilterMenu; readonly onOpenSettings: () => void; }): NativeStackHeaderItem[] { return [ - createSidebarFilterHeaderItem(input), + withNativeGlassHeaderItem({ + type: "menu", + axisBehavior: "horizontalOnly", + label: "", + accessibilityLabel: "Filter threads", + icon: sfSymbolIcon(input.filterIcon), + menu: { + title: input.filterMenu.title, + items: toNativeHeaderMenuItems(input.filterMenu.items), + }, + }), withNativeGlassHeaderItem({ type: "button", axisBehavior: "horizontalOnly", diff --git a/apps/mobile/src/features/threads/thread-feed-live-follow.test.ts b/apps/mobile/src/features/threads/thread-feed-live-follow.test.ts index b8c067ca826a2..93cddab7dc08b 100644 --- a/apps/mobile/src/features/threads/thread-feed-live-follow.test.ts +++ b/apps/mobile/src/features/threads/thread-feed-live-follow.test.ts @@ -2,6 +2,9 @@ import { describe, expect, it } from "vite-plus/test"; import { resolveThreadFeedLiveFollow, + resolveThreadFeedReflowAnchor, + resolveThreadFeedReflowOffset, + resolveThreadFeedReflowScroll, resolveThreadFeedSubmissionAnchor, resolveThreadWorkGroupInitialScroll, shouldFollowThreadWorkGroupAppend, @@ -178,3 +181,115 @@ describe("resolveThreadFeedLiveFollow", () => { ).toBe(false); }); }); + +describe("width reflow anchors", () => { + const layout = { rowsTop: 50, headerInset: 100 }; + const feedState = ( + rows: ReadonlyArray<{ readonly id: string; readonly size: number }>, + scroll: number, + isWithinMaintainScrollAtEndThreshold = false, + ) => { + const positions = rows.map((_, index) => + rows.slice(0, index).reduce((top, row) => top + row.size, 0), + ); + return { + data: rows, + scroll, + isWithinMaintainScrollAtEndThreshold, + indexByKey: (key: string) => { + const index = rows.findIndex((row) => row.id === key); + return index < 0 ? undefined : index; + }, + positionAtIndex: (index: number) => positions[index], + sizes: new Map(rows.map((row) => [row.id, row.size])), + }; + }; + const wide = [ + { id: "question", size: 400 }, + { id: "reply", size: 2_000 }, + { id: "follow-up", size: 300 }, + ]; + // The line under the header sits 1,200px, 60%, into the reply. + const readingReply = feedState(wide, 1_550); + + it("keeps the end for a feed that is following it", () => { + expect(resolveThreadFeedReflowAnchor(feedState(wide, 1_550, true), layout, true)).toBe("end"); + }); + + it("keeps the reader's row after a status-bar scroll left follow on far from the end", () => { + expect(resolveThreadFeedReflowAnchor(readingReply, layout, true)).toEqual({ + key: "reply", + offsetWithinRow: 1_200, + size: 2_000, + }); + }); + + it.each([ + { change: "narrows", replySize: 4_000 }, + { change: "widens", replySize: 1_000 }, + ])("keeps the reader 60% into a reply when the feed $change", ({ replySize }) => { + const anchor = resolveThreadFeedReflowAnchor(readingReply, layout, false); + if (anchor === null || anchor === "end") throw new Error("expected a row anchor"); + const reflowed = feedState( + [ + { id: "question", size: 400 * (replySize / 2_000) }, + { id: "reply", size: replySize }, + { id: "follow-up", size: 300 }, + ], + readingReply.scroll, + ); + expect(resolveThreadFeedReflowScroll(anchor, reflowed, layout)).toEqual({ + index: 1, + viewOffset: layout.headerInset - 0.6 * replySize, + }); + }); + + it.each([ + { change: "narrows", replySize: 4_000 }, + { change: "widens", replySize: 1_000 }, + ])( + "holds the reader 60% into a reply on each re-measure as the feed $change", + ({ replySize }) => { + const anchor = resolveThreadFeedReflowAnchor(readingReply, layout, false); + if (anchor === null || anchor === "end") throw new Error("expected a row anchor"); + const rows = [ + { id: "question", size: 400 * (replySize / 2_000) }, + { id: "reply", size: replySize }, + { id: "follow-up", size: 300 }, + ]; + const offset = resolveThreadFeedReflowOffset( + anchor, + feedState(rows, readingReply.scroll), + layout, + ); + if (offset === undefined) throw new Error("expected an offset"); + expect(resolveThreadFeedReflowAnchor(feedState(rows, offset), layout, false)).toEqual({ + key: "reply", + offsetWithinRow: 0.6 * replySize, + size: replySize, + }); + }, + ); + + it("leaves a reader at the top of the thread where they are", () => { + expect(resolveThreadFeedReflowAnchor(feedState(wide, -layout.headerInset), layout, false)).toBe( + null, + ); + }); + + it("does not scroll when the row did not change size", () => { + const anchor = resolveThreadFeedReflowAnchor(readingReply, layout, false); + if (anchor === null || anchor === "end") throw new Error("expected a row anchor"); + expect(resolveThreadFeedReflowScroll(anchor, readingReply, layout)).toBeNull(); + }); + + it("does not restore a row that left the feed", () => { + expect( + resolveThreadFeedReflowScroll( + { key: "reply", offsetWithinRow: 1_200, size: 2_000 }, + feedState([{ id: "question", size: 400 }], 0), + layout, + ), + ).toBeNull(); + }); +}); diff --git a/apps/mobile/src/features/threads/thread-feed-live-follow.ts b/apps/mobile/src/features/threads/thread-feed-live-follow.ts index 431dda7550d14..d0cfe299999b2 100644 --- a/apps/mobile/src/features/threads/thread-feed-live-follow.ts +++ b/apps/mobile/src/features/threads/thread-feed-live-follow.ts @@ -1,3 +1,5 @@ +import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor"; + export type ThreadFeedLiveFollowEvent = | { readonly type: "reset" } | { readonly type: "user-scroll-begin" } @@ -88,3 +90,89 @@ export function resolveThreadFeedLiveFollow( return current; } } + +/** The LegendList state a width reflow reads before rows re-measure and after they settle. */ +export interface ThreadFeedReflowListState { + readonly data: ReadonlyArray<{ readonly id: string }>; + readonly scroll: number; + readonly isWithinMaintainScrollAtEndThreshold: boolean; + readonly indexByKey: (key: string) => number | undefined; + readonly positionAtIndex: (index: number) => number | undefined; + readonly sizes: ReadonlyMap; +} + +export interface ThreadFeedReflowLayout { + /** List padding and header; row positions start below them. */ + readonly rowsTop: number; + /** The top of the viewport covered by the navigation header. */ + readonly headerInset: number; +} + +export interface ThreadFeedReflowRowAnchor { + readonly key: string; + readonly offsetWithinRow: number; + readonly size: number; +} + +/** A feed that follows keeps the end through a reflow; a reader keeps the row they are in. */ +export type ThreadFeedReflowAnchor = "end" | ThreadFeedReflowRowAnchor; + +function readingLine(state: ThreadFeedReflowListState, layout: ThreadFeedReflowLayout) { + return state.scroll + layout.headerInset - layout.rowsTop; +} + +export function resolveThreadFeedReflowAnchor( + state: ThreadFeedReflowListState, + layout: ThreadFeedReflowLayout, + following: boolean, +): ThreadFeedReflowAnchor | null { + // Follow alone is not enough: a status-bar tap scrolls to the top without a drag, so it + // leaves follow on while the reader is far from the end. + if (following && state.isWithinMaintainScrollAtEndThreshold) return "end"; + const line = readingLine(state, layout); + // A reader at the top of the thread stays there without help. + if (line <= 0) return null; + const row = resolveWorkGroupScrollAnchor({ + data: state.data, + scroll: line, + positionAtIndex: state.positionAtIndex, + }); + const size = row ? state.sizes.get(row.rowId) : undefined; + return row && size ? { key: row.rowId, offsetWithinRow: row.offsetWithinRow, size } : null; +} + +function resolveReflowAnchorPoint( + anchor: ThreadFeedReflowRowAnchor, + state: ThreadFeedReflowListState, +) { + const index = state.indexByKey(anchor.key); + const top = index === undefined ? undefined : state.positionAtIndex(index); + const size = state.sizes.get(anchor.key); + if (index === undefined || top === undefined || size === undefined) return null; + // Rewrapped text grows with its row, so the reader's line sits at the same share of the + // row rather than the same pixel offset into it. + return { index, top, offsetWithinRow: (anchor.offsetWithinRow * size) / anchor.size }; +} + +/** The scroll offset that puts the reader's line back under the header at the current sizes. */ +export function resolveThreadFeedReflowOffset( + anchor: ThreadFeedReflowRowAnchor, + state: ThreadFeedReflowListState, + layout: ThreadFeedReflowLayout, +): number | undefined { + const point = resolveReflowAnchorPoint(anchor, state); + return point + ? point.top + point.offsetWithinRow - layout.headerInset + layout.rowsTop + : undefined; +} + +export function resolveThreadFeedReflowScroll( + anchor: ThreadFeedReflowRowAnchor, + state: ThreadFeedReflowListState, + layout: ThreadFeedReflowLayout, +): { readonly index: number; readonly viewOffset: number } | null { + const point = resolveReflowAnchorPoint(anchor, state); + if (!point) return null; + if (Math.abs(readingLine(state, layout) - (point.top + point.offsetWithinRow)) < 1) return null; + return { index: point.index, viewOffset: layout.headerInset - point.offsetWithinRow }; +} diff --git a/apps/mobile/src/features/threads/thread-inspector-content-stack.tsx b/apps/mobile/src/features/threads/thread-inspector-content-stack.tsx index b36218cd29aa8..fd2748574075e 100644 --- a/apps/mobile/src/features/threads/thread-inspector-content-stack.tsx +++ b/apps/mobile/src/features/threads/thread-inspector-content-stack.tsx @@ -2,6 +2,7 @@ import { useEffect, useState, type ReactNode } from "react"; import { View } from "react-native"; import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary"; +import { NativeInspectorContent } from "../../native/NativeInspectorContent"; export type ThreadInspectorMode = "route" | "git" | "files"; @@ -33,7 +34,9 @@ function InspectorContentPane(props: { ( - + + + )} > {props.children} diff --git a/apps/mobile/src/features/threads/useThreadHeaderOptions.tsx b/apps/mobile/src/features/threads/useThreadHeaderOptions.tsx index 366c2640b4c88..2153918ab0647 100644 --- a/apps/mobile/src/features/threads/useThreadHeaderOptions.tsx +++ b/apps/mobile/src/features/threads/useThreadHeaderOptions.tsx @@ -100,23 +100,6 @@ export function useThreadHeaderOptions(props: { [navigation], ); - const duoRightHeaderItems = useMemo( - () => [ - ...threadCenterHeaderItems, - { type: "spacing", spacing: 8 }, - withNativeGlassHeaderItem({ - type: "button" as const, - axisBehavior: "verticalPreferred", - identifier: "thread-right-new-task", - label: "New task", - accessibilityLabel: "New task", - icon: { name: "square.and.pencil", type: "sfSymbol" as const }, - onPress: () => navigation.navigate("NewTaskSheet", { screen: "NewTask" }), - }), - ], - [navigation, threadCenterHeaderItems], - ); - const options: AppNativeStackNavigationOptions = { headerShown: true, headerTitle: props.title, @@ -133,12 +116,9 @@ export function useThreadHeaderOptions(props: { : canGoBack ? undefined : () => compactHomeHeaderItems, + // The workspace navigator adds compose to the Duo detail column's bar. unstable_headerRightItems: () => - usesDuoHeader - ? duoRightHeaderItems - : layout.usesSplitView - ? threadCenterHeaderItems - : compactRightHeaderItems, + usesDuoHeader || layout.usesSplitView ? threadCenterHeaderItems : compactRightHeaderItems, unstable_headerToolbarItems: () => [], unstable_headerSubtitle: props.usesNativeHeaderGlass ? props.subtitle : undefined, contentStyle: undefined, @@ -154,7 +134,6 @@ export function useThreadHeaderOptions(props: { splitLeftHeaderItems, threadCenterHeaderItems, compactRightHeaderItems, - duoRightHeaderItems, usesDuoHeader, environmentId, threadId, diff --git a/apps/mobile/src/features/threads/worktree-setup-card.tsx b/apps/mobile/src/features/threads/worktree-setup-card.tsx index 45a5bb9404d74..7495399edd2c4 100644 --- a/apps/mobile/src/features/threads/worktree-setup-card.tsx +++ b/apps/mobile/src/features/threads/worktree-setup-card.tsx @@ -84,7 +84,7 @@ export function WorktreeSetupCard(props: WorktreeSetupCardProps) { accessibilityRole="button" accessibilityLabel={ backgroundSetup - ? `${scriptName} is still running. Show setup progress.` + ? `Background setup is still running: ${scriptName}. Show setup progress.` : "Worktree setup details" } accessibilityState={{ expanded: detailsOpen }} @@ -116,7 +116,7 @@ export function WorktreeSetupCard(props: WorktreeSetupCardProps) { /> ) : null} - {backgroundSetup ? scriptName : "Details"} + {backgroundSetup ? "Background setup" : "Details"} {!backgroundSetup ? ( diff --git a/apps/mobile/src/features/workspace/WorkspaceRootScreen.tsx b/apps/mobile/src/features/workspace/WorkspaceRootScreen.tsx index 98040a69c0f43..97a11068057c0 100644 --- a/apps/mobile/src/features/workspace/WorkspaceRootScreen.tsx +++ b/apps/mobile/src/features/workspace/WorkspaceRootScreen.tsx @@ -5,11 +5,13 @@ import { useKeyboardState } from "react-native-keyboard-controller"; import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context"; import { CompactBrandTitle } from "../../components/CompactBrandTitle"; +import { isDuoDevice } from "../../lib/device-type"; import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader"; import { NativeStackScreenOptions } from "../../native/StackHeader"; import { NativePrimaryColumnContext } from "../../native/v5-workspace-context"; import { useDeviceType, + useDuoBottomBarInset, useNativeColumnLayoutMetrics, useNativeLayoutMetrics, } from "../../native/native-layout-metrics"; @@ -24,7 +26,7 @@ import { useWorkspaceTabs, } from "./WorkspaceTabsContext"; import { WorkspaceToolbar } from "./WorkspaceToolbar"; -import { WORKSPACE_DOCK, workspaceToolbarHeight } from "./workspace-tabs-state"; +import { WORKSPACE_DOCK, WORKSPACE_TOOLBAR, workspaceToolbarHeight } from "./workspace-tabs-state"; import { WorkspaceSidebarTabs } from "./WorkspaceSidebarTabs"; import { useSidebarWorkspaceTabs, useSystemWorkspaceTabBar } from "./useSystemWorkspaceTabBar"; @@ -69,6 +71,7 @@ function WorkspaceRootContent() { (nativeMetrics !== null && nativeMetrics.verticalBarEdge !== "none")); const width = columnMetrics?.width ?? windowWidth; const insets = useSafeAreaInsets(); + const bottomBarInset = useDuoBottomBarInset(); const keyboardHeight = useKeyboardState((keyboard) => keyboard.height); const workspace = useWorkspaceTabs()!; const { state } = workspace; @@ -88,14 +91,18 @@ function WorkspaceRootContent() { ); const tab = state.tabs[state.selectedTab]; const bottomClearance = - Platform.OS === "ios" - ? Math.max(insets.bottom, keyboardHeight) + - (systemTabBar || sidebarTabs || tab.searchMode !== "resting" - ? 16 - : WORKSPACE_DOCK.height + WORKSPACE_DOCK.bottomGap + 16) - : keyboardHeight > 0 && tab.searchMode !== "resting" - ? keyboardHeight + 64 - : Math.max(insets.bottom, 12) + workspaceToolbarHeight(tab.searchMode) + 16; + Platform.OS === "ios" && isDuoDevice(deviceType) + ? Math.max(bottomBarInset ?? Math.max(insets.bottom, 12), keyboardHeight + 8) + + WORKSPACE_TOOLBAR.height + + 16 + : Platform.OS === "ios" + ? Math.max(insets.bottom, keyboardHeight) + + (systemTabBar || sidebarTabs || tab.searchMode !== "resting" + ? 16 + : WORKSPACE_DOCK.height + WORKSPACE_DOCK.bottomGap + 16) + : keyboardHeight > 0 && tab.searchMode !== "resting" + ? keyboardHeight + 64 + : Math.max(insets.bottom, 12) + workspaceToolbarHeight(tab.searchMode) + 16; const context = useMemo(() => ({ ...workspace, bottomClearance }), [workspace, bottomClearance]); return ( @@ -112,7 +119,6 @@ function WorkspaceRootContent() { headerShown: true, unstable_headerLeftItems: () => [], headerTitle: renderHeaderTitle, - ...(state.selectedTab === "threads" ? {} : { nativeSidebarFilter: undefined }), }} /> ) : ( diff --git a/apps/mobile/src/features/workspace/WorkspaceSearchField.tsx b/apps/mobile/src/features/workspace/WorkspaceSearchField.tsx new file mode 100644 index 0000000000000..98fb746e71d19 --- /dev/null +++ b/apps/mobile/src/features/workspace/WorkspaceSearchField.tsx @@ -0,0 +1,60 @@ +import type { Ref } from "react"; +import { Keyboard, Pressable, TextInput, View, type TextInputInstance } from "react-native"; +import { useResolveClassNames } from "uniwind"; + +import { SymbolView } from "../../components/ui/AppSymbol"; +import { GlassSurface } from "../../components/ui/GlassSurface"; +import { WORKSPACE_TOOLBAR, type WorkspaceTab } from "./workspace-tabs-state"; + +export function WorkspaceSearchField({ + ref, + ...props +}: { + readonly ref?: Ref; + readonly tab: WorkspaceTab; + readonly query: string; + readonly onChangeQuery: (query: string) => void; + readonly onFocus: () => void; + readonly onBlur?: () => void; + readonly onClear: () => void; +}) { + const inputStyle = useResolveClassNames("text-foreground font-sans text-base"); + const placeholderStyle = useResolveClassNames("text-foreground-muted"); + const label = props.tab === "pullRequests" ? "Search pull requests" : "Search threads"; + return ( + + + + Keyboard.dismiss()} + autoCapitalize="none" + autoCorrect={false} + returnKeyType="search" + maxLength={props.tab === "pullRequests" ? 200 : undefined} + style={[inputStyle, { flex: 1, minWidth: 0, paddingHorizontal: 8, paddingVertical: 0 }]} + /> + {props.query ? ( + + + + ) : null} + + + ); +} diff --git a/apps/mobile/src/features/workspace/WorkspaceToolbar.ios.tsx b/apps/mobile/src/features/workspace/WorkspaceToolbar.ios.tsx index af815639fabc1..00febb5781f96 100644 --- a/apps/mobile/src/features/workspace/WorkspaceToolbar.ios.tsx +++ b/apps/mobile/src/features/workspace/WorkspaceToolbar.ios.tsx @@ -1,16 +1,24 @@ import { Toolbar } from "../../components/ui/Toolbar"; import { useFocusEffect, useNavigation } from "@react-navigation/native"; -import { use, useCallback, useEffect, useRef } from "react"; -import { Platform } from "react-native"; -import { useDeviceType, useNativeLayoutMetrics } from "../../native/native-layout-metrics"; +import { use, useCallback, useEffect, useRef, type ReactNode } from "react"; +import { Platform, Pressable, type TextInputInstance } from "react-native"; +import { useReanimatedKeyboardAnimation } from "react-native-keyboard-controller"; +import Animated, { useAnimatedStyle } from "react-native-reanimated"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; +import { isDuoDevice } from "../../lib/device-type"; +import { useDeviceType, useDuoBottomBarInset } from "../../native/native-layout-metrics"; import type { SearchBarCommands } from "react-native-screens"; +import { SymbolView } from "../../components/ui/AppSymbol"; +import { GlassSurface } from "../../components/ui/GlassSurface"; import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass"; import { NativeStackScreenOptions } from "../../native/StackHeader"; import { NativeWorkspaceTabActivityContext } from "../../native/v5-workspace-context"; import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands"; import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout"; import { useWorkspaceTabs } from "./WorkspaceTabsContext"; +import { WorkspaceSearchField } from "./WorkspaceSearchField"; +import { WORKSPACE_TOOLBAR } from "./workspace-tabs-state"; import { useSidebarWorkspaceTabs } from "./useSystemWorkspaceTabBar"; import { useSelectWorkspaceTab } from "./useSelectWorkspaceTab"; import { useMobileNavigationTheme } from "../../lib/useMobileNavigationTheme"; @@ -18,26 +26,61 @@ import { useMobileNavigationTheme } from "../../lib/useMobileNavigationTheme"; // Tabler's git-pull-request geometry, shared with the UIKit tab bar. const PULL_REQUEST_ICON = require("../../../assets/icons/pull-request.png"); +/** + * Rises once the keyboard reaches its content. UIKit also reports keyboards without height, with a + * hardware keyboard and around a fold, and those must not move it. + */ +function AboveKeyboard(props: { readonly bottom: number; readonly children: ReactNode }) { + const keyboard = useReanimatedKeyboardAnimation(); + const { bottom } = props; + const lift = useAnimatedStyle(() => ({ + transform: [{ translateY: Math.min(0, keyboard.height.value + bottom - 8) }], + })); + return ( + + {props.children} + + ); +} + export function WorkspaceToolbar(props: { readonly onNewTask: () => void; readonly sidebar?: boolean; }) { const workspace = useWorkspaceTabs()!; const navigation = useNavigation(); - const metrics = useNativeLayoutMetrics(); const deviceType = useDeviceType(); const sidebarTabs = useSidebarWorkspaceTabs(); const selectTab = useSelectWorkspaceTab(); const selectedTint = useMobileNavigationTheme().colors.primary; + // On the Duo, compose belongs to the threads tab, in the detail column's bar when unfolded. const nativeToolbarCompose = Platform.OS === "ios" && - (deviceType === "pad" || - sidebarTabs !== null || - (metrics?.verticalBarEdge ?? "none") !== "none"); + (isDuoDevice(deviceType) + ? deviceType === "duo-folded" && workspace.state.selectedTab === "threads" + : deviceType === "pad"); + // The Duo searches from a field at the bottom of the list in every pose. UIKit has no such + // placement once the vertical bar holds the toolbar, and re-placing its search controller on + // each fold replaces the search field. + const listSearch = isDuoDevice(deviceType); + const insets = useSafeAreaInsets(); + const bottomBarInset = useDuoBottomBarInset(); const { isTabActive } = workspace; const tabActive = use(NativeWorkspaceTabActivityContext)?.active ?? true; const { panes, togglePrimarySidebar } = useAdaptiveWorkspaceLayout(); const searchRef = useRef(null); + const fieldRef = useRef(null); const tab = workspace.state.tabs[workspace.state.selectedTab]; const selectedTab = workspace.state.selectedTab; const enterSearch = useCallback(() => { @@ -51,10 +94,25 @@ export function WorkspaceToolbar(props: { }, [workspace, selectedTab, props.sidebar, panes.primarySidebarVisible, togglePrimarySidebar]); const focusSearch = useCallback(() => { if (!workspace.isTabActive(selectedTab)) return false; + if (listSearch) { + fieldRef.current?.focus(); + return true; + } if (!NATIVE_LIQUID_GLASS_SUPPORTED) enterSearch(); searchRef.current?.focus(); return true; - }, [workspace, selectedTab, enterSearch]); + }, [workspace, selectedTab, listSearch, enterSearch]); + const cancelSearch = useCallback(() => { + workspace.recordScrollOffset(selectedTab, tab.searchEntryOffset); + workspace.dispatch({ type: "cancel", tab: selectedTab }); + }, [workspace, selectedTab, tab.searchEntryOffset]); + const searchFocused = useCallback( + () => + tab.searchMode === "resting" + ? enterSearch() + : workspace.dispatch({ type: "search", tab: selectedTab }), + [tab.searchMode, enterSearch, workspace, selectedTab], + ); useHardwareKeyboardCommand("focusSearch", focusSearch); const restoreSearch = useCallback(() => { if (isTabActive(selectedTab) && tab.searchMode !== "resting") @@ -79,7 +137,7 @@ export function WorkspaceToolbar(props: { // Liquid Glass keeps search mounted as UIKit's own header button, which // morphs into the field; swapping a stacked bar in and out cannot animate. headerSearchBarOptions: - NATIVE_LIQUID_GLASS_SUPPORTED || tab.searchMode !== "resting" + !listSearch && (NATIVE_LIQUID_GLASS_SUPPORTED || tab.searchMode !== "resting") ? { ref: searchRef, autoFocus: tab.searchMode === "active", @@ -92,10 +150,7 @@ export function WorkspaceToolbar(props: { placeholder: selectedTab === "pullRequests" ? "Search pull requests" : "Search threads", cancelButtonText: "✕", - onFocus: () => - tab.searchMode === "resting" - ? enterSearch() - : workspace.dispatch({ type: "search", tab: selectedTab }), + onFocus: searchFocused, onBlur: () => workspace.dispatch({ type: "expand", tab: selectedTab }), onSearchButtonPress: () => searchRef.current?.blur(), onChangeText: ({ nativeEvent }) => @@ -104,10 +159,7 @@ export function WorkspaceToolbar(props: { query: nativeEvent.text, tab: selectedTab, }), - onCancelButtonPress: () => { - workspace.recordScrollOffset(selectedTab, tab.searchEntryOffset); - workspace.dispatch({ type: "cancel", tab: selectedTab }); - }, + onCancelButtonPress: cancelSearch, } : undefined, }} @@ -164,6 +216,45 @@ export function WorkspaceToolbar(props: { /> ) : null} + {listSearch ? ( + + + workspace.dispatch({ type: "query", query, tab: selectedTab }) + } + onFocus={searchFocused} + onBlur={() => workspace.dispatch({ type: "expand", tab: selectedTab })} + onClear={() => { + workspace.dispatch({ type: "query", query: "", tab: selectedTab }); + fieldRef.current?.focus(); + }} + /> + {tab.searchMode === "resting" ? null : ( + + { + cancelSearch(); + fieldRef.current?.blur(); + }} + className="flex-1 items-center justify-center" + > + + + + )} + + ) : null} ); } diff --git a/apps/mobile/src/features/workspace/WorkspaceToolbar.tsx b/apps/mobile/src/features/workspace/WorkspaceToolbar.tsx index a659bdcd33d08..73c8a9e8733df 100644 --- a/apps/mobile/src/features/workspace/WorkspaceToolbar.tsx +++ b/apps/mobile/src/features/workspace/WorkspaceToolbar.tsx @@ -5,19 +5,18 @@ import { Keyboard, Platform, Pressable, - TextInput, View, useWindowDimensions, type TextInputInstance, } from "react-native"; import { KeyboardStickyView, useKeyboardState } from "react-native-keyboard-controller"; import { useSafeAreaInsets } from "react-native-safe-area-context"; -import { useResolveClassNames } from "uniwind"; import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol"; import { GlassSurface } from "../../components/ui/GlassSurface"; import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands"; import { WorkspaceDock } from "./WorkspaceDock"; +import { WorkspaceSearchField } from "./WorkspaceSearchField"; import { useWorkspaceTabs } from "./WorkspaceTabsContext"; import { WORKSPACE_TOOLBAR, type WorkspaceTab } from "./workspace-tabs-state"; import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs"; @@ -60,8 +59,6 @@ export function WorkspaceToolbar(props: { const edge = width < 360 ? 12 : WORKSPACE_TOOLBAR.edge; const gap = width < 360 ? 6 : WORKSPACE_TOOLBAR.gap; const keyboardVisible = useKeyboardState((state) => state.isVisible); - const inputStyle = useResolveClassNames("text-foreground font-sans text-base"); - const placeholderStyle = useResolveClassNames("text-foreground-muted"); const focusSearch = useCallback(() => { if (!workspace) return false; const tab = workspace.state.selectedTab; @@ -126,50 +123,17 @@ export function WorkspaceToolbar(props: { onPress={() => dispatch({ type: "expand" })} /> ) : null} - - - - dispatch({ type: "query", query })} - onFocus={() => dispatch({ type: "search" })} - onSubmitEditing={() => Keyboard.dismiss()} - autoCapitalize="none" - autoCorrect={false} - returnKeyType="search" - maxLength={state.selectedTab === "pullRequests" ? 200 : undefined} - style={[ - inputStyle, - { flex: 1, minWidth: 0, paddingHorizontal: 8, paddingVertical: 0 }, - ]} - /> - {tab.query ? ( - { - dispatch({ type: "query", query: "" }); - focusSearch(); - }} - className="h-11 w-11 items-center justify-center" - > - - - ) : null} - - + dispatch({ type: "query", query })} + onFocus={() => dispatch({ type: "search" })} + onClear={() => { + dispatch({ type: "query", query: "" }); + focusSearch(); + }} + /> ) : null} diff --git a/apps/mobile/src/lib/layout.ts b/apps/mobile/src/lib/layout.ts index 8b1e344826e60..111bb2b40fce6 100644 --- a/apps/mobile/src/lib/layout.ts +++ b/apps/mobile/src/lib/layout.ts @@ -58,6 +58,8 @@ export interface Layout { export interface WorkspacePaneLayout { readonly primarySidebarVisible: boolean; + /** Whether the sidebar shows once a collapsed split expands; independent of the current width. */ + readonly primarySidebarWhenExpanded: boolean; readonly primarySidebarSuppressedByAuxiliary: boolean; readonly contentPaneWidth: number; readonly supportsAuxiliaryPane: boolean; @@ -215,6 +217,7 @@ export function deriveWorkspacePaneLayout(input: { return { primarySidebarVisible, + primarySidebarWhenExpanded: input.primarySidebarPreferredVisible, primarySidebarSuppressedByAuxiliary, contentPaneWidth: Math.max(0, viewportWidth - primarySidebarWidth), supportsAuxiliaryPane: fileInspector.supported, @@ -235,6 +238,7 @@ export function deriveWorkspacePaneLayout(input: { return { primarySidebarVisible: preferredPrimarySidebarVisible, + primarySidebarWhenExpanded: input.primarySidebarPreferredVisible, primarySidebarSuppressedByAuxiliary: false, contentPaneWidth, supportsAuxiliaryPane, diff --git a/apps/mobile/src/lib/markdownMedia.test.ts b/apps/mobile/src/lib/markdownMedia.test.ts index 33fec670e41ea..ef7cca311146f 100644 --- a/apps/mobile/src/lib/markdownMedia.test.ts +++ b/apps/mobile/src/lib/markdownMedia.test.ts @@ -38,10 +38,10 @@ describe("resolveMarkdownMediaPreview", () => { ["/tmp/frame%23one.png:12", "/tmp/frame#one.png"], ["/tmp/frame%3Fone.png:12:3", "/tmp/frame?one.png"], ["/tmp/frame%2523one.png:12", "/tmp/frame%23one.png"], - ["file://server/share/frame.png", "\\\\server\\share\\frame.png"], - ["\\\\server\\share\\frame.png", "\\\\server\\share\\frame.png"], - ])("keeps encoded filename and UNC semantics for %s", (href, path) => { - expect(resolveMarkdownMediaPreview(href, input)).toMatchObject({ + ["file://server/share/frame.png", "\\\\server\\share\\frame.png", "\\\\server\\share"], + ["\\\\server\\share\\frame.png", "\\\\server\\share\\frame.png", "\\\\server\\share"], + ])("keeps encoded filename and UNC semantics for %s", (href, path, workspaceRoot = "/repo") => { + expect(resolveMarkdownMediaPreview(href, { ...input, workspaceRoot })).toMatchObject({ kind: "image", source: { resource: { path }, diff --git a/apps/mobile/src/lib/reserved-regions.ts b/apps/mobile/src/lib/reserved-regions.ts index c212dffd311f4..f88af9239c367 100644 --- a/apps/mobile/src/lib/reserved-regions.ts +++ b/apps/mobile/src/lib/reserved-regions.ts @@ -19,6 +19,8 @@ export interface NativeLayoutMetrics { readonly right: number; }; readonly reservedRegions: ReadonlyArray; + /** How far above the bottom edge UIKit floats a 48pt bottom bar, level with its tab bar. iOS 27.1+. */ + readonly bottomBarInset?: number; } export function deriveBottomControlInsets(metrics: NativeLayoutMetrics | null) { diff --git a/apps/mobile/src/native/NativeHeaderToolbar.test.tsx b/apps/mobile/src/native/NativeHeaderToolbar.test.tsx index 3c522bf7dc6bf..60fe05661f4cb 100644 --- a/apps/mobile/src/native/NativeHeaderToolbar.test.tsx +++ b/apps/mobile/src/native/NativeHeaderToolbar.test.tsx @@ -3,22 +3,34 @@ import { act, createContext, type ReactElement } from "react"; import { createRoot, type Root } from "react-dom/client"; import { afterEach, expect, it, vi } from "vite-plus/test"; +type HeaderOptions = { + unstable_headerLeftItems?: () => NativeStackHeaderItem[]; + unstable_headerRightItems?: () => NativeStackHeaderItem[]; + unstable_headerToolbarItems?: () => NativeStackHeaderItem[]; +}; + const harness = vi.hoisted(() => ({ params: { path: ["first", "guide.pdf"] }, + appliedOptions: {} as HeaderOptions, renderedItems: [] as NativeStackHeaderItem[], setOptionsCalls: 0, openedDocuments: [] as string[], })); -// Native headers retain the actions materialized when navigation applies options. +// Native headers retain the actions materialized when navigation applies options. Like React +// Navigation, the header renders again only when the options are no longer shallowly equal. vi.mock("@react-navigation/native", () => { const navigation = { - setOptions(options: { - unstable_headerLeftItems?: () => NativeStackHeaderItem[]; - unstable_headerRightItems?: () => NativeStackHeaderItem[]; - unstable_headerToolbarItems?: () => NativeStackHeaderItem[]; - }) { + setOptions(options: HeaderOptions) { harness.setOptionsCalls += 1; + const previous: Record = harness.appliedOptions; + const next: Record = { ...previous, ...options }; + harness.appliedOptions = next; + if ( + Object.keys(next).length === Object.keys(previous).length && + Object.keys(next).every((key) => next[key] === previous[key]) + ) + return; harness.renderedItems = options.unstable_headerLeftItems?.() ?? options.unstable_headerRightItems?.() ?? @@ -104,6 +116,7 @@ function openRenderedDocument() { afterEach(() => { act(() => root?.unmount()); root = null; + harness.appliedOptions = {}; harness.renderedItems = []; harness.setOptionsCalls = 0; harness.openedDocuments = []; diff --git a/apps/mobile/src/native/NativeHeaderToolbar.tsx b/apps/mobile/src/native/NativeHeaderToolbar.tsx index 2e6e7059880b9..3f7f98a4b2324 100644 --- a/apps/mobile/src/native/NativeHeaderToolbar.tsx +++ b/apps/mobile/src/native/NativeHeaderToolbar.tsx @@ -42,6 +42,10 @@ type NativeStackHeaderAxisBehavior = Extract< NativeStackHeaderItem, { type: "button" } >["axisBehavior"]; +type NativeStackHeaderVisibilityPriority = Extract< + NativeStackHeaderItem, + { type: "button" } +>["visibilityPriority"]; type NativeToolbarItem = NativeStackHeaderItem | HeaderBarButtonSearchBarPlacementItem; type NativeStackOptionsWithToolbar = NativeStackNavigationOptions & { unstable_headerToolbarItems?: () => NativeToolbarItem[]; @@ -166,6 +170,7 @@ function convertToolbarChild(child: ReactNode): NativeToolbarItem | null { ? child.props.variant : "plain", identifier: typeof child.props.identifier === "string" ? child.props.identifier : undefined, + visibilityPriority: child.props.visibilityPriority as NativeStackHeaderVisibilityPriority, }; } @@ -277,6 +282,7 @@ function NativeHeaderToolbarButton(_props: { readonly tintColor?: ColorValue; readonly variant?: "plain" | "done" | "prominent"; readonly identifier?: string; + readonly visibilityPriority?: NativeStackHeaderVisibilityPriority; }) { return null; } diff --git a/apps/mobile/src/native/NativeInspectorContent.tsx b/apps/mobile/src/native/NativeInspectorContent.tsx new file mode 100644 index 0000000000000..4907618f2d4b6 --- /dev/null +++ b/apps/mobile/src/native/NativeInspectorContent.tsx @@ -0,0 +1,17 @@ +import type { ReactNode } from "react"; +import { SafeAreaView } from "react-native-safe-area-context"; + +import { useNativeWorkspaceColumnsSupported } from "./NativeWorkspaceColumns"; + +// Pads with the inspector column's insets, which the column leaves to its panes so their +// native headers lay out against the vertical bar themselves. +export function NativeInspectorContent(props: { readonly children: ReactNode }) { + const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported(); + if (!usesNativeWorkspaceColumns) return <>{props.children}; + + return ( + + {props.children} + + ); +} diff --git a/apps/mobile/src/native/NativeSheetContent.tsx b/apps/mobile/src/native/NativeSheetContent.tsx deleted file mode 100644 index ec44dc0dde2b6..0000000000000 --- a/apps/mobile/src/native/NativeSheetContent.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import type { ReactNode } from "react"; -import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context"; - -import { useNativeWorkspaceColumnsSupported } from "./NativeWorkspaceColumns"; - -export function NativeSheetContent(props: { readonly children: ReactNode }) { - const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported(); - if (!usesNativeWorkspaceColumns) return <>{props.children}; - - return ( - - - {props.children} - - - ); -} diff --git a/apps/mobile/src/native/StackHeader.tsx b/apps/mobile/src/native/StackHeader.tsx index 698a345035cca..ae9783f39dd6c 100644 --- a/apps/mobile/src/native/StackHeader.tsx +++ b/apps/mobile/src/native/StackHeader.tsx @@ -1,6 +1,5 @@ import { useNavigation, type ParamListBase } from "@react-navigation/native"; import type { - NativeStackHeaderItemMenu, NativeStackNavigationOptions, NativeStackNavigationProp, } from "@react-navigation/native-stack"; @@ -20,7 +19,6 @@ export type AppNativeStackNavigationOptions = Omit< "headerTintColor" | "unstable_headerLeftItems" | "unstable_headerRightItems" > & { readonly nativeContentInsetHorizontally?: boolean; - readonly nativeSidebarFilter?: NativeStackHeaderItemMenu; readonly headerTintColor?: string | ColorValue; readonly unstable_headerCenterItems?: unknown; readonly unstable_headerLeftItems?: unknown; @@ -201,8 +199,19 @@ export function NativeStackScreenOptions(props: { return; } lastAppliedOptionsSignatureRef.current = signature; - navigation.setOptions(stableOptions); - }, [navigation, props.optionsVersion, stableOptions, tabActive]); + // React Navigation keeps a screen's descriptor while its options are shallowly equal. The + // stabilized factories keep their identity, so one whose output changed needs a new wrapper + // to reach the header. + optionFunctionWrappersRef.current = new Map(); + navigation.setOptions( + stabilizeOptionFunctions( + normalizedOptions, + "options", + latestOptionFunctionsRef.current, + optionFunctionWrappersRef.current, + ) as NativeStackNavigationOptions, + ); + }, [navigation, normalizedOptions, props.optionsVersion, stableOptions, tabActive]); useEffect(() => { if (!navigation || !props.listeners) { diff --git a/apps/mobile/src/native/V5StackHeader.ios.tsx b/apps/mobile/src/native/V5StackHeader.ios.tsx index 85419d80353e5..13720678c3f37 100644 --- a/apps/mobile/src/native/V5StackHeader.ios.tsx +++ b/apps/mobile/src/native/V5StackHeader.ios.tsx @@ -128,6 +128,8 @@ function convertItems(items: NativeStackHeaderItem[], prefix: string): HeaderIte axisBehavior: item.axisBehavior, icon: convertIcon(item.icon), onPress: item.disabled ? undefined : item.onPress, + visibilityPriority: + item.visibilityPriority === "default" ? "standard" : item.visibilityPriority, variant: item.variant, tintColor: item.tintColor, hidesSharedBackground: item.hidesSharedBackground, @@ -139,36 +141,32 @@ function convertItems(items: NativeStackHeaderItem[], prefix: string): HeaderIte export function V5StackHeader(props: { readonly options: Options; readonly canGoBack: boolean; - readonly primary?: boolean; - readonly sidebarFilter?: NativeStackHeaderItemMenu; + /** Workspace split columns share the vertical bar with the workspace tab bar. */ + readonly column?: "primary" | "detail"; + /** The workspace's compose action, shown as its own group in this column's bar. */ + readonly onCompose?: () => void; }) { const { options } = props; const theme = useMobileNavigationTheme(); const nativeMetrics = useNativeLayoutMetrics(); const deviceType = useDeviceType(); const searchRef = useRef(null); - const usesDuoToolbarRail = - deviceType === "duo-unfolded" && (nativeMetrics?.verticalBarEdge ?? "none") !== "none"; const itemProps = { tintColor: options.headerTintColor, canGoBack: props.canGoBack }; const leading = convertItems(options.unstable_headerLeftItems?.(itemProps) ?? [], "leading"); - const trailingItems = [ - ...(options.unstable_headerCenterItems?.() ?? []), - ...(options.unstable_headerRightItems?.(itemProps) ?? []), - ]; - // Keep the sidebar's filter actions when UIKit moves the menu to the detail rail. - if (usesDuoToolbarRail && !props.primary && props.sidebarFilter) { - trailingItems.push({ - ...props.sidebarFilter, - identifier: "home-filter", - axisBehavior: "verticalPreferred", - }); - } - const trailing = convertItems(trailingItems, "trailing"); + const trailing = convertItems( + [ + ...(options.unstable_headerCenterItems?.() ?? []), + ...(options.unstable_headerRightItems?.(itemProps) ?? []), + ], + "trailing", + ); const toolbar = options.unstable_headerToolbarItems?.() ?? []; const mailSearch = toolbar.find( (item): item is HeaderBarButtonMailSearchToolbarItem => item.type === "mailSearchToolbar", ); const bottomSearch = Boolean(mailSearch) && deviceType !== "pad"; + // A vertical bar keeps fixed spaces at full length and separates items itself. + const spacesSearch = bottomSearch && (nativeMetrics?.verticalBarEdge ?? "none") === "none"; const bottom = toolbar.flatMap((item, index) => { if (item.type === "mailSearchToolbar") return []; if (item.type === "searchBarPlacement") @@ -180,7 +178,6 @@ export function V5StackHeader(props: { bottom.push({ type: "item", id: mailSearch.filterButtonId ?? "filter", - axisBehavior: bottomSearch ? "horizontalOnly" : undefined, icon: { type: "sfSymbol", name: mailSearch.filterSystemImageName ?? "line.3.horizontal.decrease", @@ -188,37 +185,46 @@ export function V5StackHeader(props: { menu: convertMenu(mailSearch.filterMenu, "filter-menu"), }); if (bottomSearch) { - if (bottom.length) + if (spacesSearch && bottom.length) bottom.push({ type: "spacer", id: "before-search", sizing: "fixed", width: 8 }); - bottom.push({ - type: "item", - id: "home-search", - axisBehavior: "horizontalOnly", - searchBarPlacement: true, - }); - if (mailSearch.onComposePress) + bottom.push({ type: "item", id: "home-search", searchBarPlacement: true }); + if (spacesSearch && mailSearch.onComposePress) bottom.push({ type: "spacer", id: "after-search", sizing: "fixed", width: 8 }); } if (mailSearch.onComposePress) bottom.push({ type: "item", id: mailSearch.composeButtonId ?? "compose", - axisBehavior: bottomSearch ? "horizontalOnly" : undefined, identifier: "workspace-trailing-action", icon: { type: "sfSymbol", name: mailSearch.composeSystemImageName ?? "square.and.pencil" }, onPress: mailSearch.onComposePress, }); } - // Duo keeps compose at the bottom of a visible sidebar. On a single panel, - // the primary column owns the rail too; its separate UIToolbar is inaccessible. + // UIKit doesn't stack a column's toolbar against the workspace tab bar, which owns the + // bottom of the vertical bar and draws over it. Those columns keep the group in their + // navigation items. An expanded sidebar's toolbar stays horizontal, outside the bar. if ( + props.column && nativeMetrics && nativeMetrics.verticalBarEdge !== "none" && - (!props.primary || nativeMetrics.horizontalSizeClass === "compact") + (props.column === "detail" || nativeMetrics.horizontalSizeClass === "compact") ) { + if (trailing.length && bottom.length) + trailing.push({ type: "spacer", id: "toolbar-group", sizing: "fixed", width: 8 }); trailing.push(...bottom); bottom.length = 0; } + if (props.onCompose) { + if (trailing.length) + trailing.push({ type: "spacer", id: "compose-group", sizing: "fixed", width: 8 }); + trailing.push({ + type: "item", + id: "workspace-compose", + title: "New task", + icon: { type: "sfSymbol", name: "square.and.pencil" }, + onPress: props.onCompose, + }); + } const left = options.headerLeft?.(itemProps); const right = options.headerRight?.(itemProps); if (!options.unstable_headerLeftItems && isValidElement(left)) diff --git a/apps/mobile/src/native/createV5StackNavigator.ios.tsx b/apps/mobile/src/native/createV5StackNavigator.ios.tsx index 6433ab5002019..1c8cea900618f 100644 --- a/apps/mobile/src/native/createV5StackNavigator.ios.tsx +++ b/apps/mobile/src/native/createV5StackNavigator.ios.tsx @@ -369,6 +369,7 @@ export function V5SheetStackView(props: V5StackViewProps) { initialDetentIndex={options.sheetInitialDetentIndex} largestUndimmedDetentIndex={options.sheetLargestUndimmedDetentIndex} prefersGrabberVisible={options.sheetGrabberVisible} + prefersHorizontalBars={options.sheetPrefersHorizontalBars} preferredCornerRadius={options.sheetCornerRadius} prefersScrollingExpandsWhenScrolledToEdge={options.sheetExpandsWhenScrolledToEdge} nativeContainerStyle={{ diff --git a/apps/mobile/src/native/native-layout-metrics.tsx b/apps/mobile/src/native/native-layout-metrics.tsx index 44d12142d522e..195e7a2cec050 100644 --- a/apps/mobile/src/native/native-layout-metrics.tsx +++ b/apps/mobile/src/native/native-layout-metrics.tsx @@ -1,6 +1,6 @@ import { createContext, use, useState, type ReactNode } from "react"; import { Platform } from "react-native"; -import { deriveDeviceType, type DeviceType } from "../lib/device-type"; +import { deriveDeviceType, isDuoDevice, type DeviceType } from "../lib/device-type"; import type { NativeLayoutMetrics } from "../lib/reserved-regions"; import { NativeLayoutObserver } from "./NativeLayoutObserver"; @@ -38,3 +38,13 @@ export function useNativeColumnLayoutMetrics() { export function useDeviceType() { return use(DeviceTypeContext); } + +/** + * Where the Duo's floating bottom controls end in this column. Its tab bar floats below the safe + * area, and the controls beside it sit on the same line. + */ +export function useDuoBottomBarInset() { + const deviceType = useDeviceType(); + const inset = use(NativeColumnLayoutMetricsContext)?.bottomBarInset; + return isDuoDevice(deviceType) ? inset : undefined; +} diff --git a/apps/mobile/src/native/sheet-surface.ts b/apps/mobile/src/native/sheet-surface.ts index 7867b2b77e81f..9de5943a008e0 100644 --- a/apps/mobile/src/native/sheet-surface.ts +++ b/apps/mobile/src/native/sheet-surface.ts @@ -1,3 +1,11 @@ -export const FORM_SHEET_PRESENTATION_OPTIONS = { +import { Platform } from "react-native"; + +export const HORIZONTAL_FORM_SHEET_OPTIONS = { presentation: "formSheet" as const, + sheetPrefersHorizontalBars: true, }; + +export function formSheetDetents(initialDetent: number, androidExpandedDetent = 0.92) { + // Duo moves the status bar above the sheet only at the maximum native detent. + return [initialDetent, Platform.OS === "ios" ? 1 : androidExpandedDetent]; +} diff --git a/apps/mobile/src/native/useRestingTopOffset.test.tsx b/apps/mobile/src/native/useRestingTopOffset.test.tsx new file mode 100644 index 0000000000000..7be7e1d82c3b1 --- /dev/null +++ b/apps/mobile/src/native/useRestingTopOffset.test.tsx @@ -0,0 +1,73 @@ +import { act, useLayoutEffect } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, describe, expect, it } from "vite-plus/test"; + +import { useRestingTopOffset } from "./useRestingTopOffset"; + +let root: Root | null = null; +let latest: ReturnType | null = null; + +function Probe(props: { readonly topInset: number; readonly restoredOffset?: number }) { + const restingOffset = useRestingTopOffset( + props.topInset, + props.restoredOffset === undefined ? {} : { contentOffset: { x: 0, y: props.restoredOffset } }, + ); + useLayoutEffect(() => { + latest = restingOffset; + }); + return null; +} + +function render(topInset: number, restoredOffset?: number) { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + root ??= createRoot(document.createElement("div")); + act(() => root!.render()); +} + +function scrollTo(y: number) { + const event = { nativeEvent: { contentOffset: { x: 0, y } } } as Parameters< + ReturnType["onScroll"] + >[0]; + act(() => latest!.onScroll(event)); +} + +function offset() { + return latest!.contentOffset.y; +} + +afterEach(() => { + act(() => root?.unmount()); + root = null; + latest = null; +}); + +describe("useRestingTopOffset", () => { + it("keeps an untouched list below the header once the column's inset arrives", () => { + // The folded iPhone Duo's window has no top inset; the header's arrives after mount. + render(0); + render(54); + expect(offset()).toBe(-54); + }); + + it("does not move a list the reader scrolled when the inset changes", () => { + render(54); + scrollTo(300); + render(90); + expect(offset()).toBe(-54); + }); + + it("follows the inset again once the list is back at the top", () => { + render(54); + scrollTo(300); + render(90); + scrollTo(-90); + render(54); + expect(offset()).toBe(-54); + }); + + it("holds a restored position through an inset change", () => { + render(0, 1_200); + render(54); + expect(offset()).toBe(1_200); + }); +}); diff --git a/apps/mobile/src/native/useRestingTopOffset.ts b/apps/mobile/src/native/useRestingTopOffset.ts new file mode 100644 index 0000000000000..33fc6bd09b472 --- /dev/null +++ b/apps/mobile/src/native/useRestingTopOffset.ts @@ -0,0 +1,29 @@ +import { useState } from "react"; +import type { NativeScrollEvent, NativeSyntheticEvent, ScrollViewProps } from "react-native"; + +/** + * A scroll view with a manual top inset rests at `-topInset`, just below the header. The inset + * can change after mount: a column's safe area starts as the window's until UIKit measures it, + * and rotation or folding changes it again. While the view rests below the header it follows the + * inset; once scrolled away it holds the last resting offset, because RN re-applies a changed + * `contentOffset` prop and would move the reader. + */ +export function holdRestingTopOffset(held: number | null, scrollY: number, topInset: number) { + return Math.abs(scrollY + topInset) <= 1 ? null : (held ?? -topInset); +} + +export function useRestingTopOffset( + topInset: number, + props: Pick, +) { + // A list restoring a saved position mounts away from its resting offset. + const [held, setHeld] = useState(props.contentOffset?.y ?? null); + return { + contentOffset: { x: 0, y: held ?? -topInset }, + onScroll: (event: NativeSyntheticEvent) => { + const scrollY = event.nativeEvent.contentOffset.y; + setHeld((current) => holdRestingTopOffset(current, scrollY, topInset)); + props.onScroll?.(event); + }, + }; +} diff --git a/apps/mobile/src/reactCompilerCoverage.test.ts b/apps/mobile/src/reactCompilerCoverage.test.ts index fc6c04aa5833b..f51c729f319e4 100644 --- a/apps/mobile/src/reactCompilerCoverage.test.ts +++ b/apps/mobile/src/reactCompilerCoverage.test.ts @@ -66,8 +66,7 @@ interface CompilerEvent { // babel.config.js is the file Metro loads; the logger rides on the preset's // own react-compiler option so the plugin runs with Metro's exact settings. -function compilerBailouts(file: string): string[] { - const events: CompilerEvent[] = []; +function compileLikeMetro(file: string, events: CompilerEvent[], output: Record) { const babelConfig = requireFromMobile("./babel.config.js")({ cache: () => {} }); const presets = babelConfig.presets.map(([name, options]: [string, object]) => name === "babel-preset-expo" @@ -82,14 +81,20 @@ function compilerBailouts(file: string): string[] { ] : [name, options], ); - babel.transformFileSync(NodePath.join(mobileRoot, file), { + return babel.transformFileSync(NodePath.join(mobileRoot, file), { babelrc: false, configFile: false, cwd: mobileRoot, presets, caller: metroCaller, code: false, + ...output, }); +} + +function compilerBailouts(file: string): string[] { + const events: CompilerEvent[] = []; + compileLikeMetro(file, events, {}); return events .filter((event) => event.kind === "CompileError" || event.kind === "CompileSkip") .map( @@ -98,6 +103,47 @@ function compilerBailouts(file: string): string[] { ); } +interface AstNode { + readonly type: string; + readonly [key: string]: unknown; +} + +const isAstNode = (value: unknown): value is AstNode => + typeof value === "object" && value !== null && "type" in value && typeof value.type === "string"; + +function walkAst( + value: unknown, + visit: (node: AstNode, ancestors: readonly AstNode[]) => void, + ancestors: readonly AstNode[] = [], +) { + if (typeof value !== "object" || value === null) return; + const node = isAstNode(value) ? value : null; + if (node) visit(node, ancestors); + const childAncestors = node ? [...ancestors, node] : ancestors; + for (const child of Object.values(value)) walkAst(child, visit, childAncestors); +} + +// For each call to `callee`, whether it runs only on the cache-miss branch of +// an `if ($[n] !== dep)` block rather than on every render. +function compilerCachedCalls(file: string, callee: string): boolean[] { + const result = compileLikeMetro(file, [], { ast: true }); + const cached: boolean[] = []; + if (typeof result !== "object" || result === null || !("ast" in result)) return cached; + walkAst(result.ast, (node, ancestors) => { + if (node.type !== "CallExpression" || !isAstNode(node.callee)) return; + if (node.callee.type !== "Identifier" || node.callee.name !== callee) return; + cached.push( + ancestors.some( + (ancestor, index) => + ancestor.type === "IfStatement" && + ancestors[index + 1] === ancestor.consequent && + JSON.stringify(ancestor.test).includes('"name":"$"'), + ), + ); + }); + return cached; +} + describe("React Compiler coverage", () => { it("Metro's transformer applies the compiler", async () => { const { transformer } = await metroConfig; @@ -137,6 +183,14 @@ describe("React Compiler coverage", () => { } }); + // The compiler once silently dropped this cache, so every + // ThreadFeed render rebuilt the feed and handed LegendList a new data array. + it("caches the thread feed derivation", () => { + expect( + compilerCachedCalls("src/features/threads/ThreadFeed.tsx", "deriveThreadFeedPresentation"), + ).toEqual([true]); + }); + it("lists only files that exist", () => { expect(Object.keys(KNOWN_BAILOUTS).filter((file) => !sourceFiles.includes(file))).toEqual([]); }); diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index 3f66714c68815..640deb7f6bc27 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -6,6 +6,7 @@ const reactTests = [ "src/features/settings/SettingsServerControlsRouteScreen.test.tsx", "src/features/settings/components/BranchNamingSettings.test.tsx", "src/native/NativeHeaderToolbar.test.tsx", + "src/native/useRestingTopOffset.test.tsx", "src/state/use-selected-thread-git-actions.test.tsx", ]; diff --git a/apps/server/scripts/cli.ts b/apps/server/scripts/cli.ts index fca0adeb690cd..b8b47c2b2e878 100644 --- a/apps/server/scripts/cli.ts +++ b/apps/server/scripts/cli.ts @@ -11,6 +11,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { DEVELOPMENT_ICON_OVERRIDES } from "../../../scripts/lib/brand-assets.ts"; import { findEsmImportsOfExternalPackages } from "../../../scripts/lib/cli-executable-imports.ts"; +import rootPackageJson from "../../../package.json" with { type: "json" }; import { resolveSpawnCommand } from "@t3tools/shared/shell"; import { ServerCliBuildAssetMissingError, @@ -149,7 +150,7 @@ const buildExeCmd = Command.make( }), ).pipe( Command.withDescription( - "Build the server as a Node single-executable (needs a Node 25.7+ host for --build-sea). The binary still resolves native packages from a node_modules tree beside it.", + `Build the server as a Node single-executable. Native builds require Node ${rootPackageJson.engines.node}; explicit cross-target builds need a Node 25.7+ host for --build-sea. The binary still resolves native packages from a node_modules tree beside it.`, ), ); diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index a5d0a2f6616b4..05e6e9c3b1b83 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -17,6 +17,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Redacted from "effect/Redacted"; import * as Path from "effect/Path"; +import * as PlatformError from "effect/PlatformError"; import * as Schema from "effect/Schema"; import { HttpClient, HttpClientResponse, HttpServerResponse } from "effect/http"; import { vi } from "vite-plus/test"; @@ -359,6 +360,47 @@ describe("AssetAccess", () => { }).pipe(Effect.provide(layerTest)), ); + // Resolving `file://attacker.test/share/cat.jpg` from an agent's markdown sent the + // Windows user's NTLM credentials to attacker.test. + it.effect("never resolves a network media path outside the thread's project", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const resolved: Array = []; + const recordingFileSystem = FileSystem.FileSystem.of({ + ...fs, + realPath: (requestedPath) => { + resolved.push(requestedPath); + return Effect.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "FileSystem", + method: "realPath", + pathOrDescriptor: requestedPath, + }), + ); + }, + }); + const share = "//nas.test/share/project"; + for (const resource of [ + { + _tag: "media-file", + threadId: ThreadId.make("thread-1"), + path: "//attacker.test/s/a.png", + }, + { _tag: "draft-workspace-file", cwd: share, path: "//attacker.test/s/a.png" }, + { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: `${share}/a.png` }, + ] as const) { + const error = yield* issueAssetUrl({ resource, workspaceRoot: share }).pipe( + Effect.provideService(FileSystem.FileSystem, recordingFileSystem), + Effect.flip, + ); + expect(error._tag).toBe("AssetWorkspaceAssetNotFoundError"); + } + expect(resolved).toEqual([path.resolve(`${share}/a.png`)]); + }).pipe(Effect.provide(layerTest)), + ); + it.effect.skipIf(!symlinksSupported)( "rejects non-previewable files, disguised targets, and directories", () => diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index c25dce2494f26..853c07435b363 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -36,6 +36,7 @@ import { isProjectFaviconPath, PROJECT_FAVICON_FALLBACK_MARKER, } from "@t3tools/shared/projectFavicon"; +import { isNetworkPath } from "@t3tools/shared/path"; import { MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH, toolOutputImages } from "@t3tools/shared/toolOutput"; import * as Clock from "effect/Clock"; import * as Crypto from "effect/Crypto"; @@ -60,6 +61,7 @@ import * as ServerConfig from "../config.ts"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts"; +import { isWithinRoot } from "../workspace/KnownWorkspaces.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; import * as NativeAppIconResolver from "./NativeAppIconResolver.ts"; import { extractIcnsPng } from "./icns.ts"; @@ -349,11 +351,27 @@ const readImageDimensionsFromHeader = (filePath: string) => const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMediaFileAsset")( function* (input: { readonly requestedPath: string; + readonly workspaceRoot: string | undefined; readonly resource: AssetResource; readonly expiresAt: number; }) { const path = yield* Path.Path; - const canonicalFile = yield* resolveCanonicalFile(input.requestedPath).pipe( + // Resolving a network path makes Windows sign in to its host with the + // user's NTLM credentials, so only the thread's own project may be on a share. + // Windows reads a `\\?\` path as written, `..` included, so the lookup gets + // the resolved path this check approved. + const requestedPath = path.resolve(input.requestedPath); + if ( + isNetworkPath(input.requestedPath) && + (input.workspaceRoot === undefined || + !isWithinRoot(path, requestedPath, path.resolve(input.workspaceRoot))) + ) { + return yield* new AssetWorkspaceAssetNotFoundError({ + resource: input.resource, + checkedPath: input.requestedPath, + }); + } + const canonicalFile = yield* resolveCanonicalFile(requestedPath).pipe( Effect.mapError( (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }), ), @@ -524,6 +542,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i } const finalized = yield* finalizeAbsoluteMediaFileAsset({ requestedPath, + workspaceRoot: input.workspaceRoot, resource: input.resource, expiresAt, }); @@ -566,6 +585,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i if (path.isAbsolute(hostPath)) { const finalized = yield* finalizeAbsoluteMediaFileAsset({ requestedPath: hostPath, + workspaceRoot: draftWorkspaceRoot, resource: input.resource, expiresAt, }); diff --git a/apps/server/src/cli/server.ts b/apps/server/src/cli/server.ts index e9f0d7e19ae12..fee427cc7fa28 100644 --- a/apps/server/src/cli/server.ts +++ b/apps/server/src/cli/server.ts @@ -13,6 +13,13 @@ import { type CliServerFlags, resolveServerConfig, sharedServerCommandFlags } fr const encodeCommand = Schema.encodeEffect(Schema.fromJsonString(Schema.String)); +// The desktop launcher reads this process's stdout and stderr. Once it is gone, +// every log write fails, and Node turns an unhandled stream error into a crash +// that skips shutdown and leaves the ownership lock and runtime record behind. +function ignoreClosedLauncherPipe(error: NodeJS.ErrnoException): void { + if (error.code !== "EPIPE" && error.code !== "ERR_STREAM_DESTROYED") throw error; +} + const runServerCommand = Effect.fn("server.runServerCommand")(function* ( flags: CliServerFlags, options?: { @@ -25,6 +32,10 @@ const runServerCommand = Effect.fn("server.runServerCommand")(function* ( const config = yield* resolveServerConfig(flags, logLevel, options); const run = runServer.pipe(Effect.provideService(ServerConfig.ServerConfig, config)); if (config.mode !== "desktop" || config.desktopBootstrapToken === undefined) return yield* run; + yield* Effect.sync(() => { + process.stdout.on("error", ignoreClosedLauncherPipe); + process.stderr.on("error", ignoreClosedLauncherPipe); + }); return yield* Effect.raceFirst( run, awaitLauncherLoss().pipe( diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index ef6f71a46a2e2..3acbd697f5865 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -187,7 +187,9 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* ( const baseDir = typeof baseDirOrPrefix === "string" ? baseDirOrPrefix - : yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix }); + : // macOS temp dirs live under the /var -> /private/var symlink; storage cleanup's + // symlink guards compare resolved paths, so generated test dirs must be real paths. + yield* fs.realPath(yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix })); const derivedPaths = yield* deriveServerPaths(baseDir, devUrl); yield* ensureServerDirectories(derivedPaths); diff --git a/apps/server/src/diagnostics/ProcessDiagnostics.test.ts b/apps/server/src/diagnostics/ProcessDiagnostics.test.ts index b480b021375f3..5c981033a9953 100644 --- a/apps/server/src/diagnostics/ProcessDiagnostics.test.ts +++ b/apps/server/src/diagnostics/ProcessDiagnostics.test.ts @@ -15,6 +15,11 @@ import * as ResourceAttribution from "../resourceTelemetry/ResourceAttribution.t import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts"; import * as ProcessDiagnostics from "./ProcessDiagnostics.ts"; +// ProcessDiagnostics treats process.pid as the server, so the fixture PID is an +// offset from it. A fixed PID collides whenever the test worker is assigned it. +const SERVER_PID = process.pid; +const CHILD_PID = SERVER_PID + 1; + function makeNativeSnapshot( processes: ResourceMonitorSnapshotEvent["processes"], ): ResourceMonitorSnapshotEvent { @@ -71,7 +76,7 @@ describe("ProcessDiagnostics", () => { const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe( Effect.flatMap((processDiagnostics) => processDiagnostics.signal({ - pid: 4_242, + pid: CHILD_PID, startTimeMs: 2_000, signal: "SIGINT", }), @@ -80,10 +85,12 @@ describe("ProcessDiagnostics", () => { ); expect(result).toEqual({ - pid: 4242, + pid: CHILD_PID, signal: "SIGINT", signaled: false, - message: Option.some("Process 4242 no longer matches the selected process identity."), + message: Option.some( + `Process ${CHILD_PID} no longer matches the selected process identity.`, + ), }); }), ); @@ -92,8 +99,8 @@ describe("ProcessDiagnostics", () => { Effect.gen(function* () { const snapshot = makeNativeSnapshot([ { - pid: 4_242, - ppid: process.pid, + pid: CHILD_PID, + ppid: SERVER_PID, startTimeMs: 2_000, runTimeMs: 4_000, name: "agent", @@ -134,7 +141,7 @@ describe("ProcessDiagnostics", () => { const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe( Effect.flatMap((processDiagnostics) => processDiagnostics.signal({ - pid: 4_242, + pid: CHILD_PID, startTimeMs: 2_000, signal: "SIGINT", }), @@ -143,11 +150,11 @@ describe("ProcessDiagnostics", () => { ); expect(result).toEqual({ - pid: 4_242, + pid: CHILD_PID, signal: "SIGINT", signaled: false, message: Option.some( - "Could not refresh process 4242; refusing to signal a stale identity.", + `Could not refresh process ${CHILD_PID}; refusing to signal a stale identity.`, ), }); }), @@ -160,7 +167,7 @@ describe("ProcessDiagnostics", () => { ); const snapshot = makeNativeSnapshot([ { - pid: 4_242, + pid: CHILD_PID, ppid: 1, startTimeMs: 2_000, runTimeMs: 4_000, @@ -182,7 +189,7 @@ describe("ProcessDiagnostics", () => { type: "desktopTelemetry", sequence: 1, sampledAtUnixMs, - electronPid: 4_242, + electronPid: CHILD_PID, power: { source: "electron-main", idle: "false", @@ -198,7 +205,7 @@ describe("ProcessDiagnostics", () => { speedLimitPercent: Option.none(), electronProcesses: [ { - pid: 4_242, + pid: CHILD_PID, creationTimeMs: 2_000, type: "Browser", name: "electron", @@ -214,7 +221,7 @@ describe("ProcessDiagnostics", () => { const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe( Effect.flatMap((processDiagnostics) => processDiagnostics.signal({ - pid: 4_242, + pid: CHILD_PID, startTimeMs: 2_000, signal: "SIGKILL", }), @@ -223,10 +230,10 @@ describe("ProcessDiagnostics", () => { ); expect(result).toEqual({ - pid: 4_242, + pid: CHILD_PID, signal: "SIGKILL", signaled: false, - message: Option.some("Process 4242 is not a signalable T3 backend descendant."), + message: Option.some(`Process ${CHILD_PID} is not a signalable T3 backend descendant.`), }); const diagnostics = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe( diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 7bfc2c8027738..660e2de9cbd8b 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -17,6 +17,7 @@ import * as PlatformError from "effect/PlatformError"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; import { ChildProcessSpawner } from "effect/process"; import { expect } from "vite-plus/test"; import type { @@ -1076,6 +1077,62 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("branch PR lookup notifies linked threads when draft status changes", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/draft-status"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/draft-status"]); + const drafts = [false, true, true, false, false, true]; + const pullRequest = { + number: 1, + title: "Draft status", + url: "https://github.com/pingdotgg/codething-mvp/pull/1", + baseRefName: "main", + headRefName: "feature/draft-status", + state: "OPEN", + }; + const { manager } = yield* makeManager({ + ghScenario: { + prListSequence: [ + ...drafts.map((isDraft) => encodeCliJson([{ ...pullRequest, isDraft }])), + encodeCliJson([ + { + ...pullRequest, + number: 2, + url: "https://github.com/pingdotgg/codething-mvp/pull/2", + state: "MERGED", + }, + ]), + ], + }, + }); + const changes = yield* manager.subscribePullRequestStateChanges; + for (const isDraft of drafts) { + const pr = yield* manager.branchPullRequest( + { cwd: repoDir, branch: "feature/draft-status" }, + { refresh: true }, + ); + expect(pr?.isDraft === true).toBe(isDraft); + } + // A different PR ends collection without waiting on a background stream consumer. + yield* manager.branchPullRequest( + { cwd: repoDir, branch: "feature/draft-status" }, + { refresh: true }, + ); + const events = yield* Stream.runCollect( + changes.pipe(Stream.takeUntil((event) => event.number === 2, { excludeLast: true })), + ); + expect(events).toEqual([ + { host: "github.com", repository: "pingdotgg/codething-mvp", number: 1 }, + { host: "github.com", repository: "pingdotgg/codething-mvp", number: 1 }, + { host: "github.com", repository: "pingdotgg/codething-mvp", number: 1 }, + ]); + }), + ); + it.effect("branch PR lookup uses a saved tracked branch without changing checkout", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); @@ -1785,6 +1842,11 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { "gitlab.example.com/group/subgroup/repository", ], ["https://bitbucket.org/team/repository/pull-requests/42", "bitbucket.org/team/repository"], + ["https://codeberg.org/team/repository/pulls/42", "codeberg.org/team/repository"], + [ + "http://code.example:3000/forgejo/team/repository/pulls/42/files", + "code.example/forgejo/team/repository", + ], [ "https://dev.azure.com/org/project/_git/repository/pullrequest/42", "dev.azure.com/org/project/_git/repository", diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index bb180042c0344..1b5002ec110e8 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -260,7 +260,7 @@ export function pullRequestRepositoryKey(value: string): string | null { try { const url = new URL(value); const match = - /^(.*)(?:\/pull\/|\/-\/merge_requests\/|\/pull-requests\/|\/pullrequest\/)\d+(?:\/.*)?$/iu.exec( + /^(.*)(?:\/pulls?\/|\/-\/merge_requests\/|\/pull-requests\/|\/pullrequest\/)\d+(?:\/.*)?$/iu.exec( url.pathname, ); if (match?.[1] === undefined) return null; @@ -1195,21 +1195,27 @@ export const make = Effect.gen(function* () { return prLookupFailureTtl(streak); }; const pullRequestStateChanges = yield* PubSub.sliding(64); - const lookupStates = new Map(); + const lookupStates = new Map< + string, + { readonly state: PullRequestInfo["state"]; readonly isDraft: boolean } + >(); const noteLookupState = (pr: PullRequestInfo) => Effect.suspend(() => { const parsed = parseChangeRequestUrl(pr.url); if (parsed === null || parsed.number !== pr.number) return Effect.void; const key = normalizeThreadPullRequestKey(parsed); const id = threadPullRequestKeyOf(key); - const previous = lookupStates.get(id) ?? "open"; + const previous = lookupStates.get(id); lookupStates.delete(id); if (lookupStates.size >= PR_LOOKUP_CACHE_CAPACITY) { const oldest = lookupStates.keys().next().value; if (oldest !== undefined) lookupStates.delete(oldest); } - lookupStates.set(id, pr.state); - return previous === pr.state ? Effect.void : PubSub.publish(pullRequestStateChanges, key); + lookupStates.set(id, { state: pr.state, isDraft: pr.isDraft === true }); + return (previous?.state ?? "open") === pr.state && + (previous?.isDraft === true) === (pr.isDraft === true) + ? Effect.void + : PubSub.publish(pullRequestStateChanges, key); }); const prLookupCache = yield* Cache.makeWith( (key: string) => { diff --git a/apps/server/src/htmlRender/HtmlRender.test.ts b/apps/server/src/htmlRender/HtmlRender.test.ts index c317e6881e65b..1bbdf0e483ee4 100644 --- a/apps/server/src/htmlRender/HtmlRender.test.ts +++ b/apps/server/src/htmlRender/HtmlRender.test.ts @@ -1,11 +1,12 @@ // @effect-diagnostics nodeBuiltinImport:off - plain local servers stand in for LAN services. import * as NodeServices from "@effect/platform-node/NodeServices"; -import { describe, expect, it } from "@effect/vitest"; +import { assert, describe, expect, it } from "@effect/vitest"; import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Base64 from "effect/encoding/Base64"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; @@ -19,6 +20,7 @@ import * as NodeURL from "node:url"; import { resolveAttachmentPathById } from "../attachmentStore.ts"; import * as ServerConfig from "../config.ts"; import * as HtmlRender from "./HtmlRender.ts"; +import { HtmlRenderBrowserError } from "./headlessChrome.ts"; import * as PreviewBrowser from "../preview/PreviewBrowser.ts"; const TEST_BROWSER_ENV = "T3CODE_TEST_HEADLESS_SHELL"; @@ -287,6 +289,33 @@ describe("HtmlRender", () => { }), ); + // Windows reports ENOENT asynchronously for this path instead of throwing ENOTDIR. + describe.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "when the browser spawn throws synchronously", + () => { + it.live("reports a typed preview error", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const file = yield* fileSystem.makeTempFileScoped({ prefix: "t3-browser-spawn-" }); + const outcome = yield* HtmlRender.HtmlRender.use((htmlRender) => + htmlRender.preview({ html: "

x

" }).pipe(Effect.flip), + ).pipe( + Effect.provide(layerHtmlRender(path.join(file, "chrome-headless-shell"))), + Effect.exit, + ); + assert(Exit.isSuccess(outcome), "Expected a typed preview error."); + const error = outcome.value; + expect(error).toBeInstanceOf(HtmlRenderBrowserError); + expect(error.message).toBe( + "Headless Chrome could not render the page: the browser could not be started.", + ); + expect(error).toMatchObject({ cause: { code: "ENOTDIR" } }); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + }, + ); + it.live("keeps every local file but the page itself out of the browser", (ctx) => Effect.gen(function* () { const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV]; diff --git a/apps/server/src/htmlRender/headlessChrome.ts b/apps/server/src/htmlRender/headlessChrome.ts index 4ad26a4aa6838..d9339b9c46946 100644 --- a/apps/server/src/htmlRender/headlessChrome.ts +++ b/apps/server/src/htmlRender/headlessChrome.ts @@ -229,6 +229,13 @@ const launchBrowser = Effect.fnUntraced(function* (input: { (cause) => new HtmlRenderBrowserError({ reason: "the browser could not be started", cause }), ), + // Node throws some spawn errors synchronously, such as `spawn UNKNOWN` + // when policy blocks the executable; `mapError` cannot catch those. + Effect.catchDefect((cause) => + Effect.fail( + new HtmlRenderBrowserError({ reason: "the browser could not be started", cause }), + ), + ), ); let stderrTail = ""; diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 6e54be84ef863..85ccc3ab926e4 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -375,6 +375,53 @@ it.effect("decodes null optional arguments the way it decodes omitted ones", () }).pipe(Effect.provide(layerRecordingTools(calls))); }); +it.effect( + "clamps t3_thread_read page sizes above their maximum instead of rejecting the call", + () => { + const calls: Array = []; + return Effect.gen(function* () { + const thread = { threadId: "thread-clamped-arguments" }; + // Codex never shows the model these bounds, so an over-large page must still read. + yield* callTool("t3_thread_read", { + ...thread, + limit: 150, + runLimit: 80, + maxCharsPerItem: 60_000, + }); + yield* callTool("t3_thread_read", { + ...thread, + limit: 100, + runLimit: 50, + maxCharsPerItem: 50_000, + }); + yield* callTool("t3_thread_read", { ...thread, limit: 7, runLimit: 1, maxCharsPerItem: 1 }); + + expect(calls).toEqual([ + { ...thread, limit: 100, runLimit: 50, maxCharsPerItem: 50_000 }, + { ...thread, limit: 100, runLimit: 50, maxCharsPerItem: 50_000 }, + { ...thread, limit: 7, runLimit: 1, maxCharsPerItem: 1 }, + ]); + }).pipe(Effect.provide(layerRecordingTools(calls))); + }, +); + +it.effect.each(["limit", "runLimit", "maxCharsPerItem"])( + "still rejects a t3_thread_read %s below its minimum", + (field) => { + const calls: Array = []; + return Effect.gen(function* () { + // Zero is a different request than one item, so it fails rather than answering another question. + const rejected = yield* callTool("t3_thread_read", { + threadId: "thread-below-minimum", + [field]: 0, + }).pipe(Effect.flip); + + expect(String(rejected)).toContain("greater than or equal to 1"); + expect(calls).toEqual([]); + }).pipe(Effect.provide(layerRecordingTools(calls))); + }, +); + it.effect( "registers the pull request toolkit and surfaces a missing capability as a tool error", () => diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.test.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.test.ts new file mode 100644 index 0000000000000..75db3e4d59786 --- /dev/null +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.test.ts @@ -0,0 +1,16 @@ +import { expect, it } from "@effect/vitest"; +import { Tool } from "effect/ai"; + +import { OrchestratorToolkit } from "./tools.ts"; + +// Oversized page sizes clamp on decode, so the schema has no `maximum`; Codex also drops +// bounds from its TypeScript view. The description is the only place a model sees a limit. +it("states t3_thread_read page size limits in the parameter descriptions", () => { + const schema = Tool.getJsonSchema(OrchestratorToolkit.tools.t3_thread_read) as { + readonly properties: Readonly>; + }; + const limits = { limit: "100", runLimit: "50", maxCharsPerItem: "50000" }; + for (const [name, maximum] of Object.entries(limits)) { + expect(schema.properties[name]?.description, name).toContain(maximum); + } +}); diff --git a/apps/server/src/observability/Metrics.ts b/apps/server/src/observability/Metrics.ts index 6ba17819ceafb..9d3b3e13c0fcb 100644 --- a/apps/server/src/observability/Metrics.ts +++ b/apps/server/src/observability/Metrics.ts @@ -63,6 +63,18 @@ export const serverEventLoopDelayMax = Metric.gauge("t3_server_event_loop_delay_ attributes: { unit: "ms" }, }); +export const runsTotal = Metric.counter("t3_runs_total", { + description: "Runs that finished, by outcome. A later rollback does not count again.", +}); + +export const runDuration = Metric.timer("t3_run_duration", { + description: "Wall time of a run, from when it started to its terminal status.", +}); + +export const runQueueWait = Metric.timer("t3_run_queue_wait", { + description: "Time a run waited between being requested and starting.", +}); + export const gitCommandsTotal = Metric.counter("t3_git_commands_total", { description: "Total git commands executed by the server runtime.", }); diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts index d2bd8a7ac0315..bf50bbc8395ee 100644 --- a/apps/server/src/orchestration-v2/EventSink.ts +++ b/apps/server/src/orchestration-v2/EventSink.ts @@ -26,6 +26,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import { replayAndBufferProjectedLiveEvents } from "./LiveStreamBudget.ts"; import type { UnsequencedProjectEvent } from "../persistence/OrchestrationEventStore.ts"; import { projectDomainEventForWire } from "./WireProjection.ts"; +import { makeRunOutcomeRecorder, type RunOutcome } from "./RunMetrics.ts"; import * as CommandReceiptStore from "./CommandReceiptStore.ts"; import * as EffectOutbox from "./EffectOutbox.ts"; @@ -243,8 +244,23 @@ const layerBase: Layer.Layer< ); } }); - const publishStoredEvents = (events: ReadonlyArray) => - eventStore.publishCommitted(events).pipe(Effect.andThen(publishLiveEvents(events))); + const runOutcomes = makeRunOutcomeRecorder((threadId) => + // One payload row; unlike the shell, it still resolves a deleted child thread. + projectionStore + .getThread(threadId) + .pipe(Effect.map((thread) => thread.lineage.relationshipToParent === "subagent")), + ); + // Recorded before publication, so an interrupted publish cannot lose a committed outcome. + const publishStoredEvents = ( + events: ReadonlyArray, + outcomes: ReadonlyArray, + ) => + runOutcomes + .record(outcomes) + .pipe( + Effect.andThen(eventStore.publishCommitted(events)), + Effect.andThen(publishLiveEvents(events)), + ); // Transactions commit one at a time, but each writer publishes after its // commit. If a writer is descheduled in between, a later commit reaches @@ -373,6 +389,8 @@ const layerBase: Layer.Layer< updated_at = excluded.updated_at `; } + // Read lineage here, on the connection this transaction holds; see makeRunOutcomeRecorder. + return yield* runOutcomes.prepare(storedEvents); }); const writeEffect = Effect.fn("orchestrationV2.EventSink.write")(function* ( @@ -384,7 +402,7 @@ const layerBase: Layer.Layer< "orchestration_v2.thread_id": input.events[0]?.threadId ?? null, }); - return yield* commitThenPublish( + const { committed } = yield* commitThenPublish( Effect.gen(function* () { // Check ownership in the same transaction that claims the native session. const imported = input.unlessNativeThreadOwned; @@ -398,7 +416,7 @@ const layerBase: Layer.Layer< AND json_extract(payload_json, '$.nativeThreadRef.nativeId') = ${imported.nativeThreadRef.nativeId} LIMIT 1 `; - if (owners.length > 0) return []; + if (owners.length > 0) return { committed: [], outcomes: [] }; } // Checkpoint capture can finish after a cohort writer reads its parent run. // Merge in this transaction so the event log and projection keep that completion. @@ -433,18 +451,19 @@ const layerBase: Layer.Layer< ...(input.commandId === undefined ? {} : { commandId: input.commandId }), events: normalized, }); - yield* applyStoredEvents(committed); + const outcomes = yield* applyStoredEvents(committed); yield* effectOutbox.enqueue(input.effects); - return committed; + return { committed, outcomes }; }).pipe(Effect.withTracerEnabled(false)), - (storedEvents) => + ({ committed, outcomes }) => Effect.gen(function* () { if (input.effects.length > 0) { yield* effectOutbox.notifyAvailable(input.effects.length); } - yield* publishStoredEvents(storedEvents); + yield* publishStoredEvents(committed, outcomes); }), ); + return committed; }); const writeIfRunCurrentEffect = Effect.fn("orchestrationV2.EventSink.writeIfRunCurrent")( @@ -491,9 +510,9 @@ const layerBase: Layer.Layer< ...(input.commandId === undefined ? {} : { commandId: input.commandId }), events: normalized, }); - yield* applyStoredEvents(storedEvents); + const outcomes = yield* applyStoredEvents(storedEvents); yield* effectOutbox.enqueue(input.effects ?? []); - return { committed: true as const, storedEvents }; + return { committed: true as const, storedEvents, outcomes }; }), (result) => Effect.gen(function* () { @@ -501,7 +520,7 @@ const layerBase: Layer.Layer< if (input.effects !== undefined && input.effects.length > 0) { yield* effectOutbox.notifyAvailable(input.effects.length); } - yield* publishStoredEvents(result.storedEvents); + yield* publishStoredEvents(result.storedEvents, result.outcomes); }), ); }, @@ -556,10 +575,13 @@ const layerBase: Layer.Layer< ...(input.commandId === undefined ? {} : { commandId: input.commandId }), events: normalized, }); - yield* applyStoredEvents(storedEvents); - return { committed: true as const, storedEvents }; + const outcomes = yield* applyStoredEvents(storedEvents); + return { committed: true as const, storedEvents, outcomes }; }), - (result) => (result.committed ? publishStoredEvents(result.storedEvents) : Effect.void), + (result) => + result.committed + ? publishStoredEvents(result.storedEvents, result.outcomes) + : Effect.void, ); }); @@ -589,10 +611,13 @@ const layerBase: Layer.Layer< const normalized = yield* normalizeEvents(input.events); const storedEvents = yield* eventStore.append({ events: normalized }); - yield* applyStoredEvents(storedEvents); - return { committed: true as const, storedEvents }; + const outcomes = yield* applyStoredEvents(storedEvents); + return { committed: true as const, storedEvents, outcomes }; }), - (result) => (result.committed ? publishStoredEvents(result.storedEvents) : Effect.void), + (result) => + result.committed + ? publishStoredEvents(result.storedEvents, result.outcomes) + : Effect.void, ); }); @@ -642,7 +667,7 @@ const layerBase: Layer.Layer< new Error(`Command ${input.commandId} produced no orchestration events.`), ); } - yield* applyStoredEvents(storedEvents); + const outcomes = yield* applyStoredEvents(storedEvents); yield* effectOutbox.enqueue(input.effects); const receipt: CommandReceiptStore.CommandReceiptV2 = { commandId: input.commandId, @@ -661,7 +686,7 @@ const layerBase: Layer.Layer< threadId: input.threadId, ...input.cancelUnsettledEffects, }); - return { receipt, storedEvents, committed: true as const, cancelledEffectIds }; + return { receipt, storedEvents, outcomes, committed: true as const, cancelledEffectIds }; }), (result) => Effect.gen(function* () { @@ -669,7 +694,7 @@ const layerBase: Layer.Layer< if (result.committed && input.effects.length > 0) { yield* effectOutbox.notifyAvailable(input.effects.length); } - if (result.committed) yield* publishStoredEvents(result.storedEvents); + if (result.committed) yield* publishStoredEvents(result.storedEvents, result.outcomes); }), ); return { diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 0e7ecfa9f0147..8fca16a101725 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -7,6 +7,7 @@ import { NodeId, ProviderSessionId, ProviderThreadId, + ProviderTurnId, ProviderDriverKind, ProviderInstanceId, ProviderSetupError, @@ -271,6 +272,14 @@ function makeLocalCommandHarness(input: { readonly interruptRunBeforeOpenFailure?: boolean; readonly writeFailure?: unknown; readonly failReadsAfterRunning?: boolean; + readonly previousTurn?: { + readonly runStatus: "failed" | "completed"; + readonly turnStatus: "running" | "completed" | "interrupted"; + readonly differentThread?: boolean; + readonly liveSession?: boolean; + readonly interruptFailure?: boolean; + readonly interruptCurrentRun?: boolean; + }; }) { const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z"); const threadId = ThreadId.make("thread-native-account-command"); @@ -456,6 +465,74 @@ function makeLocalCommandHarness(input: { ), }; } + const previousTurnId = ProviderTurnId.make("previous-provider-turn"); + if (input.previousTurn !== undefined) { + const previousRunId = RunId.make("previous-failed-run"); + const previousAttemptId = RunAttemptId.make("previous-failed-attempt"); + const previousProviderThreadId = input.previousTurn.differentThread + ? oldProviderThreadId + : providerThreadId; + projection = { + ...projection, + runs: [ + { + ...run, + id: previousRunId, + ordinal: 1, + status: input.previousTurn.runStatus, + rootNodeId: NodeId.make("previous-root"), + activeAttemptId: previousAttemptId, + providerThreadId: previousProviderThreadId, + completedAt: now, + }, + run, + ], + providerThreads: [ + { + ...providerThread, + nativeThreadRef: { + driver: providerThread.driver, + nativeId: "existing-native-conversation", + strength: "strong", + }, + }, + ], + providerTurns: [ + { + id: previousTurnId, + providerThreadId: previousProviderThreadId, + nodeId: NodeId.make("previous-root"), + runAttemptId: previousAttemptId, + ordinal: 1, + nativeTurnRef: null, + status: input.previousTurn.turnStatus, + startedAt: now, + completedAt: input.previousTurn.turnStatus === "running" ? null : now, + }, + ], + }; + } + let providerBusy = + input.previousTurn?.runStatus === "failed" && + input.previousTurn.turnStatus === "running" && + !input.previousTurn.differentThread && + input.previousTurn.liveSession !== false; + const interruptTurn = vi.fn((request: ProviderAdapter.ProviderAdapterV2InterruptInput) => + Effect.gen(function* () { + expect(request.providerTurnId).toBe(previousTurnId); + expect(request.providerThread.id).toBe(providerThreadId); + if (input.previousTurn?.interruptFailure) { + return yield* new ProviderAdapter.ProviderAdapterInterruptError({ + driver: providerThread.driver, + providerThreadId, + providerTurnId: request.providerTurnId, + cause: "provider interrupt failed", + }); + } + providerBusy = false; + if (input.previousTurn?.interruptCurrentRun) interruptRun(); + }), + ); const events: Array = []; const interruptRun = () => { projection = { @@ -515,7 +592,7 @@ function makeLocalCommandHarness(input: { ), ), ) - : input.failReadsAfterRunning === true + : input.failReadsAfterRunning === true || input.previousTurn !== undefined ? Effect.succeed({ driver: providerThread.driver, providerSession: { @@ -531,14 +608,17 @@ function makeLocalCommandHarness(input: { lastError: null, }, ensureThread: () => Effect.succeed(providerThread), + resumeThread: () => Effect.succeed(projection.providerThreads[0]), } as never) : Effect.die("A local command must not open a native session."), ); const startRootRun = vi.fn< (input: RunExecutionService.RunExecutionServiceV2StartRootRunInput) => Effect.Effect >(() => - input.failReadsAfterRunning === true - ? Effect.void + input.failReadsAfterRunning === true || input.previousTurn !== undefined + ? Effect.suspend(() => + providerBusy ? Effect.die("The previous provider turn is still running.") : Effect.void, + ) : Effect.die("A local command must not start a native turn."), ); const failReadIfRunning = Effect.suspend(() => @@ -642,7 +722,19 @@ function makeLocalCommandHarness(input: { }), ), }), - Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ open }), + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ + open, + get: () => + Effect.succeed( + input.previousTurn?.liveSession === false + ? Option.none() + : Option.some({ + driver: providerThread.driver, + providerSessionId, + interruptTurn, + } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime), + ), + }), Layer.mock(ProviderAuthService.ProviderAuthService)({ tryHandlePromptCommand }), Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }), Layer.mock(RuntimePolicy.RuntimePolicyV2)({ @@ -662,6 +754,7 @@ function makeLocalCommandHarness(input: { open, writeIfRunCurrent, startRootRun, + interruptTurn, tryHandlePromptCommand, events, oldInstanceId, @@ -681,6 +774,106 @@ function makeLocalCommandHarness(input: { }; } +effectIt.effect("recovers an abandoned failed turn before continuing its native conversation", () => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "Continue", + previousTurn: { runStatus: "failed", turnStatus: "running" }, + }); + + yield* harness.start; + + expect(harness.interruptTurn).toHaveBeenCalledOnce(); + expect(harness.projection().runs.at(-1)?.status).toBe("running"); + expect(harness.projection().providerTurns[0]).toMatchObject({ + status: "interrupted", + completedAt: expect.anything(), + }); + expect(harness.startRootRun).toHaveBeenCalledOnce(); + expect(harness.startRootRun.mock.calls[0]?.[0].providerThread.nativeThreadRef?.nativeId).toBe( + "existing-native-conversation", + ); + }), +); + +effectIt.effect.each([ + { runStatus: "failed", turnStatus: "completed" }, + { runStatus: "completed", turnStatus: "completed" }, + { runStatus: "failed", turnStatus: "running", differentThread: true }, + { runStatus: "failed", turnStatus: "running", liveSession: false }, + { runStatus: "failed", turnStatus: "interrupted", interruptFailure: true }, +] as const)("continues without interrupting when recovery does not apply: %j", (previousTurn) => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ text: "Continue", previousTurn }); + + yield* harness.start; + + expect(harness.interruptTurn).not.toHaveBeenCalled(); + expect(harness.projection().runs.at(-1)?.status).toBe("running"); + }), +); + +effectIt.effect("does not start another turn when abandoned-turn cleanup fails", () => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "Continue", + previousTurn: { runStatus: "failed", turnStatus: "running", interruptFailure: true }, + }); + + yield* harness.start; + + expect(harness.interruptTurn).toHaveBeenCalledOnce(); + expect(harness.startRootRun).not.toHaveBeenCalled(); + expect(harness.projection().runs.at(-1)?.status).toBe("failed"); + }), +); + +effectIt.effect("retries abandoned-turn cleanup without failing the continuation early", () => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "Continue", + previousTurn: { runStatus: "failed", turnStatus: "running", interruptFailure: true }, + }); + + const error = yield* harness.startWithRetry.pipe(Effect.flip); + + expect(error._tag).toBe("ProviderTurnStartError"); + expect(harness.projection().runs.at(-1)?.status).toBe("starting"); + expect(harness.open).not.toHaveBeenCalled(); + }), +); + +effectIt.effect("does not start the continuation if recording recovery fails", () => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "Continue", + previousTurn: { runStatus: "failed", turnStatus: "running" }, + writeFailure: new Error("database unavailable"), + }); + + const error = yield* harness.start.pipe(Effect.flip); + + expect(error._tag).toBe("ProviderTurnStartError"); + expect(harness.projection().runs.at(-1)?.status).toBe("starting"); + expect(harness.projection().providerTurns[0]?.status).toBe("running"); + expect(harness.open).not.toHaveBeenCalled(); + }), +); + +effectIt.effect("does not resume a continuation stopped while recovery was in flight", () => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "Continue", + previousTurn: { runStatus: "failed", turnStatus: "running", interruptCurrentRun: true }, + }); + + yield* harness.start; + + expect(harness.projection().runs.at(-1)?.status).toBe("interrupted"); + expect(harness.open).not.toHaveBeenCalled(); + }), +); + effectIt.effect.each(["cleanup-first", "startup-first"])( "coordinates provider startup with %s", (order) => diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 325c4557636fc..89ae2cc2c0c13 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -541,26 +541,6 @@ export const layer: Layer.Layer< const existingSessionProjection = projection.providerSessions.find( (candidate) => candidate.id === providerSessionId, ); - const sessionResult = yield* Effect.result( - providerSessions.open({ - threadId: projection.thread.id, - providerSessionId, - modelSelection: run.modelSelection, - runtimePolicy: resolvedRuntimePolicy, - ...(existingSessionProjection === undefined - ? {} - : { resumeFromSession: existingSessionProjection }), - ...(providerThread.nativeThreadRef?.nativeId == null - ? {} - : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }), - ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined - ? {} - : { - initialProviderItemIdentityVersion: - providerThread.nativeMetadata.itemIdentityVersion, - }), - }), - ); const settleStartFailure = Effect.fn("ProviderTurnStartService.settleStartFailure")( function* (failed: { readonly signal: string; @@ -592,6 +572,91 @@ export const layer: Layer.Layer< }); }, ); + const failedRuns = new Map( + projection.runs + .filter( + (previous) => + previous.ordinal < run.ordinal && + previous.providerThreadId === providerThread.id && + previous.status === "failed", + ) + .map((previous) => [previous.activeAttemptId, previous] as const), + ); + const abandonedTurns = projection.providerTurns.flatMap((turn) => { + const previous = failedRuns.get(turn.runAttemptId); + return turn.providerThreadId === providerThread.id && + turn.status === "running" && + previous !== undefined && + turn.nodeId === previous.rootNodeId + ? [{ turn, run: previous }] + : []; + }); + const abandonedTurn = abandonedTurns.at(-1)?.turn; + if (abandonedTurn !== undefined) { + const liveSession = yield* providerSessions.get(providerSessionId); + if (Option.isSome(liveSession)) { + // Older versions could fail the run without stopping its provider. + // Recover that exact turn before reusing its native conversation. + const recovered = yield* Effect.result( + liveSession.value.interruptTurn({ + providerThread, + providerTurnId: abandonedTurn.id, + requestRuntimeRestart: true, + }), + ); + if (recovered._tag === "Failure") { + if (input.willRetry === true) return yield* recovered.failure; + yield* settleStartFailure({ + signal: "provider-turn-recovery-failure", + title: "Provider turn recovery failed", + error: recovered.failure, + }); + return; + } + } + const completedAt = yield* DateTime.now; + const repaired = yield* eventSink.writeIfRunCurrent({ + threadId: projection.thread.id, + runId: run.id, + activeAttemptId: attempt.id, + expectedStatus: "starting", + events: yield* Effect.forEach(abandonedTurns, ({ turn, run: failedRun }) => + Effect.gen(function* () { + return { + id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }), + type: "provider-turn.updated" as const, + threadId: projection.thread.id, + runId: failedRun.id, + nodeId: turn.nodeId, + providerInstanceId: failedRun.providerInstanceId, + occurredAt: completedAt, + payload: { ...turn, status: "interrupted" as const, completedAt }, + }; + }), + ), + }); + if (!repaired.committed) return; + } + const sessionResult = yield* Effect.result( + providerSessions.open({ + threadId: projection.thread.id, + providerSessionId, + modelSelection: run.modelSelection, + runtimePolicy: resolvedRuntimePolicy, + ...(existingSessionProjection === undefined + ? {} + : { resumeFromSession: existingSessionProjection }), + ...(providerThread.nativeThreadRef?.nativeId == null + ? {} + : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }), + ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined + ? {} + : { + initialProviderItemIdentityVersion: + providerThread.nativeMetadata.itemIdentityVersion, + }), + }), + ); if (sessionResult._tag === "Failure") { if (input.willRetry === true) return yield* sessionResult.failure; yield* settleStartFailure({ diff --git a/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts b/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts index b5058898783d0..54f3e4b25553e 100644 --- a/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts +++ b/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts @@ -913,6 +913,43 @@ describe("PullRequestSyncReactor", () => { ), ); + it.effect.each([true, false])( + "syncs linked draft status %s as soon as a reader reports a change", + (isDraft) => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const draft = yield* Ref.make(!isDraft); + const invalidated = yield* Ref.make>([]); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([ + makeThread("agent", { pullRequests: [makeLink(7, { isDraft: !isDraft })] }), + ]), + summary: (input) => + Ref.get(draft).pipe(Effect.map((isDraft) => makeSummary(input, { isDraft }))), + invalidate: ({ reference }) => + Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]), + }); + + yield* Effect.gen(function* () { + const reactor = yield* startAndSweep(fixture); + yield* Ref.set(draft, isDraft); + yield* Queue.offer(fixture.stateChanges, { + host: "github.com", + repository: "owner/repository", + number: 7, + }); + yield* Queue.take(fixture.snapshotReads); + yield* reactor.drain; + + assert.deepStrictEqual(yield* Ref.get(invalidated), [7]); + assert.deepStrictEqual( + (yield* Ref.get(fixture.syncCommands)).map((command) => command.snapshot.isDraft), + [isDraft], + ); + }).pipe(Effect.provide(fixture.layer)); + }), + ); + it.effect("preserves a refresh requested while an older host read is in flight", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index 4dcfaa069f5d7..e7937f8a1fc9f 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -2487,6 +2487,152 @@ it.effect("refreshes pull requests after a provider stream exits with an error", }), ); +it.effect.each(["failure", "defect", "interrupt-failure", "ownership-lost"] as const)( + "stops the live provider and background work before settling an ingestion %s", + (failureMode) => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const stopped = yield* Deferred.make(); + const backgroundWorkRunning = yield* Ref.make(true); + const backgroundWorkAtFinalization = yield* Ref.make(null); + const now = yield* DateTime.now; + const interrupts = yield* Ref.make< + ReadonlyArray + >([]); + const ids = backgroundScenarioIds(`ingestion:${failureMode}`); + const { observed, finalEvents } = yield* captureRootRunTermination({ + key: `ingestion:${failureMode}`, + initialProviderTurnId: null, + rejectTerminalWrite: failureMode === "ownership-lost", + shouldFinalizeRun: () => Effect.succeed(true), + startTurn: () => + Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(stopped))), + events: () => + Stream.unwrap( + Deferred.await(started).pipe( + Effect.as( + Stream.make({ + type: "provider_turn.updated" as const, + driver, + providerTurn: { + id: ids.rootProviderTurnId, + providerThreadId: ids.providerThreadId, + nodeId: ids.rootNodeId, + runAttemptId: ids.attemptId, + nativeTurnRef: null, + ordinal: 1, + status: "running" as const, + startedAt: now, + completedAt: null, + }, + }), + ), + ), + ), + ingestNormalized: () => { + const error = new ProviderEventIngestor.ProviderEventPublishError({ + providerSessionId: ProviderSessionId.make(`session:${failureMode}`), + eventCount: 1, + cause: new Error("SQLITE_FULL: database or disk is full"), + }); + return failureMode === "defect" ? Effect.die(error) : Effect.fail(error); + }, + interruptTurn: (input) => + Ref.update(interrupts, (current) => [...current, input]).pipe( + Effect.andThen( + input.requestRuntimeRestart === true && failureMode !== "interrupt-failure" + ? Ref.set(backgroundWorkRunning, false) + : Effect.void, + ), + Effect.andThen(Deferred.succeed(stopped, undefined)), + Effect.andThen( + failureMode === "interrupt-failure" + ? Effect.fail( + new ProviderAdapter.ProviderAdapterInterruptError({ + driver, + providerThreadId: input.providerThread.id, + providerTurnId: input.providerTurnId, + cause: "provider already exited", + }), + ) + : Effect.void, + ), + ), + beforeTerminalWrite: () => + Effect.gen(function* () { + const calls = yield* Ref.get(interrupts); + assert.equal(calls.length, 1); + assert.equal(calls[0]?.providerTurnId, ids.rootProviderTurnId); + assert.equal(calls[0]?.providerThread.id, ids.providerThreadId); + yield* Ref.set(backgroundWorkAtFinalization, yield* Ref.get(backgroundWorkRunning)); + return true; + }), + }); + if (failureMode === "ownership-lost") { + assert.deepEqual(finalEvents, []); + assert.deepEqual(observed, []); + } else { + assert.equal( + yield* Ref.get(backgroundWorkAtFinalization), + failureMode === "interrupt-failure", + ); + assert.deepEqual(observed, ["run:failed", "pull-requests-refreshed"]); + const repaired = finalEvents.find((event) => event.type === "provider-turn.updated"); + if (failureMode === "interrupt-failure") { + assert.isUndefined(repaired); + } else { + assert.equal(repaired?.payload.id, ids.rootProviderTurnId); + assert.equal(repaired?.payload.status, "interrupted"); + assert.isNotNull(repaired?.payload.completedAt); + } + } + }), +); + +it.effect("does not interrupt an ended provider when its terminal write fails", () => + Effect.gen(function* () { + const interrupts = yield* Ref.make(0); + const writes = yield* Ref.make(0); + const { observed } = yield* captureRootRunTermination({ + key: "terminal-write-failure", + shouldFinalizeRun: () => Effect.succeed(true), + events: (ids) => Stream.make(rootTerminalEvent(ids, "completed")), + interruptTurn: () => Ref.update(interrupts, (count) => count + 1), + beforeTerminalWrite: () => + Effect.gen(function* () { + if ((yield* Ref.updateAndGet(writes, (count) => count + 1)) === 1) { + return yield* new EventSink.EventSinkWriteError({ eventCount: 1 }); + } + return true; + }), + }); + assert.equal(yield* Ref.get(interrupts), 0); + assert.deepEqual(observed, ["run:failed", "pull-requests-refreshed"]); + }), +); + +it.effect("does not interrupt a provider when ingestion fails before the root turn is known", () => + Effect.gen(function* () { + const interrupts = yield* Ref.make(0); + const { observed } = yield* captureRootRunTermination({ + key: "unknown-turn-stream-error", + initialProviderTurnId: null, + shouldFinalizeRun: () => Effect.succeed(true), + events: () => + Stream.fail( + new ProviderAdapter.ProviderAdapterEventStreamError({ + driver, + providerSessionId: ProviderSessionId.make("session:unknown-turn"), + cause: "provider process exited", + }), + ), + interruptTurn: () => Ref.update(interrupts, (count) => count + 1), + }); + assert.equal(yield* Ref.get(interrupts), 0); + assert.deepEqual(observed, ["run:failed", "pull-requests-refreshed"]); + }), +); + it.effect("fails the run when its event stream ends without a root terminal", () => Effect.gen(function* () { const { observed, finalEvents } = yield* captureRootRunTermination({ @@ -2564,6 +2710,8 @@ function captureRootRunTermination(input: { ProviderAdapter.ProviderAdapterV2Error >; readonly startTurn?: ProviderAdapter.ProviderAdapterV2SessionRuntime["startTurn"]; + readonly interruptTurn?: ProviderAdapter.ProviderAdapterV2SessionRuntime["interruptTurn"]; + readonly initialProviderTurnId?: ProviderTurnId | null; readonly onStartFailure?: ( error: RunExecutionService.RunExecutionServiceV2Error, ) => Effect.Effect; @@ -2704,6 +2852,7 @@ function captureRootRunTermination(input: { ), }), startTurn: input.startTurn ?? (() => Effect.void), + interruptTurn: input.interruptTurn ?? (() => Effect.void), } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime, run: { id: ids.runId, @@ -2724,7 +2873,10 @@ function captureRootRunTermination(input: { } as OrchestrationV2ProviderThread, attempt: { id: ids.attemptId, - providerTurnId: ids.rootProviderTurnId, + providerTurnId: + input.initialProviderTurnId === undefined + ? ids.rootProviderTurnId + : input.initialProviderTurnId, } as OrchestrationV2RunAttempt, attemptId: ids.attemptId, providerTurnOrdinal: 1, diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 022b67d9cf48b..a2b4f1de5bcf2 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -622,6 +622,7 @@ export const layer: Layer.Layer< readonly shouldFinalizeRun?: () => Effect.Effect; readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect; readonly openRunOwnedSubagents?: OpenRunOwnedSubagentProjection; + readonly interruptedProviderTurn?: OrchestrationV2ProviderTurn; readonly terminal: ProviderTerminalEvent; readonly completedAt?: DateTime.Utc; readonly failureItemPersisted: boolean; @@ -743,6 +744,24 @@ export const layer: Layer.Layer< : [], events: [ ...cascadedSubagentEvents, + ...(input.interruptedProviderTurn === undefined + ? [] + : [ + { + id: yield* allocateEventId(), + type: "provider-turn.updated" as const, + threadId: input.run.threadId, + runId: input.run.id, + nodeId: input.rootNode.id, + providerInstanceId: input.run.providerInstanceId, + occurredAt: completedAt, + payload: { + ...input.interruptedProviderTurn, + status: "interrupted" as const, + completedAt, + }, + }, + ]), ...(finalizedAttempt === null ? [] : [ @@ -962,6 +981,7 @@ export const layer: Layer.Layer< const terminalEvent = yield* Ref.make(null); const latestTurnItemOrdinal = yield* Ref.make(input.providerTurnOrdinal * 100); const latestProviderThread = yield* Ref.make(input.providerThread); + const latestRootProviderTurn = yield* Ref.make(null); const routeIdentity: ProviderEventRouteIdentity = { threadId: input.run.threadId, runId: input.run.id, @@ -1318,6 +1338,13 @@ export const layer: Layer.Layer< Stream.tap(({ event, accepted }) => Effect.gen(function* () { if (!accepted) return; + if ( + event.type === "provider_turn.updated" && + event.providerTurn.runAttemptId === input.attempt.id && + event.providerTurn.providerThreadId === input.providerThread.id + ) { + yield* Ref.set(latestRootProviderTurn, event.providerTurn); + } let storedEventCount = 0; const deliveredEvent = filterAssistantEvent( event, @@ -1436,6 +1463,28 @@ export const layer: Layer.Layer< }); if (yield* Ref.get(rootRunFinalized)) return; const providerThread = yield* Ref.get(latestProviderThread); + const routing = yield* Ref.get(eventRouting); + // Stop background work too; the failed consumer cannot persist terminal events. + const interruptedProviderTurn = + routing.rootProviderTurnId !== null && !routing.rootTurnEnded + ? yield* input.session + .interruptTurn({ + providerThread, + providerTurnId: routing.rootProviderTurnId, + requestRuntimeRestart: true, + }) + .pipe( + Effect.as(yield* Ref.get(latestRootProviderTurn)), + Effect.catchCauseIf( + (interruptCause) => !Cause.hasInterruptsOnly(interruptCause), + (interruptCause) => + Effect.logWarning( + "orchestration V2 failed to interrupt turn after ingestion failure", + { runId: input.run.id, cause: interruptCause }, + ).pipe(Effect.as(null)), + ), + ) + : null; const latestItemOrdinal = yield* Ref.get(latestTurnItemOrdinal); const openSubagents = yield* Ref.get(openRunOwnedSubagents); let nextRetryWarningAt = completedAt; @@ -1450,6 +1499,7 @@ export const layer: Layer.Layer< expectedStatus: "running", }, openRunOwnedSubagents: openSubagents, + ...(interruptedProviderTurn === null ? {} : { interruptedProviderTurn }), completedAt, terminal: makeFailedTerminalEvent( makeProviderFailure({ cause: Cause.squash(cause), class: "unknown" }), diff --git a/apps/server/src/orchestration-v2/RunMetrics.test.ts b/apps/server/src/orchestration-v2/RunMetrics.test.ts new file mode 100644 index 0000000000000..fead1c29a969e --- /dev/null +++ b/apps/server/src/orchestration-v2/RunMetrics.test.ts @@ -0,0 +1,284 @@ +import { assert, describe, it } from "@effect/vitest"; +import { + EventId, + MessageId, + ProjectId, + ProviderInstanceId, + RunId, + ThreadId, + type OrchestrationV2AppThread, + type OrchestrationV2DomainEvent, + type OrchestrationV2Run, + type OrchestrationV2StoredEvent, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as Metric from "effect/Metric"; +import * as Option from "effect/Option"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as EventSink from "./EventSink.ts"; +import * as EventStore from "./EventStore.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import { makeRunOutcomeRecorder } from "./RunMetrics.ts"; + +const at = (iso: string) => DateTime.makeUnsafe(iso); +const threadId = ThreadId.make("thread:metrics"); + +// Each test labels its runs with its own provider, since the metric registry is shared. +const runUpdated = ( + sequence: number, + provider: string, + run: Pick & + Partial, +): OrchestrationV2StoredEvent => ({ + sequence, + commandId: null, + event: { + type: "run.updated", + id: EventId.make(`event:${provider}:${sequence}`), + threadId, + occurredAt: at("2026-10-19T12:00:00.000Z"), + payload: { + threadId, + ordinal: 1, + providerInstanceId: ProviderInstanceId.make(provider), + modelSelection: { instanceId: ProviderInstanceId.make(provider), model: "claude-opus-5-5" }, + requestedAt: at("2026-10-19T12:00:00.000Z"), + ...run, + } as OrchestrationV2Run, + }, +}); + +// Prepare inside the transaction, record after its commit, as the EventSink does. +const commitWith = + (recorder: ReturnType>) => + (events: ReadonlyArray) => + recorder.prepare(events).pipe(Effect.flatMap(recorder.record)); + +const runSnapshots = (provider: string) => + Metric.snapshot.pipe( + Effect.map((snapshots) => + snapshots.filter( + (snapshot) => + snapshot.id.startsWith("t3_run") && snapshot.attributes?.["provider"] === provider, + ), + ), + ); + +describe("makeRunOutcomeRecorder", () => { + it.effect("records a finished run once, labelled, with its queue wait and duration", () => + Effect.gen(function* () { + // A subagent thread's first run carries no delegatedTaskId; only its lineage says delegated. + const recorder = makeRunOutcomeRecorder(() => Effect.succeed(true)); + const record = commitWith(recorder); + const finished = { + id: RunId.make("run:metrics:once"), + status: "completed" as const, + startedAt: at("2026-10-19T12:00:30.000Z"), + completedAt: at("2026-10-19T12:10:30.000Z"), + }; + + yield* record([runUpdated(1, "p1", { ...finished, status: "running", completedAt: null })]); + // A transaction that rolls back prepares and never records; it must not reserve the run. + yield* recorder.prepare([runUpdated(2, "p1", finished)]); + yield* record([runUpdated(2, "p1", finished)]); + // Later updates to a finished run, such as its checkpoint, are not another run. + yield* record([runUpdated(3, "p1", finished)]); + + const snapshots = yield* runSnapshots("p1"); + const byId = (id: string) => snapshots.find((snapshot) => snapshot.id === id); + const counter = byId("t3_runs_total"); + assert.strictEqual(counter?.type === "Counter" ? counter.state.count : undefined, 1); + assert.deepStrictEqual(counter?.attributes, { + provider: "p1", + modelFamily: "claude", + outcome: "completed", + delegated: "true", + }); + const histogramSum = (id: string) => { + const snapshot = byId(id); + return snapshot?.type === "Histogram" ? snapshot.state.sum : undefined; + }; + assert.strictEqual(histogramSum("t3_run_queue_wait"), 30_000); + assert.strictEqual(histogramSum("t3_run_duration"), 600_000); + }), + ); + + it.effect("does not count a rollback of a run that already finished", () => + Effect.gen(function* () { + // A fresh recorder stands in for a restart, which forgets the runs already counted. + const record = commitWith(makeRunOutcomeRecorder(() => Effect.succeed(false))); + yield* record([ + runUpdated(1, "p2", { + id: RunId.make("run:metrics:rolled-back"), + status: "rolled_back", + startedAt: at("2026-10-19T12:00:30.000Z"), + completedAt: at("2026-10-20T09:00:00.000Z"), + }), + ]); + + assert.deepStrictEqual(yield* runSnapshots("p2"), []); + }), + ); +}); + +describe("EventSink run outcomes", () => { + const parentId = ThreadId.make("thread:metrics:sink:parent"); + const childId = ThreadId.make("thread:metrics:sink:child"); + const provider = ProviderInstanceId.make("p-sink"); + const now = at("2026-10-19T12:00:00.000Z"); + const thread = (id: ThreadId, lineage: OrchestrationV2AppThread["lineage"]) => + ({ + type: "thread.created", + id: EventId.make(`event:${id}:created`), + threadId: id, + occurredAt: now, + payload: { + createdBy: "user", + creationSource: "web", + id, + projectId: ProjectId.make("project:metrics"), + title: id, + providerInstanceId: provider, + modelSelection: { instanceId: provider, model: "gpt-6.1" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + }) satisfies OrchestrationV2DomainEvent; + const runId = RunId.make("run:metrics:sink:child"); + const run = (status: OrchestrationV2Run["status"]): OrchestrationV2Run => ({ + id: runId, + threadId: childId, + ordinal: 1, + providerInstanceId: provider, + modelSelection: { instanceId: provider, model: "gpt-6.1" }, + providerThreadId: null, + userMessageId: MessageId.make("message:metrics:sink"), + rootNodeId: null, + activeAttemptId: null, + status, + queuePosition: null, + requestedAt: now, + startedAt: at("2026-10-19T12:00:10.000Z"), + completedAt: status === "running" ? null : at("2026-10-19T12:01:10.000Z"), + checkpointId: null, + contextHandoffId: null, + }); + const runEvent = (type: "run.created" | "run.updated", status: OrchestrationV2Run["status"]) => + ({ + type, + id: EventId.make(`event:${runId}:${status}`), + threadId: childId, + runId, + occurredAt: now, + payload: run(status), + }) satisfies OrchestrationV2DomainEvent; + + it.effect("reads lineage inside the transaction, so a concurrent writer cannot deadlock it", () => + Effect.gen(function* () { + const lookupEntered = yield* Deferred.make(); + const releaseLookup = yield* Deferred.make(); + const writerStarted = yield* Deferred.make(); + const pausedLookup = Layer.effect( + ProjectionStore.ProjectionStoreV2, + Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const sql = yield* SqlClient.SqlClient; + let paused = false; + return { + ...store, + getThread: (id) => + Effect.gen(function* () { + if (id === childId && !paused) { + paused = true; + const inTransaction = Option.isSome( + yield* Effect.serviceOption(sql.transactionService), + ); + yield* Deferred.succeed(lookupEntered, inTransaction); + // Outside the transaction this read would wait on the writer it is racing. + if (inTransaction) yield* Deferred.await(releaseLookup); + } + return yield* store.getThread(id); + }), + }; + }), + ); + const layer = EventSink.layer.pipe( + Layer.provideMerge(pausedLookup), + Layer.provideMerge( + Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe( + Layer.provideMerge(SqlitePersistence.layerMemory), + ), + ), + ); + + yield* Effect.gen(function* () { + const sink = yield* EventSink.EventSinkV2; + yield* sink.write({ + events: [ + thread(parentId, { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: parentId, + }), + thread(childId, { + parentThreadId: parentId, + relationshipToParent: "subagent", + rootThreadId: parentId, + }), + runEvent("run.created", "running"), + ], + }); + const terminal = yield* sink + .write({ events: [runEvent("run.updated", "completed")] }) + .pipe(Effect.forkScoped); + assert.isTrue(yield* Deferred.await(lookupEntered), "lineage read outside the transaction"); + const unrelated = yield* Deferred.succeed(writerStarted, undefined).pipe( + Effect.andThen( + sink.write({ + events: [ + thread(ThreadId.make("thread:metrics:sink:other"), { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: ThreadId.make("thread:metrics:sink:other"), + }), + ], + }), + ), + Effect.forkScoped, + ); + yield* Deferred.await(writerStarted); + yield* Deferred.succeed(releaseLookup, undefined); + + const [terminalEvents, unrelatedEvents] = [ + yield* Fiber.join(terminal), + yield* Fiber.join(unrelated), + ]; + assert.strictEqual(terminalEvents.length, 1); + assert.strictEqual(unrelatedEvents.length, 1); + const counter = (yield* runSnapshots("p-sink")).find( + (snapshot) => snapshot.id === "t3_runs_total", + ); + assert.strictEqual(counter?.type === "Counter" ? counter.state.count : undefined, 1); + assert.strictEqual(counter?.attributes?.["delegated"], "true"); + }).pipe(Effect.provide(layer)); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/RunMetrics.ts b/apps/server/src/orchestration-v2/RunMetrics.ts new file mode 100644 index 0000000000000..17b90d254418a --- /dev/null +++ b/apps/server/src/orchestration-v2/RunMetrics.ts @@ -0,0 +1,113 @@ +import type { + OrchestrationV2Run, + OrchestrationV2StoredEvent, + RunId, + ThreadId, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import type * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Metric from "effect/Metric"; + +import { normalizeModelMetricLabel } from "../observability/Attributes.ts"; +import { + metricAttributes, + runDuration, + runQueueWait, + runsTotal, +} from "../observability/Metrics.ts"; + +const REMEMBERED_RUNS = 4096; +// A rollback rewrites runs that already finished, stamping the rollback time as their completion, +// so it is not counted as an outcome. Declared here because ThreadManagementService imports +// EventSink. +const OUTCOMES: ReadonlySet = new Set([ + "completed", + "failed", + "cancelled", + "interrupted", +]); + +export interface RunOutcome { + readonly runId: RunId; + readonly attributes: ReturnType; + readonly queueWait: Duration.Duration | undefined; + readonly duration: Duration.Duration | undefined; +} + +/** + * Records each run once, when a committed event first shows it finished. A finished run's row is + * updated again later (its checkpoint, a settlement), so recently counted runs are remembered. + * + * A run carries `delegatedTaskId` only when a follow-up is associated with a task, so a subagent + * thread's first run is recognized by its thread's lineage instead. A failed lookup only costs the + * label: the events still commit and publish. + * + * `prepare` reads lineage, so the EventSink runs it inside the write transaction, on the + * connection that transaction already holds. `record` runs after the commit, under the publish + * lane, and must stay free of I/O: a read there waits for the writer connection while holding the + * lane, and the next writer holds that connection while it waits for the lane. + */ +export const makeRunOutcomeRecorder = ( + isSubagentThread: (threadId: ThreadId) => Effect.Effect, +) => { + const counted = new Set(); + // Untraced: both run for every committed batch inside the EventSink operation's span. + // Never reads or writes `counted`, so a transaction that rolls back reserves nothing. + const prepare = Effect.fnUntraced(function* (events: ReadonlyArray) { + const outcomes: Array = []; + // Every finished run is prepared, in order, even one already counted: an earlier outcome in + // this batch may evict it before `record` reaches it, so only `record` decides what counts. + // Only the lineage read is shared. + const delegatedThreads = new Map(); + for (const { event } of events) { + if (event.type !== "run.updated") continue; + const run = event.payload; + if (!OUTCOMES.has(run.status)) continue; + let delegated = run.delegatedTaskId !== undefined || delegatedThreads.get(run.threadId); + if (delegated === undefined) { + delegated = yield* isSubagentThread(run.threadId).pipe(Effect.orElseSucceed(() => false)); + delegatedThreads.set(run.threadId, delegated); + } + outcomes.push({ + runId: run.id, + attributes: metricAttributes({ + provider: run.providerInstanceId, + modelFamily: normalizeModelMetricLabel(run.modelSelection.model), + outcome: run.status, + delegated, + }), + queueWait: + run.startedAt === null ? undefined : DateTime.distance(run.requestedAt, run.startedAt), + duration: + run.startedAt === null || run.completedAt === null + ? undefined + : DateTime.distance(run.startedAt, run.completedAt), + }); + } + return outcomes; + }); + // Uninterruptible so a run is never marked counted with only part of its measurements. + const record = Effect.fnUntraced(function* (outcomes: ReadonlyArray) { + for (const outcome of outcomes) { + // Concurrent writers can prepare the same run; the first to publish counts it. + if (counted.has(outcome.runId)) continue; + counted.add(outcome.runId); + if (counted.size > REMEMBERED_RUNS) counted.delete(counted.values().next().value!); + yield* Metric.update(Metric.withAttributes(runsTotal, outcome.attributes), 1); + if (outcome.queueWait !== undefined) { + yield* Metric.update( + Metric.withAttributes(runQueueWait, outcome.attributes), + outcome.queueWait, + ); + } + if (outcome.duration !== undefined) { + yield* Metric.update( + Metric.withAttributes(runDuration, outcome.attributes), + outcome.duration, + ); + } + } + }, Effect.uninterruptible); + return { prepare, record }; +}; diff --git a/apps/server/src/process/externalLauncher.test.ts b/apps/server/src/process/externalLauncher.test.ts index 787a729f86b40..73ff1b067e875 100644 --- a/apps/server/src/process/externalLauncher.test.ts +++ b/apps/server/src/process/externalLauncher.test.ts @@ -340,7 +340,7 @@ for (const {} of [ platform: "darwin", installPath: "Applications/WebStorm.app/Contents/MacOS/webstorm", editor: "webstorm", - args: ["--line", "12", "--column", "4", "/workspace with spaces/file.ts"], + args: ["--line", "12", "--column", "3", "/workspace with spaces/file.ts"], }, { platform: "darwin", @@ -364,13 +364,13 @@ for (const {} of [ platform: "win32", installPath: "Programs/JetBrains/WebStorm 2026.2/bin/webstorm64.exe", editor: "webstorm", - args: ["--line", "12", "--column", "4", "/workspace with spaces/file.ts"], + args: ["--line", "12", "--column", "3", "/workspace with spaces/file.ts"], }, { platform: "win32", installPath: "Programs/WebStorm/bin/webstorm64.exe", editor: "webstorm", - args: ["--line", "12", "--column", "4", "/workspace with spaces/file.ts"], + args: ["--line", "12", "--column", "3", "/workspace with spaces/file.ts"], }, { platform: "win32", @@ -382,7 +382,7 @@ for (const {} of [ platform: "linux", installPath: ".local/share/JetBrains/Toolbox/scripts/idea", editor: "idea", - args: ["--line", "12", "--column", "4", "/workspace with spaces/file.ts"], + args: ["--line", "12", "--column", "3", "/workspace with spaces/file.ts"], }, { platform: "linux", @@ -472,7 +472,7 @@ it.effect.each([ "--line", "12", "--column", - "4", + "3", "/workspace with spaces/file.ts", ]); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), diff --git a/apps/server/src/process/externalLauncher.ts b/apps/server/src/process/externalLauncher.ts index 2c24857555bb6..1260f2e3fda80 100644 --- a/apps/server/src/process/externalLauncher.ts +++ b/apps/server/src/process/externalLauncher.ts @@ -163,9 +163,10 @@ function resolveCommandEditorArgs( onSome: ({ path, line, column }) => [ "--line", line, + // JetBrains IDEs count `--column` from 0; targets count columns from 1. ...Option.match(column, { onNone: () => [], - onSome: (value) => ["--column", value], + onSome: (value) => ["--column", String(Math.max(0, Number(value) - 1))], }), path, ], diff --git a/apps/server/src/project/RepositoryIdentityResolver.test.ts b/apps/server/src/project/RepositoryIdentityResolver.test.ts index 2fce68ed27b9f..6fc57297a40e0 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.test.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.test.ts @@ -261,6 +261,7 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { expect(identity?.displayName).toBe("T3Tools/t3code"); expect(identity?.origin).toEqual({ canonicalKey: "github.com/julius/t3code-fork", + remoteUrl: "git@github.com:julius/t3code-fork.git", displayName: "julius/t3code-fork", }); }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), diff --git a/apps/server/src/project/RepositoryIdentityResolver.ts b/apps/server/src/project/RepositoryIdentityResolver.ts index e3f3674c11e64..0ec948b485fc0 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.ts @@ -105,7 +105,7 @@ function buildRepositoryOrigin( const originKey = normalizeGitRemoteUrl(originUrl); if (originKey === canonicalKey) return undefined; const displayName = repositoryPathOf(originKey, originUrl); - return { canonicalKey: originKey, ...(displayName ? { displayName } : {}) }; + return { canonicalKey: originKey, remoteUrl: originUrl, ...(displayName ? { displayName } : {}) }; } function buildRepositoryIdentity(input: { diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts index b6682d974b7e6..5452560d28917 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.ts @@ -76,6 +76,7 @@ function makeCodexMaintenanceResolver(sharedHomePath: string) { nativeUpdate: { args: ["update"], isCommandPath: isCodexStandaloneCommandPath, + requiresCommandPath: true, env: { CODEX_HOME: sharedHomePath }, }, }); diff --git a/apps/server/src/provider/providerMaintenanceRunner.test.ts b/apps/server/src/provider/providerMaintenanceRunner.test.ts index de373771345bc..43808ff37df87 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.test.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.test.ts @@ -454,14 +454,43 @@ describe("providerMaintenanceRunner", () => { const updateState = result.providers[0]?.updateState; assert.strictEqual(updateState?.status, "failed"); - assert.strictEqual(updateState?.message, "Update command exited with code 1."); - assert.include(updateState?.output ?? "", "permission denied"); + assert.strictEqual( + updateState?.message, + "Update command exited with code 1: Error: Could not detect the Codex installation method.", + ); + assert.include(updateState?.output ?? "", "checking install"); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + layerLatestVersionHttpClient("0.0.0"), + layerMockSpawner(() => ({ + stdout: "checking install\n", + stderr: "Error: Could not detect the Codex installation method.\n\n", + code: 1, + })), + ), + ), + ), + ); + + it.effect("keeps the exit code message when a failed command prints nothing", () => + Effect.gen(function* () { + const { registry } = yield* makeRegistry(); + const updater = yield* makeTestRunner(registry); + + const result = yield* updater.updateProvider(CODEX_DRIVER); + + assert.strictEqual( + result.providers[0]?.updateState?.message, + "Update command exited with code 1.", + ); }).pipe( Effect.provide( Layer.mergeAll( layerNonWindowsPlatform, layerLatestVersionHttpClient("0.0.0"), - layerMockSpawner(() => ({ stderr: "permission denied", code: 1 })), + layerMockSpawner(() => ({ code: 1 })), ), ), ), diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.ts index 7b59e1dea946f..43d8b1e3916ad 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.ts @@ -242,14 +242,30 @@ function commandOutput(result: ProviderMaintenanceCommandResult): string | null return truncateText(output, UPDATE_OUTPUT_MAX_BYTES); } +// Updaters print their reason last, usually on stderr. +function lastOutputLine(result: ProviderMaintenanceCommandResult): string | null { + for (const output of [result.stderr, result.stdout]) { + const line = output + .split(/\r\n|\r|\n/) + .map(toProgressLine) + .findLast(Boolean); + if (line) { + return line; + } + } + return null; +} + function failureMessage(result: ProviderMaintenanceCommandResult): string { if (result.timedOut) { return "Update timed out."; } - if (result.exitCode !== null && result.exitCode !== 0) { - return `Update command exited with code ${result.exitCode}.`; - } - return "Update command failed."; + const summary = + result.exitCode !== null && result.exitCode !== 0 + ? `Update command exited with code ${result.exitCode}` + : "Update command failed"; + const reason = lastOutputLine(result); + return reason ? `${summary}: ${reason}` : `${summary}.`; } function isOutdatedProvider(provider: ServerProvider | undefined): boolean { @@ -474,6 +490,13 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { const result = yield* runMaintenanceCommand(command, setRunningMessage); const finishedAt = yield* nowIso; if (result.timedOut || result.exitCode !== 0) { + yield* Effect.logWarning("Provider update command failed", { + provider, + command: describeCommand(command), + exitCode: result.exitCode, + timedOut: result.timedOut, + output: commandOutput(result), + }); return yield* finish( makeUpdateState({ status: "failed", diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index d270636c40148..a438ac780f43f 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -2680,6 +2680,74 @@ it.effect( }), ); +it.effect("notifies linked threads when detail changes draft status in either direction", () => + Effect.gen(function* () { + let isDraft = true; + let updatedAt = "2026-07-02T00:00:00Z"; + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakeProvider(SourceControlProviderKind.make("github"), { + getChangeRequest: () => + Effect.sync(() => ({ ...hostedChangeRequest("body"), isDraft, updatedAt })), + }), + ], + }); + const changes = yield* service.subscribeStateChanges; + const read = () => service.detail({ ...reference, allowStale: false }); + yield* read(); + yield* read(); + isDraft = false; + yield* service.invalidate({ reference }); + yield* read(); + yield* read(); + isDraft = true; + yield* service.invalidate({ reference }); + yield* read(); + + isDraft = false; + updatedAt = "2026-07-01T00:00:00Z"; + yield* service.invalidate({ reference }); + yield* read(); + + // A different PR ends collection after all the synchronous notifications above. + yield* service.reportState({ reference: { ...reference, number: 2 }, state: "open" }); + const events = yield* Stream.runCollect( + changes.pipe(Stream.takeUntil((event) => event.number === 2, { excludeLast: true })), + ); + assert.deepStrictEqual(events, [ + { host: "github.com", repository: "acme/web", number: 1 }, + { host: "github.com", repository: "acme/web", number: 1 }, + { host: "github.com", repository: "acme/web", number: 1 }, + ]); + }), +); + +it.effect("deduplicates routed PR reports without dropping draft changes", () => + Effect.gen(function* () { + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [fakeProvider(SourceControlProviderKind.make("github"))], + }); + const changes = yield* service.subscribeStateChanges; + for (const isDraft of [true, true, false, false, true]) { + yield* service.reportState({ reference, state: "open", isDraft }); + } + yield* service.reportState({ reference, state: "open" }); + yield* service.reportState({ reference, state: "open" }); + yield* service.reportState({ reference: { ...reference, number: 2 }, state: "open" }); + const events = yield* Stream.runCollect( + changes.pipe(Stream.takeUntil((event) => event.number === 2, { excludeLast: true })), + ); + assert.deepStrictEqual( + events.map((event) => event.number), + [1, 1, 1, 1], + ); + }), +); + it.effect("reuses an observed merged state for strict settlement reads", () => Effect.gen(function* () { const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index f0c2b580064ad..3c6c9b333fbfe 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -102,7 +102,10 @@ export interface PullRequestMergeEvent extends PullRequestRef { readonly mergedAt: string; } -type PullRequestReading = Pick; +type PullRequestReading = Pick< + PullRequestSummary, + "state" | "isDraft" | "updatedAt" | "observedAt" +>; function supersedesReading(current: PullRequestReading | undefined, next: PullRequestReading) { if (current === undefined) return true; @@ -2891,10 +2894,12 @@ export const make = Effect.gen(function* () { } detailStates.set(scope, { state: next.state, + isDraft: next.isDraft, updatedAt: next.updatedAt, observedAt: next.observedAt, }); - return current?.state !== next.state && ref.host !== undefined + return (current?.state !== next.state || current?.isDraft !== next.isDraft) && + ref.host !== undefined ? PubSub.publish(stateChanges, { host: ref.host, repository: ref.repository, @@ -2906,22 +2911,34 @@ export const make = Effect.gen(function* () { // must never outrank a reading this environment made itself. const reportedStates = new Map< string, - { readonly state: PullRequestState; readonly atMs: number } + { + readonly state: PullRequestState; + readonly isDraft: boolean | undefined; + readonly atMs: number; + } >(); - const reportState: PullRequestService["Service"]["reportState"] = ({ reference, state }) => + const reportState: PullRequestService["Service"]["reportState"] = ({ + reference, + state, + isDraft, + }) => Effect.all([canonicalRef(reference), Clock.currentTimeMillis]).pipe( Effect.flatMap(([ref, nowMs]) => Effect.suspend(() => { const scope = refScope(ref); const reported = reportedStates.get(scope); - if (reported?.state === state && nowMs - reported.atMs < REPORTED_STATE_DEDUPE_MS) + if ( + reported?.state === state && + reported.isDraft === isDraft && + nowMs - reported.atMs < REPORTED_STATE_DEDUPE_MS + ) return Effect.void; reportedStates.delete(scope); if (reportedStates.size >= REF_EPOCH_CAPACITY) { const oldest = reportedStates.keys().next().value; if (oldest !== undefined) reportedStates.delete(oldest); } - reportedStates.set(scope, { state, atMs: nowMs }); + reportedStates.set(scope, { state, isDraft, atMs: nowMs }); return ref.host === undefined ? Effect.void : PubSub.publish(stateChanges, { diff --git a/apps/server/src/resourceTelemetry/ResourceTelemetry.test.ts b/apps/server/src/resourceTelemetry/ResourceTelemetry.test.ts index 51ed62d08982f..c12e2e44ed7eb 100644 --- a/apps/server/src/resourceTelemetry/ResourceTelemetry.test.ts +++ b/apps/server/src/resourceTelemetry/ResourceTelemetry.test.ts @@ -19,6 +19,14 @@ import * as NativeTelemetryClient from "./NativeTelemetryClient.ts"; import * as ResourceAttribution from "./ResourceAttribution.ts"; import * as ResourceTelemetry from "./ResourceTelemetry.ts"; +// ResourceTelemetry classifies process.pid as the server, so fixture PIDs are +// offsets from it. Fixed PIDs collide whenever the test worker is assigned one. +const SERVER_PID = process.pid; +const CODEX_PID = SERVER_PID + 1; +const SHORT_LIVED_CHILD_PID = SERVER_PID + 2; +const ELECTRON_PID = SERVER_PID + 3; +const MONITOR_PID = SERVER_PID + 4; + function processSample( input: Partial & Pick, @@ -48,14 +56,14 @@ function nativeSnapshot(input: { }): ResourceMonitorSnapshotEvent { const processes = [ processSample({ - pid: process.pid, + pid: SERVER_PID, ppid: 1, startTimeMs: 100, cpuTimeMs: input.sequence * 10, }), processSample({ - pid: 4_242, - ppid: process.pid, + pid: CODEX_PID, + ppid: SERVER_PID, startTimeMs: 200, name: "codex", command: "codex app-server", @@ -63,7 +71,7 @@ function nativeSnapshot(input: { ioWriteBytes: input.childWriteBytes, }), processSample({ - pid: 5_000, + pid: ELECTRON_PID, ppid: 1, startTimeMs: 300, name: "electron", @@ -71,8 +79,8 @@ function nativeSnapshot(input: { cpuTimeMs: input.sequence * 20, }), processSample({ - pid: 9_000, - ppid: process.pid, + pid: MONITOR_PID, + ppid: SERVER_PID, startTimeMs: 400, name: "t3-resource-monitor", command: "t3-resource-monitor", @@ -109,7 +117,7 @@ function desktopSnapshot(sampledAtUnixMs: number): DesktopHostTelemetrySnapshot type: "desktopTelemetry", sequence: 1, sampledAtUnixMs, - electronPid: 5_000, + electronPid: ELECTRON_PID, power: { source: "electron-main", idle: "false", @@ -125,7 +133,7 @@ function desktopSnapshot(sampledAtUnixMs: number): DesktopHostTelemetrySnapshot speedLimitPercent: Option.some(90), electronProcesses: [ { - pid: 5_000, + pid: ELECTRON_PID, creationTimeMs: 300, type: "Browser", name: "electron", @@ -152,17 +160,17 @@ describe("ResourceTelemetry", () => { childWriteBytes: index * 100, }); const processes = sample.processes - .filter((entry) => entry.pid === process.pid || entry.pid === 4_242) + .filter((entry) => entry.pid === SERVER_PID || entry.pid === CODEX_PID) .map((entry) => - entry.pid === 4_242 + entry.pid === CODEX_PID ? { ...entry, startTimeMs: index } : { ...entry, ioWriteBytes: index * 100 }, ); if (index === 0 || index === 2) { processes.push( processSample({ - pid: 4_243, - ppid: process.pid, + pid: SHORT_LIVED_CHILD_PID, + ppid: SERVER_PID, startTimeMs: 500, cpuTimeMs: index === 0 ? 100 : 350, ioWriteBytes: index === 0 ? 1_000 : 5_000, @@ -190,18 +198,20 @@ describe("ResourceTelemetry", () => { expect(history.topProcesses).toHaveLength(sampleCount + 2); expect( - history.topProcesses.find((entry) => entry.identity.pid === process.pid), + history.topProcesses.find((entry) => entry.identity.pid === SERVER_PID), ).toMatchObject({ sampleCount, cpuTimeMs: (sampleCount - 1) * 10, ioWriteBytes: (sampleCount - 1) * 100, }); - const children = history.topProcesses.filter((entry) => entry.identity.pid === 4_242); + const children = history.topProcesses.filter((entry) => entry.identity.pid === CODEX_PID); expect(children).toHaveLength(sampleCount); for (const child of children) { expect(child).toMatchObject({ sampleCount: 1, cpuTimeMs: 0, ioWriteBytes: 0 }); } - expect(history.topProcesses.find((entry) => entry.identity.pid === 4_243)).toMatchObject({ + expect( + history.topProcesses.find((entry) => entry.identity.pid === SHORT_LIVED_CHILD_PID), + ).toMatchObject({ sampleCount: 2, cpuTimeMs: 250, ioWriteBytes: 4_000, @@ -224,7 +234,7 @@ describe("ResourceTelemetry", () => { sampledAtUnixMs, childCpuTimeMs: 100, childWriteBytes: 1_000, - externalProcesses: [{ pid: 5_000, startTimeMs: 300 }], + externalProcesses: [{ pid: ELECTRON_PID, startTimeMs: 300 }], }); const desktop = { ...desktopSnapshot(sampledAtUnixMs), @@ -253,9 +263,9 @@ describe("ResourceTelemetry", () => { return yield* telemetry.refresh; }).pipe(Effect.provide(layerTelemetry)); - expect(snapshot.processes.find((entry) => entry.identity.pid === 5_000)?.category).toBe( - "electron-main", - ); + expect( + snapshot.processes.find((entry) => entry.identity.pid === ELECTRON_PID)?.category, + ).toBe("electron-main"); expect(snapshot.groups.electron.processStarts).toBe(1); expect(snapshot.groups.backend.processStarts).toBe(3); }), diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts index bcb110a5da71b..09e1d7674044f 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts @@ -116,3 +116,54 @@ it.effect("preserves a due run when a save only pads the scheduled hour", () => }).pipe(Effect.provide(ScheduledTaskService.layer.pipe(Layer.provide(layerDependencies)))); }).pipe(Effect.provide(SqlitePersistence.layerMemory)), ); + +it.effect("keeps the task list order when a toggle or edit rewrites updated_at", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-07-01T09:00:00.000Z")); + const layerDependencies = Layer.mergeAll( + NodeCrypto.layer, + Scheduler.layer, + Layer.mock(ThreadLaunchService.ThreadLaunchService)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), + Layer.mock(ThreadManagementService.ThreadManagementService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + ); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const input = (id: string) => ({ + id, + title: id, + prompt: "Review the open pull requests.", + enabled: true, + schedule: { type: "interval", everyMs: 60_000 }, + projectId: "project-stable-order", + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + }); + const listedIds = service + .list() + .pipe(Effect.map(({ tasks }) => tasks.map((task) => String(task.id)))); + + const older = yield* service.upsert(yield* decodeUpsertInput(input("scheduled-task:older"))); + yield* TestClock.adjust("1 second"); + yield* service.upsert(yield* decodeUpsertInput(input("scheduled-task:newer"))); + const order = ["scheduled-task:newer", "scheduled-task:older"]; + expect(yield* listedIds).toEqual(order); + + yield* TestClock.adjust("1 second"); + const toggled = yield* service.setEnabled({ id: older.task.id, enabled: false }); + expect(toggled.task.updatedAt > older.task.updatedAt).toBe(true); + expect(yield* listedIds).toEqual(order); + + yield* TestClock.adjust("1 second"); + const edit = { ...input(older.task.id), requireExisting: true, title: "Edited" }; + yield* service.upsert(yield* decodeUpsertInput({ ...edit, enabled: false })); + expect(yield* listedIds).toEqual(order); + }).pipe(Effect.provide(ScheduledTaskService.layer.pipe(Layer.provide(layerDependencies)))); + }).pipe(Effect.provide(SqlitePersistence.layerMemory)), +); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index ea681a30afe03..374d6b38027b8 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -456,7 +456,9 @@ export const layer = Layer.effect( webhook_token, webhook_secret FROM scheduled_tasks - ORDER BY updated_at DESC, task_id ASC + -- Not updated_at: toggles, runs and edits rewrite it, and clients render + -- this order as-is, so rows would move under the pointer. + ORDER BY created_at DESC, task_id ASC `; const listRows = Effect.fn("ScheduledTaskService.listRows")(function* () { diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index 33cc1874281c6..992e219db9122 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -244,7 +244,7 @@ const cleanupFixture = ( const fs = yield* FileSystem.FileSystem; const config = yield* ServerConfig.ServerConfig; const git = yield* GitVcsDriver.GitVcsDriver; - const repo = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-repo-" }); + const repo = yield* fs.realPath(yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-repo-" })); const command = (cwd: string, args: string[]) => git.execute({ operation: "cleanup-test", cwd, args }); yield* command(repo, ["init", "-b", "main"]); @@ -1299,6 +1299,36 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + // An agent can write this manifest. Statting its store sent the Windows + // user's NTLM credentials to attacker.test during a background sweep. + it.live.each([ + { storeDir: "\\\\attacker.test\\s" }, + { storeDir: "/local/store", virtualStoreDir: "//attacker.test/s" }, + ])("never stats a network pnpm store %o", (manifest) => + runCleanupTest( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const statted: Array = []; + const { service, worktree, setPolicy } = yield* cleanupFixture().pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + stat: (target) => { + statted.push(target); + return fs.stat(target); + }, + }), + ); + setPolicy("tracked-changes"); + yield* fs.makeDirectory(`${worktree}/node_modules`); + yield* fs.writeFileString( + `${worktree}/node_modules/.modules.yaml`, + JSON.stringify(manifest), + ); + expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); + expect(statted.filter((target) => target.includes("attacker.test"))).toEqual([]); + }), + ), + ); it.live("still removes a worktree when measuring its size fails", () => runCleanupTest( Effect.gen(function* () { diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index 1c4eb714facd2..a196321e38098 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -50,6 +50,7 @@ import { removeLinkedWorktree } from "./vcs/worktreeRemoval.ts"; import { withWorkspaceLease } from "./workspace/workspaceLease.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import { isNetworkPath } from "@t3tools/shared/path"; const decodeCleanupThread = Schema.decodeUnknownEffect( Schema.fromJsonString(OrchestrationV2AppThreadJson), @@ -265,6 +266,11 @@ const make = Effect.gen(function* () { const nodeModules = path.join(root, "node_modules"); const text = yield* fs.readFileString(path.join(nodeModules, ".modules.yaml")); const manifest = yield* decodePnpmModulesManifest(yield* Effect.try(() => parseYaml(text))); + // An agent can write this manifest, and statting a network path makes + // Windows sign in to its host with the user's NTLM credentials. + if (isNetworkPath(manifest.storeDir) || isNetworkPath(manifest.virtualStoreDir ?? "")) { + return null; + } const virtualStore = path.resolve(nodeModules, manifest.virtualStoreDir ?? ".pnpm"); const [store, virtual] = yield* Effect.all([ fs.stat(manifest.storeDir), diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index c0c5f261563bd..84861d6dd4ae0 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -80,6 +80,13 @@ const makeSuccessfulHandle = (stdout: string) => getOutputFd: () => Stream.empty, }); +const makeFailedHandle = (stderr: string) => + ChildProcessSpawner.makeHandle({ + ...makeNonRepositoryHandle(), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)), + stderr: Stream.encodeText(Stream.make(stderr)), + }); + const makeTmpDir = ( prefix = "git-vcs-driver-test-", ): Effect.Effect => @@ -803,6 +810,88 @@ it.effect("retries a fetch that lost a ref update to another Git process", () => }).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))), ); +describe("rejected git refs", () => { + const remoteUrl = "https://user:token-123@git.example.invalid/org/secret-repo.git"; + const failedPush = `error: failed to push some refs to '${remoteUrl}'`; + const leakedText = [ + "token-123", + "secret-repo", + "git.example.invalid", + "private-branch", + "workflow scope", + ]; + + const failWith = (stderr: string) => { + const spawner = ChildProcessSpawner.make(() => Effect.succeed(makeFailedHandle(stderr))); + const layer = GitVcsDriver.layer.pipe( + Layer.provide(layerServerConfig), + Layer.provideMerge( + Layer.merge( + NodeServices.layer, + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), + ), + ), + ); + return Effect.gen(function* () { + const driver = yield* GitVcsDriver.GitVcsDriver; + return yield* driver + .execute({ + operation: "GitVcsDriver.test.rejectedRef", + cwd: "/repo", + args: ["push", "origin", "HEAD"], + }) + .pipe(Effect.flip); + }).pipe(Effect.provide(layer)); + }; + + it.effect.each([ + { + label: "a ref the remote refused", + stderr: [ + "remote: Unable to determine if workflow can be created; workflow scope may be required.", + `To ${remoteUrl}`, + " ! [remote rejected] private-branch -> private-branch (workflow scope may be required.)", + failedPush, + ], + reason: "push_rejected_by_remote" as const, + detail: "The remote rejected the push.", + }, + { + label: "a non-fast-forward push", + stderr: [ + `To ${remoteUrl}`, + " ! [rejected] private-branch -> private-branch (non-fast-forward)", + failedPush, + ], + reason: "push_rejected_non_fast_forward" as const, + detail: "Pull or rebase", + }, + ])("names $label without quoting stderr", ({ stderr, reason, detail }) => + Effect.gen(function* () { + const error = yield* failWith(stderr.join("\n")); + + assert.deepInclude(error, { reason }); + assert.include(error.detail, detail); + for (const text of leakedText) assert.notInclude(error.message, text); + }), + ); + + // A fetch into a diverged local branch prints the same rejected line, but + // never "failed to push some refs". + it.effect("leaves a rejected fetch unclassified", () => + Effect.gen(function* () { + const error = yield* failWith( + [`From ${remoteUrl}`, " ! [rejected] main -> side (non-fast-forward)"].join( + "\n", + ), + ); + + assert.equal(error.reason, undefined); + assert.equal(error.detail, "Git command exited with a non-zero status."); + }), + ); +}); + it.layer(layerTest)("GitVcsDriver core integration", (it) => { describe("structured errors", () => { it.effect("does not retain git arguments or stderr in command failures", () => @@ -1071,7 +1160,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("does not read remote hook output as a git failure reason", () => + it.effect("reads a hook-declined push from git's rejection line, not the hook's output", () => Effect.gen(function* () { const parent = yield* makeTmpDir(); const pathService = yield* Path.Path; @@ -1100,7 +1189,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }) .pipe(Effect.flip); - assert.notProperty(error, "reason"); + assert.deepInclude(error, { reason: "push_rejected_by_remote" }); assert.notInclude(error.message, "(authentication_failed)"); }), ); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 0f3fe9a1e6b29..62798374d2aa5 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -456,8 +456,32 @@ const GIT_FAILURE_REASON_PATTERNS: ReadonlyArray> = { + push_rejected_by_remote: + "The remote rejected the push. Push this branch from a terminal to see the server's message.", + push_rejected_non_fast_forward: + "The remote has commits this branch doesn't have. Pull or rebase, then push again.", +}; + +function gitFailureDetail(reason: GitCommandFailureReason | null): string { + return ( + (reason === null ? undefined : GIT_FAILURE_REASON_DETAILS[reason]) ?? + "Git command exited with a non-zero status." + ); +} + // Existing non-commit objects share the missing-ref fatal diagnostic; Git // distinguishes them with a separate error line. const GIT_NOT_A_COMMIT_PATTERN = /^error: .+(?:, not a commit|expected commit type)/im; @@ -1031,7 +1055,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return yield* new GitCommandError({ ...gitCommandContext(commandInput), ...(reason === null ? {} : { reason }), - detail: "Git command exited with a non-zero status.", + detail: gitFailureDetail(reason), exitCode, stdoutLength: stdout.text.length, stderrLength: stderr.text.length, @@ -1123,7 +1147,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* new GitCommandError({ ...gitCommandContext({ operation, cwd, args }), ...(reason === null ? {} : { reason }), - detail: options.fallbackErrorDetail ?? "Git command exited with a non-zero status.", + detail: options.fallbackErrorDetail ?? gitFailureDetail(reason), ...(result.exitCode === null ? {} : { exitCode: result.exitCode }), stdoutLength: result.stdout.length, stderrLength: result.stderr.length, diff --git a/apps/server/src/workspace/WorkspaceFileSystem.test.ts b/apps/server/src/workspace/WorkspaceFileSystem.test.ts index 6dc5d4c085754..9eb2ba7580490 100644 --- a/apps/server/src/workspace/WorkspaceFileSystem.test.ts +++ b/apps/server/src/workspace/WorkspaceFileSystem.test.ts @@ -1,6 +1,8 @@ -// @effect-diagnostics nodeBuiltinImport:off - FileSystem cannot create a FIFO. +// @effect-diagnostics nodeBuiltinImport:off - FileSystem cannot create a FIFO, and reads spy on native realpath. import * as NodeChildProcess from "node:child_process"; +import * as NodeFSP from "node:fs/promises"; +import * as NodePath from "@effect/platform-node/NodePath"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { it, describe, expect } from "@effect/vitest"; import * as Effect from "effect/Effect"; @@ -17,6 +19,12 @@ import * as WorkspaceFileSystem from "./WorkspaceFileSystem.ts"; import * as WorkspacePaths from "./WorkspacePaths.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; +import { vi } from "vite-plus/test"; + +vi.mock("node:fs/promises", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, realpath: vi.fn(actual.realpath) }; +}); // Temp folders count as known workspaces unless named as unknown. const UNKNOWN_WORKSPACE_PREFIX = "t3code-unknown-workspace-"; @@ -123,6 +131,35 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i ]); }), ); + + // A file chip for `file://attacker.test/s/a.ts` in an agent's message sent + // the Windows user's NTLM credentials to attacker.test as it rendered. + it.effect("never stats a network path", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const statted: Array = []; + const service = yield* WorkspaceFileSystem.make.pipe( + Effect.provideService( + FileSystem.FileSystem, + FileSystem.FileSystem.of({ + ...fs, + stat: (requestedPath) => { + statted.push(requestedPath); + return fs.stat(requestedPath); + }, + }), + ), + Effect.provide(layerKnownWorkspacesTest), + ); + const paths = [ + "\\\\attacker.test\\s\\a.ts", + "//attacker.test/s/a.ts", + "/\\attacker.test\\s", + ]; + expect((yield* service.getMetadata({ paths })).entries).toEqual([null, null, null]); + expect(statted).toEqual([]); + }), + ); }); describe("readFile", () => { @@ -199,6 +236,68 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i }), ); + it.effect("refuses a network path outside the workspace", () => + Effect.gen(function* () { + const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; + + const error = yield* workspaceFileSystem + .readFile({ cwd: "//nas.test/share/project", relativePath: "//attacker.test/s/a.md" }) + .pipe(Effect.flip); + + expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError); + }), + ); + + // This resolves inside the project, but Windows reads `\\?\` paths as + // written, so realpath on the raw string signed in to attacker.test. + it.effect("reads the network path it checked", () => + Effect.gen(function* () { + const workspaceFileSystem = yield* WorkspaceFileSystem.make.pipe( + Effect.provide(Layer.merge(layerKnownWorkspacesTest, NodePath.layerWin32)), + ); + // Rejects without touching the filesystem, so a Windows runner never looks the share up. + const realpath = vi + .mocked(NodeFSP.realpath) + .mockClear() + .mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" })); + + yield* workspaceFileSystem + .readFile({ + cwd: "\\\\?\\UNC\\nas.test\\share\\project", + relativePath: "\\\\?\\UNC\\attacker.test\\s\\..\\..\\nas.test\\share\\project\\a.md", + }) + .pipe(Effect.exit); + + expect(realpath.mock.calls.map(([target]) => target)).toEqual([ + "\\\\?\\UNC\\nas.test\\share\\project\\a.md", + ]); + }), + ); + + // Resolving `..` before realpath would read beside the link instead of its target. + // Windows collapses `..` before the filesystem sees a path, so it has no such reads. + it.effect.skipIf(!symlinksSupported || HostProcess.Platform.defaultValue() === "win32")( + "reads `..` after a link from the link's target", + () => + Effect.gen(function* () { + const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* makeTempDir; + yield* writeTextFile(root, "target/parent.md", "beside the target\n"); + yield* writeTextFile(root, "parent.md", "beside the link\n"); + yield* fs.makeDirectory(path.join(root, "target", "child")); + yield* fs.symlink(path.join(root, "target", "child"), path.join(root, "link")); + + const result = yield* workspaceFileSystem.readFile({ + cwd: root, + relativePath: `${root}/link/../parent.md`, + }); + + expect(result.contents).toBe("beside the target\n"); + }), + ); + it.effect.skipIf(!symlinksSupported)( "rejects symlinks that resolve outside the workspace root", () => diff --git a/apps/server/src/workspace/WorkspaceFileSystem.ts b/apps/server/src/workspace/WorkspaceFileSystem.ts index ec18f675aae03..4e7c81404256b 100644 --- a/apps/server/src/workspace/WorkspaceFileSystem.ts +++ b/apps/server/src/workspace/WorkspaceFileSystem.ts @@ -13,6 +13,7 @@ import type { } from "@t3tools/contracts"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { isNetworkPath } from "@t3tools/shared/path"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -142,7 +143,9 @@ export const make = Effect.gen(function* () { const metadataForPath = Effect.fnUntraced(function* (requestedPath: string) { const expandedPath = expandHomePath(requestedPath, yield* HostProcess.HomeDirectory); - if (!path.isAbsolute(expandedPath)) return null; + // Chips ask as soon as an agent's message renders, and touching a network + // path makes Windows sign in to its host with the user's NTLM credentials. + if (!path.isAbsolute(expandedPath) || isNetworkPath(expandedPath)) return null; const stat = yield* fileSystem.stat(expandedPath).pipe(Effect.option); if (stat._tag === "None") return null; if (stat.value.type === "Directory") return { kind: "directory" } as const; @@ -222,7 +225,8 @@ export const make = Effect.gen(function* () { /** * Workspace-relative paths must stay inside the root, symlinks included. An * absolute or `~/` path reads a host file in place, such as a report an agent - * wrote to a temp directory; it gets no root check. + * wrote to a temp directory; it gets no root check. A network path does, since + * Windows signs in to its host with the user's NTLM credentials. */ const resolveReadTarget = Effect.fn("WorkspaceFileSystem.resolveReadTarget")(function* ( input: ProjectReadFileInput, @@ -231,15 +235,28 @@ export const make = Effect.gen(function* () { const hostPath = requestedPath.startsWith("~/") ? expandHomePath(requestedPath, yield* HostProcess.HomeDirectory) : requestedPath; + if ( + isNetworkPath(hostPath) && + !KnownWorkspaces.isWithinRoot(path, path.resolve(hostPath), path.resolve(input.cwd)) + ) { + return yield* new WorkspacePaths.WorkspacePathOutsideRootError({ + workspaceRoot: input.cwd, + relativePath: input.relativePath, + }); + } if (path.isAbsolute(hostPath)) { + // Native realpath hands Windows a `\\?\` path as written, `..` included, + // so a network path must be the resolved one the check above approved. + // Others keep POSIX `link/..` semantics, which resolving first would change. + const absolutePath = isNetworkPath(hostPath) ? path.resolve(hostPath) : hostPath; const realTargetPath = yield* Effect.tryPromise({ - try: () => NodeFSP.realpath(hostPath), + try: () => NodeFSP.realpath(absolutePath), catch: (cause) => new WorkspaceFileSystemOperationError({ workspaceRoot: input.cwd, relativePath: input.relativePath, - resolvedPath: hostPath, - operationPath: hostPath, + resolvedPath: absolutePath, + operationPath: absolutePath, operation: "realpath-target", cause, }), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 763365ceeddc1..1ba4ff99ff644 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -246,6 +246,7 @@ import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts"; import * as PairingGrantStore from "./auth/PairingGrantStore.ts"; import * as SessionStore from "./auth/SessionStore.ts"; import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts"; +import { isNetworkPath } from "@t3tools/shared/path"; import * as RelayClient from "@t3tools/shared/relayClient"; import { isTelemetryIdHash } from "@t3tools/shared/telemetryId"; import { @@ -2721,7 +2722,10 @@ export const layerWsRpc = ( input.resource._tag === "native-app-icon" || input.resource._tag === "tool-output-image" || input.resource._tag === "github-media" || - (input.resource._tag === "media-file" && path.isAbsolute(input.resource.path)) + // A network path is served only from the thread's project, looked up below. + (input.resource._tag === "media-file" && + path.isAbsolute(input.resource.path) && + !isNetworkPath(input.resource.path)) ) { return yield* issueAssetUrl({ resource: input.resource }); } diff --git a/apps/server/vite.config.ts b/apps/server/vite.config.ts index 57549bec067f2..92ad8e9083c3f 100644 --- a/apps/server/vite.config.ts +++ b/apps/server/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig, mergeConfig } from "vite-plus"; import baseConfig from "../../vite.config.ts"; import { loadRepoEnv } from "../../scripts/lib/public-config.ts"; +import rootPackageJson from "../../package.json" with { type: "json" }; import packageJson from "./package.json" with { type: "json" }; import { WeightedShardSequencer } from "./src/testUtils/weightedShardSequencer.ts"; @@ -34,7 +35,6 @@ if (!TELEMETRY_CHANNELS.includes(telemetryChannel)) { // executable needs a host Node that supports `--build-sea` (25.7+), so this is // a separate mode rather than a second entry in the default build. const packExecutable = process.env.T3CODE_PACK_EXE === "1"; -const SEA_NODE_VERSION = "26.8.2"; const SEA_TARGETS = { "darwin-arm64": { platform: "darwin", arch: "arm64" }, "darwin-x64": { platform: "darwin", arch: "x64" }, @@ -44,6 +44,12 @@ const SEA_TARGETS = { "win-x64": { platform: "win", arch: "x64" }, } as const; const packExecutableTarget = process.env.T3CODE_PACK_EXE_TARGET?.trim(); +const cliNodeVersion = rootPackageJson.engines.node; +if (packExecutable && !packExecutableTarget && process.versions.node !== cliNodeVersion) { + throw new Error( + `Native CLI executables must be built with Node ${cliNodeVersion}; running ${process.versions.node}.`, + ); +} if (packExecutableTarget && !Object.hasOwn(SEA_TARGETS, packExecutableTarget)) { throw new Error( `T3CODE_PACK_EXE_TARGET must be one of ${Object.keys(SEA_TARGETS).join(", ")}, got "${packExecutableTarget}".`, @@ -53,7 +59,7 @@ const packExecutableTargets = packExecutableTarget ? [ { ...SEA_TARGETS[packExecutableTarget as keyof typeof SEA_TARGETS], - nodeVersion: SEA_NODE_VERSION, + nodeVersion: cliNodeVersion, }, ] : undefined; diff --git a/apps/web/src/components/AddProjectToMachineDialog.tsx b/apps/web/src/components/AddProjectToMachineDialog.tsx index 7d1748f9d0c41..1d917de35104c 100644 --- a/apps/web/src/components/AddProjectToMachineDialog.tsx +++ b/apps/web/src/components/AddProjectToMachineDialog.tsx @@ -82,7 +82,10 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe const [targetId, setTargetId] = useState(request.targetEnvironmentId); const target = targets.find((t) => t.environmentId === targetId) ?? targets[0] ?? null; const source = environments.find((env) => env.environmentId === request.projectRef.environmentId); - const sourceUrl = project?.repositoryIdentity?.locator.remoteUrl ?? ""; + const sourceUrl = + project?.repositoryIdentity?.origin?.remoteUrl ?? + project?.repositoryIdentity?.locator.remoteUrl ?? + ""; const [protocol, setProtocol] = useState(() => cloneUrlProtocol(sourceUrl)); const sshUrl = cloneUrlForProtocol(sourceUrl, "ssh"); const httpsUrl = cloneUrlForProtocol(sourceUrl, "https"); diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index 311efa7e5f0c3..526ac86a6c9ad 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -219,7 +219,8 @@ function routePanelsOpen(routeThreadRef: ReturnType) { }; } -function NavigationHistoryShortcuts() { +export function NavigationHistoryShortcuts() { + const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" }); const keybindings = useAtomValue(primaryServerKeybindingsAtom); const routeThreadRef = useThreadRouteRef(); @@ -239,6 +240,7 @@ function NavigationHistoryShortcuts() { ...routePanelsOpen(routeThreadRef), editableFocus: isEditableFocused(event.target), modelPickerOpen: isModelPickerOpen(), + usagePageOpen, }, }); if (command !== "navigation.back" && command !== "navigation.forward") return; @@ -251,7 +253,7 @@ function NavigationHistoryShortcuts() { window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); - }, [keybindings, routeThreadRef]); + }, [keybindings, routeThreadRef, usagePageOpen]); return null; } diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index f0aa2ab8b6b16..a03a7929b0917 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -5,6 +5,8 @@ import { planComposerTurn, snapshotComposerSend, withMessageContext, + deriveAvailableRevertTurnCounts, + deriveWorkspaceMutationId, } from "./ChatView.logic"; import { recallCheckoutIsRepo, rememberCheckoutIsRepo } from "./ChatView.logic"; import { ProviderDriverKind, type ServerProvider } from "@t3tools/contracts"; @@ -1158,3 +1160,82 @@ describe("boundAttachmentIds", () => { ).toEqual(["upload-1", "local-2"]); }); }); + +describe("deriveAvailableRevertTurnCounts", () => { + const providerThreadId = ProviderThreadId.make("provider-thread"); + const otherProviderThreadId = ProviderThreadId.make("other-provider-thread"); + + function projection(input: { readonly providerSessionId: ProviderSessionId | null }) { + const base = makeThreadProjectionFixture(); + const run = (ordinal: number) => ({ + id: RunId.make(`run-${ordinal}`), + ordinal, + activeAttemptId: `attempt-${ordinal}`, + }); + const turn = (ordinal: number, attempt: number, threadId: ProviderThreadId) => ({ + id: `turn-${attempt}-${ordinal}`, + runAttemptId: `attempt-${attempt}`, + ordinal, + providerThreadId: threadId, + }); + return { + ...base, + thread: { ...base.thread, activeProviderThreadId: providerThreadId }, + providerThreads: [ + { + id: providerThreadId, + providerInstanceId: base.thread.modelSelection.instanceId, + providerSessionId: input.providerSessionId, + }, + ], + runs: [run(1), run(2), run(3)], + attempts: [1, 2, 3].map((ordinal) => ({ id: `attempt-${ordinal}`, providerTurnId: null })), + // Run 2's latest turn moved to another provider thread, so its checkpoint cannot restore + // this conversation. + providerTurns: [ + turn(1, 1, providerThreadId), + turn(1, 2, providerThreadId), + turn(2, 2, otherProviderThreadId), + turn(1, 3, providerThreadId), + ], + } as unknown as ReturnType; + } + + it("offers the thread start and runs whose latest turn is on the active provider thread", () => { + const available = deriveAvailableRevertTurnCounts( + projection({ providerSessionId: ProviderSessionId.make("session") }), + ); + expect([...available].toSorted()).toEqual([0, 1, 3]); + }); + + it("offers nothing without a provider session to rewind", () => { + expect(deriveAvailableRevertTurnCounts(projection({ providerSessionId: null })).size).toBe(0); + expect(deriveAvailableRevertTurnCounts(null).size).toBe(0); + }); +}); + +describe("deriveWorkspaceMutationId", () => { + const item = (id: string, type: string, status: string) => + ({ + item: { id: TurnItemId.make(id), type, status }, + }) as unknown as OrchestrationV2ProjectedTurnItem; + + it("keys on the latest finished command or file change and the latest checkpoint", () => { + expect( + deriveWorkspaceMutationId( + [ + item("edit", "file_change", "completed"), + item("reply", "assistant_message", "completed"), + item("command", "command_execution", "running"), + ], + "2026-01-01T00:00:00.000Z", + ), + ).toBe(JSON.stringify(["edit", "2026-01-01T00:00:00.000Z"])); + }); + + it("is null before anything could have touched the workspace", () => { + expect(deriveWorkspaceMutationId([item("reply", "assistant_message", "completed")], null)).toBe( + null, + ); + }); +}); diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 64abb91c5c3df..1928cd21b12c1 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -1,9 +1,22 @@ +import { type OrchestrationV2ProviderTurn, type RunAttemptId } from "@t3tools/contracts"; +import { + deriveLatestThreadRun, + deriveThreadRuntime, +} from "@t3tools/client-runtime/state/thread-execution"; +import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; +import { + latestUnheldRun, + usageLimitRunPresentedAsLatest, +} from "@t3tools/shared/orchestrationV2ThreadError"; import * as Option from "effect/Option"; import type { SetStateAction } from "react"; import { applyClaudePromptEffortPrefix, resolvePromptInjectedEffort } from "@t3tools/shared/model"; import { getProviderModelCapabilities } from "../providerModels"; import { sanitizeThreadErrorMessage } from "~/rpc/transportError"; -import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import type { + EnvironmentThread, + EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/shell"; import { ANTIGRAVITY_DEFAULT_MODEL, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, @@ -92,6 +105,8 @@ import { type ProviderInstanceEntry, } from "../providerInstances"; +type ThreadProjection = EnvironmentThread["projection"]; + export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project"; export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10; @@ -1610,3 +1625,136 @@ export function sendTitleFallbackLabels(snapshot: ComposerSendSnapshot) { previewAnnotation ? previewAnnotationContextLabel(previewAnnotation) : undefined, ]; } + +/** A thread shell built from its loaded detail, for direct links that hydrate the detail first. */ +export function presentThreadShellFromProjection( + environmentId: EnvironmentId, + threadId: ThreadId, + projection: ThreadProjection, +) { + const latestRun = deriveLatestThreadRun(projection); + const runtime = deriveThreadRuntime(projection); + const pendingRuntimeRequest = + projection.runtimeRequests.findLast((request) => request.status === "pending") ?? null; + // Direct links can hydrate detail before the thread enters the shell index. + return { + ...presentThreadShell(environmentId, { + ...projection.thread, + latestRunId: latestRun?.runId ?? null, + activeRunId: runtime?.activeRunId ?? null, + status: runtime?.status ?? "idle", + pendingRuntimeRequest, + latestVisibleMessage: null, + latestUserMessageAt: + projection.messages.findLast((message) => message.role === "user")?.updatedAt ?? null, + hasActionableProposedPlan: projection.plans.some( + (plan) => plan.kind === "proposed_plan" && plan.status === "active", + ), + providerInstanceHistory: [ + ...new Set( + projection.providerThreads + .filter((thread) => thread.appThreadId === threadId && thread.ownerNodeId === null) + .map((thread) => thread.providerInstanceId), + ), + ], + goal: + projection.providerThreads.find( + (thread) => thread.id === projection.thread.activeProviderThreadId, + )?.goal ?? null, + itemCount: projection.turnItems.length, + visibleItemCount: projection.visibleTurnItems.length, + updatedAt: projection.updatedAt, + }), + latestRun, + runtime, + }; +} + +/** Background work the provider still runs after the latest run ended. */ +export function deriveThreadPendingBackgroundTasks(projection: ThreadProjection | null) { + if (projection === null) return []; + const sessionError = + projection.providerSessions.findLast( + (session) => session.providerInstanceId === projection.thread.providerInstanceId, + )?.lastError ?? null; + const latestRun = + usageLimitRunPresentedAsLatest(projection.runs, projection.turnItems, sessionError) ?? + latestUnheldRun(projection.runs); + return [ + ...derivePendingBackgroundWork({ + latestRun, + providerThreads: projection.providerThreads, + turnItems: projection.turnItems, + activeProviderThreadId: projection.thread.activeProviderThreadId, + runs: projection.runs, + pullRequests: projection.thread.pullRequests, + }), + ]; +} + +/** + * Run ordinals the conversation can be reverted to: those whose provider turn belongs to the + * active provider thread, plus 0 for the thread start. Empty without a live provider session + * on the thread's selected instance. + */ +export function deriveAvailableRevertTurnCounts(projection: ThreadProjection | null) { + const available = new Set(); + const providerThread = projection?.providerThreads.find( + (candidate) => candidate.id === projection.thread.activeProviderThreadId, + ); + if ( + !providerThread?.providerSessionId || + providerThread.providerInstanceId !== projection?.thread.modelSelection.instanceId + ) + return available; + available.add(0); + const attemptsById = new Map(projection.attempts.map((attempt) => [attempt.id, attempt])); + const providerTurnsById = new Map< + OrchestrationV2ProviderTurn["id"], + OrchestrationV2ProviderTurn + >(); + const latestTurnByAttempt = new Map(); + for (const turn of projection.providerTurns) { + providerTurnsById.set(turn.id, turn); + if (turn.runAttemptId === null) continue; + const latest = latestTurnByAttempt.get(turn.runAttemptId); + if (latest === undefined || turn.ordinal > latest.ordinal) { + latestTurnByAttempt.set(turn.runAttemptId, turn); + } + } + for (const run of projection.runs) { + if (run.activeAttemptId === null) continue; + const attempt = attemptsById.get(run.activeAttemptId); + const providerTurn = + latestTurnByAttempt.get(run.activeAttemptId) ?? + (attempt?.providerTurnId == null ? undefined : providerTurnsById.get(attempt.providerTurnId)); + // A ready file checkpoint alone cannot restore the provider conversation. + if (providerTurn?.providerThreadId === providerThread.id) available.add(run.ordinal); + } + return available; +} + +/** + * Changes when the agent may have changed the workspace, so file views refresh. File tools are + * explicit; completed commands are included because a shell command can mutate the workspace + * without reporting the paths it touched. + */ +export function deriveWorkspaceMutationId( + visibleTurnItems: ReadonlyArray, + latestCheckpointCompletedAt: string | null, +) { + let itemId: string | null = null; + for (let index = visibleTurnItems.length - 1; index >= 0; index -= 1) { + const item = visibleTurnItems[index]?.item; + if (!item) continue; + if (item.type !== "command_execution" && item.type !== "file_change") continue; + if (item.status === "pending" || item.status === "running" || item.status === "waiting") { + continue; + } + itemId = item.id; + break; + } + return itemId === null && latestCheckpointCompletedAt === null + ? null + : JSON.stringify([itemId, latestCheckpointCompletedAt]); +} diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index e794426afbe6b..d656929307216 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1,23 +1,32 @@ -import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions"; -import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; +import { ScrollToEndButton, WorkspaceFileDropOverlay } from "./chat/TimelineOverlays"; +import { usePasteToFocusComposer } from "./chat/usePasteToFocusComposer"; +import { + deriveAvailableRevertTurnCounts, + deriveThreadPendingBackgroundTasks, + deriveWorkspaceMutationId, + presentThreadShellFromProjection, +} from "./ChatView.logic"; +import { usePullRequestDraftThread } from "./chat/usePullRequestDraftThread"; +import { useComposerSelection } from "./chat/useComposerSelection"; +import { useProjectCloneBanner } from "./chat/useProjectCloneBanner"; +import { useAttachmentPreviewHandoff } from "./chat/useAttachmentPreviewHandoff"; +import { useTimelineRewind } from "./chat/useTimelineRewind"; +import { useThreadLifecycle } from "./chat/useThreadLifecycle"; +import { useRightPanelActions } from "./chat/useRightPanelActions"; +import { type TerminalLaunchContext, useChatTerminalActions } from "./chat/useChatTerminalActions"; +import { useComposerSend } from "./chat/useComposerSend"; +import { useComposerResume } from "./chat/useComposerResume"; +import { useImplementPlanInNewThread } from "./chat/useProposedPlanSend"; import { ThreadFind, ThreadFindCanvas, type ThreadFindControls } from "./chat/ThreadFindProvider"; import { THREAD_FIND_BAR_RESERVED_HEIGHT } from "./chat/ThreadFindBar"; import { usageLimitRecoveryBannerItem } from "./chat/UsageLimitRecoveryBanner"; -import { - isThreadWokeUnseen, - mergeDirectPreviewAnnotation, - resolveBackgroundDraftWorkspaceOptions, - resolveDraftHeroState, - shouldDockDraftHeroForSubmission, -} from "./ChatView.logic"; -import { restorePlanFollowUpComposer } from "./ChatView.logic"; +import { resolveDraftHeroState } from "./ChatView.logic"; import { useQueuedRunEdit } from "./chat/useQueuedRunEdit"; import { isPaintOnlyThreadTimeline, peekHeldThreadTimeline, peekRememberedThreadTimeline, rememberReadyThreadTimeline, - resolveExplicitDiffOpenOnActivate, resolveThreadSwitchTimeline, timelineHasEphemeralPreviewUrls, recallCheckoutIsRepo, @@ -27,7 +36,6 @@ import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnviron import { useStableCallback } from "../hooks/useStableCallback"; import { useProjectScriptEditing } from "./chat/useProjectScriptEditing"; import { RightPanelSurfaceContent } from "./chat/RightPanelSurfaceContent"; -import { useThreadTerminalActions } from "./terminal/useThreadTerminalActions"; import { usePendingThreadRequests } from "./chat/usePendingThreadRequests"; import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; @@ -36,51 +44,33 @@ import { latestRootProviderFailure, } from "@t3tools/shared/orchestrationV2ThreadError"; import type { UsageLimitSourceSnapshots } from "@t3tools/contracts"; -import { isUsageLimitsCommand } from "@t3tools/shared/usageLimits"; import { feedbackBannerItem } from "./chat/ComposerFeedback"; import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel"; import { useWorktreeSetup } from "./chat/useWorktreeSetup"; -import { useChatShortcuts, type ChatShortcutHandler } from "./chat/useChatShortcuts"; -import { - pasteTextToFocusComposer, - shouldRedirectInputToComposer, -} from "./chat/composerFocusRedirect"; -import { getTerminalLabel } from "@t3tools/shared/terminalLabels"; +import { useChatShortcuts } from "./chat/useChatShortcuts"; +import { ChatBannerLane } from "./chat/ChatBannerLane"; import * as Schema from "effect/Schema"; import { AuthOrchestrationOperateScope, AuthSourceControlWriteScope, AuthPreviewOperateScope, - AuthTerminalReadScope, AuthTerminalOperateScope, type AssistantCitation, type ChatFileAttachment, - DEFAULT_MODEL, isProviderNativeSubagentThread, type EnvironmentId, type MessageId, type ModelSelection, - type OrchestrationV2ProviderTurn, - type ProjectScript, type PreviewAnnotationPayload, ProviderInstanceId, type ServerProvider, type ScopedThreadRef, type ThreadId, type RunId, - type RunAttemptId, ProviderInteractionMode, resolveIdleCompaction, RuntimeMode, } from "@t3tools/contracts"; -import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations"; -import { wasBootstrapThreadDeleted } from "@t3tools/client-runtime/errors"; -import { readPastedComposerContext } from "./composerInlineTokenPaste"; -import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste"; -import { effectiveSnoozed, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled"; -import { declinePendingApprovals } from "@t3tools/client-runtime/state/thread-requests"; -import { presentThreadShell } from "@t3tools/client-runtime/state/shell"; -import { useAcknowledgeThreadWoke, useThreadActions } from "../hooks/useThreadActions"; import { deriveProviderSubagentStatus, deriveReportedModelSelection, @@ -99,67 +89,40 @@ import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff"; import { HandoffRow } from "./chat/V2LifecycleRow"; import { codexFeedbackMessage, - parseCodexFeedbackCommand, shouldShowLoadEarlierControl, - submitCodexFeedback, type CodexFeedbackSubmission, } from "@t3tools/client-runtime/state/threads"; -import { resolveThreadLastVisitedAt } from "./Sidebar.logic"; import { parseScopedThreadKey, scopedThreadKey, scopeProjectRef, scopeThreadRef, } from "@t3tools/client-runtime/environment"; -import { - createModelSelection, - formatModelSlugName, - resolveSelectableModel, -} from "@t3tools/shared/model"; -import { - projectScriptCwd, - projectScriptTerminalInput, - resolveProjectScripts, -} from "@t3tools/shared/projectScripts"; -import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; -import { - latestUnheldRun, - usageLimitRunPresentedAsLatest, -} from "@t3tools/shared/orchestrationV2ThreadError"; +import { formatModelSlugName, resolveSelectableModel } from "@t3tools/shared/model"; +import { projectScriptCwd, resolveProjectScripts } from "@t3tools/shared/projectScripts"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl"; -import { truncate } from "@t3tools/shared/String"; import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference"; import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels"; import { useAtomValue } from "@effect/atom-react"; import { type SetStateAction, useEffect, useLayoutEffect, useRef, useState } from "react"; -import { flushSync } from "react-dom"; -import { useLocation, useNavigate, useRouter } from "@tanstack/react-router"; +import { useLocation, useNavigate } from "@tanstack/react-router"; import { assistantCitationFromLocation } from "../lib/assistantCitationNavigation"; -import { isMacPlatform } from "../lib/utils"; import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection"; import { useShallow } from "zustand/react/shallow"; import { isAtomCommandInterrupted, mapAtomCommandResult, - settlePromise, squashAtomCommandFailure, type AtomCommandResult, } from "@t3tools/client-runtime/state/runtime"; import { AsyncResult } from "effect/reactivity"; import { isElectron } from "../env"; -import { readLocalApi } from "../localApi"; import { useDiffPanelStore } from "../diffPanelStore"; import { useActiveThreadRef } from "../hooks/useActiveThreadRef"; -import { - type ComposerSubmissionIntent, - collapseExpandedComposerCursor, - composerRequiresModifier, - parseStandaloneComposerSlashCommand, -} from "../composer-logic"; +import { composerRequiresModifier } from "../composer-logic"; import { derivePhase, - selectHandoffImageResources, deriveActivePlanState, selectComposerTasksPlan, deriveActiveWorkStartedAt, @@ -170,18 +133,10 @@ import { isLatestRunSettled, } from "../session-logic"; import { type LegendListRef } from "@legendapp/list/react"; -import { useUiStateStore } from "../uiStateStore"; import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefresh"; -import { - buildPlanImplementationThreadTitle, - buildPlanImplementationPrompt, - resolvePlanFollowUpSubmission, -} from "../proposedPlan"; -import { DEFAULT_INTERACTION_MODE, MAX_TERMINALS_PER_GROUP, type ChatMessage } from "../types"; +import { DEFAULT_INTERACTION_MODE, type ChatMessage } from "../types"; import { useTheme } from "../hooks/useTheme"; import { writeTextToClipboard } from "../hooks/useCopyToClipboard"; -import { isCommandPaletteOpen } from "../commandPaletteBus"; -import { settleAndAdvance } from "../settleAndAdvance"; import { subscribeSnapShotComposerFocus } from "../lib/desktopSnapShot"; import { useMediaQuery } from "../hooks/useMediaQuery"; import { FileMetadataThreadProvider } from "../hooks/FileMetadataThreadProvider"; @@ -195,25 +150,15 @@ import { selectActiveRightPanelSurface, selectThreadPanelOpen, selectThreadRightPanelState, - type RightPanelSurface, useRightPanelStore, } from "../rightPanelStore"; -import { - isPreviewSupportedInRuntime, - setActivePreviewTab, - useThreadPreviewState, -} from "../previewStateStore"; -import { BrowserSettingsReadError, openUrlInPreview } from "../browser/openFileInPreview"; -import { resolveDiscoveredServerUrl } from "../browser/browserTargetResolver"; +import { isPreviewSupportedInRuntime, useThreadPreviewState } from "../previewStateStore"; import { previewRuntimeTabId } from "../browser/previewRuntimeTabId"; -import { addBrowserSurface } from "./preview/addBrowserSurface"; import { ThreadPreviewMiniPlayer } from "./preview/ThreadPreviewMiniPlayer"; import { usePreviewSession } from "./preview/usePreviewSession"; -import { subscribePreviewAction } from "./preview/previewActionBus"; import { getConfiguredPreviewUrls } from "./preview/previewEmptyStateLogic"; import { - browserMiniPlayerSource, previewMiniPlayerSourceKey, selectThreadPreviewMiniPlayer, usePreviewMiniPlayerStore, @@ -226,18 +171,11 @@ import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop"; import { isEditableFocused } from "../lib/editableFocus"; import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings"; import { shortcutLabelForCommand } from "../keybindings"; -import { - AlarmClockIcon, - CheckCircle2Icon, - PaperclipIcon, - ChevronDownIcon, - DownloadIcon, -} from "lucide-react"; import { cn } from "~/lib/utils"; import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar"; import { stackedThreadToast, toastManager } from "./ui/toast"; import { projectScriptIdFromCommand } from "~/projectScripts"; -import { newDraftId, newMessageId, newThreadId } from "~/lib/utils"; +import { newMessageId } from "~/lib/utils"; import { registerFaviconProjectForThread } from "~/browserFaviconStore"; import { applyProviderInstanceSettings, @@ -254,29 +192,18 @@ import { import { useNowMinute } from "../hooks/useNowMinute"; import { usePanelAnimationSettings, usePanelPresence } from "../panelAnimations"; import { useNewThreadHandler } from "../hooks/useHandleNewThread"; -import { useRemoveClonedProject } from "../hooks/useRemoveClonedProject"; import { useOpenPanelPullRequestUrl } from "../hooks/useOpenPanelPullRequestUrl"; -import { resolveAppModelSelectionForInstance } from "../modelSelection"; -import { confirmTerminalClose } from "../lib/terminalCloseConfirm"; import { isPreviewFocused } from "../lib/previewFocus"; import { getTerminalFocusOwner } from "../lib/terminalFocus"; -import { findReusableProjectScriptTerminal } from "../lib/projectScriptTerminal"; -import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions"; import { deriveLogicalProjectKeyFromSettings, selectProjectGroupingSettings, } from "../logicalProject"; -import { buildDraftThreadRouteParams, buildThreadRouteParams } from "../threadRoutes"; import { isSameSidebarThreadRef, useSidebarPendingFileDropStore, } from "../sidebarPendingFileDropStore"; import { - beginBackgroundDraftSubmissionByRef, - clearBackgroundDraftSubmissionByRef, - finalizePromotedDraftThreadByRef, - markPromotedDraftThreadByRef, - restoreFailedDraftThread, composerDraftHasUserContent, type ComposerFileAttachment, type ComposerImageAttachment, @@ -284,21 +211,13 @@ import { useComposerDraftStore, DraftId, } from "../composerDraftStore"; -import { type TerminalContextDraft, type TerminalContextSelection } from "../lib/terminalContext"; -import { - collectInlineContextIds, - ensureInlineContextReferences, -} from "../lib/composerContextReferences"; -import { - buildMessageContext, - previewAnnotationContextReference, -} from "../lib/composerContextRecords"; +import { type TerminalContextDraft } from "../lib/terminalContext"; +import { collectInlineContextIds } from "../lib/composerContextReferences"; import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; import { useKnownTerminalSessions, useThreadRunningTerminalIds } from "../state/terminalSessions"; import { useEnvironmentQuery } from "../state/query"; import { useEnvironmentScope } from "~/state/session"; import { - environmentServerConfigsAtom, primaryServerAvailableEditorsAtom, primaryServerKeybindingsAtom, serverEnvironment, @@ -306,10 +225,6 @@ import { import { threadEnvironment } from "../state/threads"; import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills"; import { vcsEnvironment } from "../state/vcs"; -import { sourceControlEnvironment } from "../state/sourceControl"; -import { useProjectClone } from "../state/projectClones"; -import { projectCloneDisplayName, projectCloneProgressSummary } from "@t3tools/contracts"; -import { dismissProjectFileCopy, useProjectFileCopy } from "../lib/addProjectToMachine"; import { type EnvironmentPresentation, useEnvironmentProviders, @@ -324,13 +239,10 @@ import { useThreadStatus, useThreadHistory, useQuietThreadShell, - useChildThreadInputs, useThreadVisibleTurnItems, useThreadCheckpointSummaries, - readThreadShell, - waitForThreadShell, } from "../state/entities"; -import { environmentShell, useEnvironmentShellHasSnapshot } from "../state/shell"; +import { useEnvironmentShellHasSnapshot } from "../state/shell"; import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer"; import { DraftHeroHeadline } from "./chat/DraftHeroHeadline"; import { ExpandedImageDialogHost, openExpandedImagePreview } from "./chat/ExpandedImageDialog"; @@ -338,9 +250,6 @@ import { BranchRestoreConfirmHost, DeviceSetupDialogHost, openBranchRestoreConfirm, - openDeviceSetupDialog, - openPullRequestThreadDialog, - openRevertConfirm, PullRequestThreadDialogHost, RevertConfirmHost, } from "./chat/ChatOverlayHosts"; @@ -360,7 +269,8 @@ import { useOpenFavoriteEditorShortcut } from "./chat/OpenInPickerShortcut"; import { PanelLayoutControls, type PanelLayoutControlsProps, - RightPanelMaximizeControl, + ThreadPanelHeaderControl, + WorkspaceTitlebarControls, } from "./chat/PanelLayoutControls"; import type { ExpandedImagePreview } from "./chat/ExpandedImagePreview"; import { ThreadDetailsPanel } from "./chat/ThreadDetailsPanel"; @@ -373,15 +283,12 @@ import { } from "./BranchToolbar.logic"; import { getProviderStatusBannerKey, - ProviderStatusBanner, shouldShowProviderStatusBanner, } from "./chat/ProviderStatusBanner"; import { - dismissThreadErrorBannerForSession, getThreadErrorBannerKey, isThreadErrorBannerDismissedForSession, shouldShowThreadErrorBanner, - ThreadErrorBanner, } from "./chat/ThreadErrorBanner"; import { QueuedRunsControl, type QueuedRunsControlHandle } from "./chat/QueuedRunsControl"; import { useThreadLinkedPullRequest } from "./pullRequest/useThreadLinkedPullRequest"; @@ -390,8 +297,6 @@ import { useIncrementalTimelineEntries } from "../hooks/useIncrementalTimelineEn import { useRightPanelSurfaceClose } from "../hooks/useRightPanelSurfaceClose"; import { useAgentOpenedPreviews } from "./preview/useAgentOpenedPreviews"; import type { ComposerBannerStackItem } from "./chat/ComposerBannerStack"; -import { ThreadStatusLine } from "./chat/ThreadStatusLine"; -import { formatRelativeTimeLabel, formatRelativeTimeUntilLabel } from "../timestampFormat"; import { ComposerSurface } from "./chat/ComposerSurface"; import { resolveThreadSyncPhase } from "../threadSync"; import { @@ -406,74 +311,40 @@ import { import { MOBILE_COMPOSER_VIEW_TRANSITION_NAME, MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME, - runMobileComposerTransition, } from "./chat/draftHeroTransition"; -import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch"; import { - branchMismatchKey, - buildExpiredTerminalContextToastCopy, buildLocalDraftThread, collectUserMessageBlobPreviewUrls, deriveCommittedServerUserMessageIds, - deriveComposerSendState, dismissBranchMismatchForSession, - isBranchMismatchDismissedForSession, - shouldShowBranchMismatchBanner, shouldShowPlanFollowUpPrompt, shouldRenderPreviewMiniPlayer, - getStartedThreadModelChangeBlockReason, - LAST_INVOKED_SCRIPT_BY_PROJECT_KEY, - LastInvokedScriptByProjectSchema, deriveLockedProvider, - readFileAsDataUrl, resolveFileAttachmentUrl, resolveComposerInteractionMode, resolveComposerProviderSelection, resolveThreadMetadataUpdateForNextTurn, resolveSendEnvMode, - revokeBlobPreviewUrl, revokeUserMessagePreviewUrls, startNewThreadForProject, codexArtifactTemplatePromptToAppend, - waitForStartedServerThread, shouldRefocusComposerOnWindowFocus, } from "./ChatView.logic"; import { useLocalStorage } from "~/hooks/useLocalStorage"; import { useComposerHandleContext } from "../composerHandleContext"; -import { - awaitAttachmentUploads, - getUploadedAttachments, - readAttachmentUpload, - releaseDraftAttachments, - retryAttachmentUpload, - startAttachmentUpload, -} from "../lib/attachmentUploadQueue"; -import { previewEnvironment } from "../state/preview"; import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments"; import { appAtomRegistry } from "../rpc/atomRegistry"; -import { fileAttachmentCapabilityBlockReason } from "./chat/composerAttachmentFiles"; import { assetEnvironment } from "../state/assets"; import { readEnvironmentScope, readPreparedConnection } from "../state/session"; import { useAtomCommand } from "../state/use-atom-command"; import { useOrchestrationCommand } from "../state/use-orchestration-command"; import { useAtomQueryRunner } from "../state/use-atom-query-runner"; -import { Button } from "./ui/button"; -import { useAssetUrls } from "../assets/assetUrls"; -import { - ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, - threadContextsOutsideEnvironment, -} from "@t3tools/shared/composerContextReferences"; import { observeResize } from "~/lib/observeResize"; import { ThreadVisitWatermark } from "./chat/ThreadVisitWatermark"; import { ChatTerminalDrawers } from "./chat/ChatTerminalDrawers"; import { ChatRightPanel } from "./chat/ChatRightPanel"; import { useDraftEnvironmentRouting } from "./chat/useDraftEnvironmentRouting"; -import { - backgroundWorkBannerItem, - branchMismatchBannerItem, - childInputBannerItem, - goalBannerItem, -} from "./chat/ThreadActivityBanners"; +import { branchMismatchBannerItem } from "./chat/ThreadActivityBanners"; import { useTimelineFollow } from "./chat/useTimelineFollow"; import { type EnvironmentUnavailableState, @@ -481,27 +352,10 @@ import { } from "./chat/useSystemComposerBanners"; import { useDraftHeroLayoutTransition } from "./chat/useDraftHeroLayoutTransition"; import { useLocalDispatchState } from "./chat/useLocalDispatchState"; +import { draftFanoutSelectionsAtom, draftSendState } from "./chat/chatViewSend"; import { - draftFanoutSelectionsAtom, - draftSendState, - type MultipleModelTarget, - resolveMultipleModelTargets, - restoreComposerDraft, - rewindToMessage, - startFanoutThread, -} from "./chat/chatViewSend"; -import { - boundAttachmentIds, - chatActionErrorMessage, - formatOutgoingPrompt, - optimisticMessageAttachments, - planComposerTurn, - sendTitleFallbackLabels, - snapshotComposerSend, - withMessageContext, isCompactCommandMessage, type LocalThreadErrorEntry, - makeModelDisabledReason, makeThreadErrorSetter, } from "./ChatView.logic"; @@ -511,15 +365,11 @@ const EMPTY_USAGE_LIMIT_SOURCES: UsageLimitSourceSnapshots = []; import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates"; const EMPTY_FEEDBACK_SUBMISSIONS: ReadonlyArray = []; -const RELATED_THREAD_SHELL_WAIT_MS = 1_000; const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = []; const EMPTY_AUTO_UPDATE_ENVIRONMENTS: ReadonlyArray = []; const EMPTY_PENDING_FILE_SURFACE_IDS: ReadonlySet = new Set(); -const SCRIPT_TERMINAL_COLS = 120; -const SCRIPT_TERMINAL_ROWS = 30; - type ChatViewProps = | { environmentId: EnvironmentId; @@ -540,13 +390,6 @@ type ChatViewProps = draftId: DraftId; }; -interface TerminalLaunchContext { - threadId: ThreadId; - cwd: string; - worktreePath: string | null; -} - -const ENVIRONMENT_UNAVAILABLE_SEND_TOAST_TRAIL_SIZE = 3; const EMPTY_HELD_TURN_DIFF_SUMMARIES: readonly never[] = []; const noopHeldTurnDiff = (_turnId: RunId, _filePath?: string) => {}; const noopHeldRevert = (_targetTurnCount: number) => {}; @@ -563,12 +406,8 @@ export default function ChatView(props: ChatViewProps) { } = props; const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope); - const hasTerminalWriteAccess = () => - readEnvironmentScope(environmentId, AuthTerminalOperateScope); - const canReadTerminal = useEnvironmentScope(environmentId, AuthTerminalReadScope); const draftId = routeKind === "draft" ? props.draftId : null; const handleNewThread = useNewThreadHandler(); - const { settleThread, pinThread, confirmAndUnpinThread } = useThreadActions(); const routeThreadRef = scopeThreadRef(environmentId, threadId); const routeThreadKey = scopedThreadKey(routeThreadRef); const currentRouteThreadKeyRef = useRef(routeThreadKey); @@ -578,13 +417,10 @@ export default function ChatView(props: ChatViewProps) { currentRouteThreadKeyRef.current = null; }; }, [routeThreadKey]); - const createThread = useOrchestrationCommand(threadEnvironment.create, { reportFailure: false }); - const deleteThread = useOrchestrationCommand(threadEnvironment.delete, { reportFailure: false }); const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, { reportFailure: false, }); const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope); - const switchGitRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false }); const setThreadRuntimeMode = useOrchestrationCommand(threadEnvironment.setRuntimeMode, { reportFailure: false, }); @@ -594,12 +430,6 @@ export default function ChatView(props: ChatViewProps) { const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, { reportFailure: false, }); - const resumeThreadQueue = useOrchestrationCommand(threadEnvironment.resumeThreadQueue, { - reportFailure: false, - }); - const uploadThreadFeedback = useOrchestrationCommand(threadEnvironment.uploadFeedback, { - reportFailure: false, - }); const createAttachmentAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { reportFailure: false, refresh: true, @@ -611,13 +441,6 @@ export default function ChatView(props: ChatViewProps) { label: "load earlier thread history", reportFailure: false, }); - const revertThreadCheckpoint = useOrchestrationCommand(threadEnvironment.revertCheckpoint, { - reportFailure: false, - }); - const forkThreadFromRun = useAtomCommand(threadEnvironment.forkFromRun, { - reportFailure: false, - }); - const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false }); const { environments } = useEnvironments(); const providersByEnvironment = useEnvironmentProviders(); const primaryEnvironment = usePrimaryEnvironment(); @@ -640,48 +463,10 @@ export default function ChatView(props: ChatViewProps) { }); const serverThreadProjection = useThreadProjection(routeThreadDetailRef); const serverProjection = serverThreadProjection?.projection ?? null; - const serverThread = (() => { - if (serverThreadShell !== null || serverProjection === null) { - return serverThreadShell; - } - const latestRun = deriveLatestThreadRun(serverProjection); - const runtime = deriveThreadRuntime(serverProjection); - const pendingRuntimeRequest = - serverProjection.runtimeRequests.findLast((request) => request.status === "pending") ?? null; - // Direct links can hydrate detail before the thread enters the shell index. - return { - ...presentThreadShell(environmentId, { - ...serverProjection.thread, - latestRunId: latestRun?.runId ?? null, - activeRunId: runtime?.activeRunId ?? null, - status: runtime?.status ?? "idle", - pendingRuntimeRequest, - latestVisibleMessage: null, - latestUserMessageAt: - serverProjection.messages.findLast((message) => message.role === "user")?.updatedAt ?? - null, - hasActionableProposedPlan: serverProjection.plans.some( - (plan) => plan.kind === "proposed_plan" && plan.status === "active", - ), - providerInstanceHistory: [ - ...new Set( - serverProjection.providerThreads - .filter((thread) => thread.appThreadId === threadId && thread.ownerNodeId === null) - .map((thread) => thread.providerInstanceId), - ), - ], - goal: - serverProjection.providerThreads.find( - (thread) => thread.id === serverProjection.thread.activeProviderThreadId, - )?.goal ?? null, - itemCount: serverProjection.turnItems.length, - visibleItemCount: serverProjection.visibleTurnItems.length, - updatedAt: serverProjection.updatedAt, - }), - latestRun, - runtime, - }; - })(); + const serverThread = + serverThreadShell !== null || serverProjection === null + ? serverThreadShell + : presentThreadShellFromProjection(environmentId, threadId, serverProjection); const promptRef = useRef(""); const localComposerRef = useRef(null); const composerRef = useComposerHandleContext() ?? localComposerRef; @@ -747,12 +532,8 @@ export default function ChatView(props: ChatViewProps) { })(); const settings = useEnvironmentSettings(environmentId); const clientSettingsHydrated = useClientSettingsHydrated(); - const setStickyComposerModelSelection = useComposerDraftStore( - (store) => store.setStickyModelSelection, - ); const timestampFormat = settings.timestampFormat; const navigate = useNavigate(); - const router = useRouter(); // Selects primitives: an object here is new on every router store update, which // re-renders ChatView on unrelated navigation state changes. const citationHref = useLocation({ select: (location) => location.href }); @@ -800,33 +581,11 @@ export default function ChatView(props: ChatViewProps) { return draft ? composerDraftHasUserContent({ ...draft, prompt: "" }) : false; }); const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt); - const setComposerDraftTerminalContexts = useComposerDraftStore( - (store) => store.setTerminalContexts, - ); - const setComposerDraftPreviewAnnotations = useComposerDraftStore( - (store) => store.setPreviewAnnotations, - ); - const setComposerDraftReviewComments = useComposerDraftStore((store) => store.setReviewComments); - const setComposerDraftThreadContexts = useComposerDraftStore((store) => store.setThreadContexts); - const setComposerDraftModelSelection = useComposerDraftStore((store) => store.setModelSelection); - const setComposerDraftRuntimeMode = useComposerDraftStore((store) => store.setRuntimeMode); - const setComposerDraftInteractionMode = useComposerDraftStore( - (store) => store.setInteractionMode, - ); - const clearComposerDraftContent = useComposerDraftStore((store) => store.clearComposerContent); const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); - const getDraftSessionByLogicalProjectKey = useComposerDraftStore( - (store) => store.getDraftSessionByLogicalProjectKey, - ); - const getDraftSession = useComposerDraftStore((store) => store.getDraftSession); - const setLogicalProjectDraftThreadId = useComposerDraftStore( - (store) => store.setLogicalProjectDraftThreadId, - ); const composerImagesRef = useRef([]); const composerFilesRef = useRef([]); const composerTerminalContextsRef = useRef([]); const branchToolbarRef = useRef(null); - const pasteAsTextShortcutUntilRef = useRef(0); const [restingComposerControlsHost, setRestingComposerControlsHost] = useState(null); const [restingComposerControlsVisible, setRestingComposerControlsVisible] = useState(false); @@ -860,10 +619,6 @@ export default function ChatView(props: ChatViewProps) { const feedbackUploading = feedbackSubmissions.some( (submission) => submission.status === "uploading", ); - const optimisticUserMessagesRef = useRef(optimisticUserMessages); - useLayoutEffect(() => { - optimisticUserMessagesRef.current = optimisticUserMessages; - }); const [localDraftErrorsByDraftId, setLocalDraftErrorsByDraftId] = useState< Record >({}); @@ -895,9 +650,6 @@ export default function ChatView(props: ChatViewProps) { const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0); const [terminalUiLaunchContext, setTerminalUiLaunchContext] = useState(null); - const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState< - Record - >({}); // Overrides chosen before a server thread's first turn; they belong to that thread only. const [pendingServerThreadEnvModeEntry, setPendingServerThreadEnvModeEntry] = useState<{ readonly threadId: ThreadId; @@ -911,11 +663,6 @@ export default function ChatView(props: ChatViewProps) { pendingServerThreadStartFromOriginByThreadId, setPendingServerThreadStartFromOriginByThreadId, ] = useState>({}); - const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useLocalStorage( - LAST_INVOKED_SCRIPT_BY_PROJECT_KEY, - {}, - LastInvokedScriptByProjectSchema, - ); const legendListRef = useRef(null); const getTimelineScrollableNode = () => legendListRef.current?.getScrollableNode() ?? null; const getTimelineScrollableNodeStable = useStableCallback(getTimelineScrollableNode); @@ -929,16 +676,8 @@ export default function ChatView(props: ChatViewProps) { const composerMountedRef = useRef(true); const [scrollToEndClearance, setScrollToEndClearance] = useState(0); const [timelineOverflows, setTimelineOverflows] = useState(false); - const attachmentPreviewHandoffByMessageIdRef = useRef>({}); - const attachmentPreviewPromotionInFlightByMessageIdRef = useRef>({}); const fanoutSelectionsAtom = draftFanoutSelectionsAtom(routeThreadKey); - const { sendInFlight: sendInFlightRef, uncertainSubmissions: uncertainMultipleSubmissionsRef } = - draftSendState(routeThreadKey); - const [resumingThreadKeys, setResumingThreadKeys] = useState>( - () => new Set(), - ); - const isResuming = resumingThreadKeys.has(routeThreadKey); - const composerSendGenerationRef = useRef(0); + const { sendInFlight: sendInFlightRef } = draftSendState(routeThreadKey); const multipleModelSelections = useAtomValue(fanoutSelectionsAtom); const setMultipleModelSelections = ( selections: SetStateAction | null>, @@ -948,20 +687,12 @@ export default function ChatView(props: ChatViewProps) { ); }; const setMultipleModelSelectionsStable = useStableCallback(setMultipleModelSelections); - const readMultipleModelSelections = () => appAtomRegistry.get(fanoutSelectionsAtom); - const environmentUnavailableSendToastSlotRef = useRef(0); const feedbackUploadsInFlightRef = useRef(new Set()); const terminalUiOpenByThreadRef = useRef>({}); const terminalUiState = useTerminalUiStateStore((state) => selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef), ); - const storeSetTerminalOpen = useTerminalUiStateStore((s) => s.setTerminalOpen); - const storeEnsureTerminal = useTerminalUiStateStore((state) => state.ensureTerminal); - const storeSplitTerminal = useTerminalUiStateStore((s) => s.splitTerminal); - const storeSplitTerminalVertical = useTerminalUiStateStore((s) => s.splitTerminalVertical); - const storeNewTerminal = useTerminalUiStateStore((s) => s.newTerminal); - const storeCloseTerminal = useTerminalUiStateStore((s) => s.closeTerminal); const fallbackDraftProjectRef = draftThread ? scopeProjectRef(draftThread.environmentId, draftThread.projectId) @@ -1129,7 +860,6 @@ export default function ChatView(props: ChatViewProps) { return labels; })(); const activeThreadRef = useActiveThreadRef(activeThread); - const terminalActions = useThreadTerminalActions(activeThreadRef); const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null; const activeEnvironmentServerBrowser = useEnvironmentSupportsServerBrowser( activeThreadRef?.environmentId ?? null, @@ -1311,110 +1041,8 @@ export default function ChatView(props: ChatViewProps) { activeProject ?? undefined, ); const activeProjectScripts = activeProject ? resolveProjectScripts(settings, activeProject) : []; - const activeProjectClone = useProjectClone(activeProjectRef); - const cancelProjectClone = useAtomCommand(sourceControlEnvironment.cancelProjectClone, { - reportFailure: false, - }); - const retryProjectClone = useAtomCommand(sourceControlEnvironment.retryProjectClone, { - reportFailure: false, - }); - const removeClonedProject = useRemoveClonedProject(); - const runProjectCloneAction = async ( - title: string, - action: () => Promise>, - ): Promise => { - const result = await action(); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title, - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - }; - const runProjectCloneActionStable = useStableCallback(runProjectCloneAction); - const activeProjectFileCopy = useProjectFileCopy(activeProjectRef); - const projectCloneSendBlockReason = - activeProjectClone?.phase === "running" - ? "Cloning repository" - : activeProjectClone !== null && activeProjectClone.phase !== "done" - ? "Repository not cloned" - : activeProjectFileCopy?.phase === "copying" - ? "Copying files" - : null; - const projectCloneBannerItem = (() => { - if (activeProjectFileCopy?.phase === "failed" && activeProjectRef) { - return { - id: `project-file-copy:${activeProjectRef.projectId}`, - variant: "error", - icon: , - title: activeProjectFileCopy.title, - description: activeProjectFileCopy.failures.join("\n"), - onDismiss: () => dismissProjectFileCopy(activeProjectRef), - }; - } - if (!activeProjectClone || !activeProjectRef || activeProjectClone.phase === "done") { - return null; - } - const name = projectCloneDisplayName(activeProjectClone); - const { environmentId, projectId } = activeProjectRef; - if (activeProjectClone.phase === "running") { - return { - id: `project-clone:${projectId}`, - variant: "info", - priority: "activity", - icon: , - title: `Cloning ${name}`, - description: projectCloneProgressSummary(activeProjectClone), - actions: ( - - ), - }; - } - const cancelled = activeProjectClone.phase === "cancelled"; - return { - id: `project-clone:${projectId}`, - variant: cancelled ? "warning" : "error", - icon: , - title: cancelled ? `Cancelled cloning ${name}` : `Failed to clone ${name}`, - description: cancelled ? "Retry to bring in the repository." : activeProjectClone.error, - actions: ( - <> - - - - ), - }; - })() as ComposerBannerStackItem | null; + const { projectCloneBannerItem, projectCloneSendBlockReason } = + useProjectCloneBanner(activeProjectRef); const activeProjectDefaultModelSelection = activeProjectSettings.settings.defaultModelSelection; const handleNewThreadInActiveProject = () => { startNewThreadForProject(activeProjectRef, handleNewThread); @@ -1509,91 +1137,18 @@ export default function ChatView(props: ChatViewProps) { activeEnvironment: activeEnvironmentOption, canPickEnvironment: hasMultipleEnvironments, }); - const openPullRequestDialog = (reference?: string) => { - if (!canCheckoutPullRequestIntoThread) { - return; - } - if (activeThreadKey === null) return; - openPullRequestThreadDialog(activeThreadKey, reference); - }; - const openPullRequestDialogStable = useStableCallback(openPullRequestDialog); - const openOrReuseProjectDraftThread = async (input: { - branch: string; - worktreePath: string | null; - envMode: DraftThreadEnvMode; - }) => { - if (!activeProject) { - throw new Error("No active project is available for this pull request."); - } - const activeProjectRef = scopeProjectRef(activeProject.environmentId, activeProject.id); - const logicalProjectKey = deriveLogicalProjectKeyFromSettings( - activeProject, + const { handlePreparedPullRequestThreadStable, openPullRequestDialogStable } = + usePullRequestDraftThread({ + routeKind, + draftId, + settings, projectGroupingSettings, - ); - const storedDraftSession = getDraftSessionByLogicalProjectKey(logicalProjectKey); - if (storedDraftSession) { - setDraftThreadContext(storedDraftSession.draftId, input); - setLogicalProjectDraftThreadId( - logicalProjectKey, - activeProjectRef, - storedDraftSession.draftId, - { - threadId: storedDraftSession.threadId, - ...input, - }, - ); - if (routeKind !== "draft" || draftId !== storedDraftSession.draftId) { - await navigate({ - to: "/draft/$draftId", - params: buildDraftThreadRouteParams(storedDraftSession.draftId), - }); - } - return storedDraftSession.threadId; - } - - const activeDraftSession = routeKind === "draft" && draftId ? getDraftSession(draftId) : null; - if (!isServerThread && activeDraftSession?.logicalProjectKey === logicalProjectKey && draftId) { - setDraftThreadContext(draftId, input); - setLogicalProjectDraftThreadId(logicalProjectKey, activeProjectRef, draftId, { - threadId: activeDraftSession.threadId, - createdAt: activeDraftSession.createdAt, - runtimeMode: activeDraftSession.runtimeMode, - interactionMode: activeDraftSession.interactionMode, - ...input, - }); - return activeDraftSession.threadId; - } - - const nextDraftId = newDraftId(); - const nextThreadId = newThreadId(); - setLogicalProjectDraftThreadId(logicalProjectKey, activeProjectRef, nextDraftId, { - threadId: nextThreadId, - createdAt: new Date().toISOString(), - runtimeMode: resolveProjectSettings(settings, activeProject.id, activeProject).settings - .defaultRuntimeMode, - interactionMode: DEFAULT_INTERACTION_MODE, - ...input, - }); - await navigate({ - to: "/draft/$draftId", - params: buildDraftThreadRouteParams(nextDraftId), - }); - return nextThreadId; - }; - - const handlePreparedPullRequestThread = async (input: { - branch: string; - worktreePath: string | null; - }) => { - await openOrReuseProjectDraftThread({ - branch: input.branch, - worktreePath: input.worktreePath, - envMode: input.worktreePath ? "worktree" : "local", + activeProject, + activeThreadKey, + isServerThread, + canCheckoutPullRequestIntoThread, }); - }; - const handlePreparedPullRequestThreadStable = useStableCallback(handlePreparedPullRequestThread); - const serverConfig = activeThread ? (activeEnvironment?.serverConfig ?? null) : (primaryEnvironment?.serverConfig ?? null); @@ -1746,13 +1301,6 @@ export default function ChatView(props: ChatViewProps) { composerRef, setThreadError, }); - // A send awaits uploads before it declines, so it reads the approvals pending by then. - const pendingApprovalsRef = useRef(pendingApprovals); - const respondingRequestIdsRef = useRef(respondingRequestIds); - useLayoutEffect(() => { - pendingApprovalsRef.current = pendingApprovals; - respondingRequestIdsRef.current = respondingRequestIds; - }, [pendingApprovals, respondingRequestIds]); const activeProposedPlan = (() => { if (!latestRunSettled) { return null; @@ -1851,31 +1399,7 @@ export default function ChatView(props: ChatViewProps) { activeThreadLiveTokenUsage, activeProviderThread, ); - const pendingBackgroundTasks = (() => { - if (serverProjection === null || serverProjection === undefined) { - return []; - } - const sessionError = - serverProjection.providerSessions.findLast( - (session) => session.providerInstanceId === serverProjection.thread.providerInstanceId, - )?.lastError ?? null; - const latestRun = - usageLimitRunPresentedAsLatest( - serverProjection.runs, - serverProjection.turnItems, - sessionError, - ) ?? latestUnheldRun(serverProjection.runs); - return [ - ...derivePendingBackgroundWork({ - latestRun, - providerThreads: serverProjection.providerThreads, - turnItems: serverProjection.turnItems, - activeProviderThreadId: serverProjection.thread.activeProviderThreadId, - runs: serverProjection.runs, - pullRequests: serverProjection.thread.pullRequests, - }), - ]; - })(); + const pendingBackgroundTasks = deriveThreadPendingBackgroundTasks(serverProjection); const activeWorkStartedAt = deriveActiveWorkStartedAt(activeActivityRun, activeRuntime, localDispatchStartedAt) ?? runlessWorkStartedAt; @@ -1883,69 +1407,6 @@ export default function ChatView(props: ChatViewProps) { const sendQueuesBehindSetup = isServerThread && (activeRunPreparing || activeActivityRun?.status === "starting"); const [setupQueueSendThreadKey, setSetupQueueSendThreadKey] = useState(null); - useEffect(() => { - attachmentPreviewHandoffByMessageIdRef.current = attachmentPreviewHandoffByMessageId; - }, [attachmentPreviewHandoffByMessageId]); - const clearAttachmentPreviewHandoff = ( - messageId: MessageId, - previewUrls?: ReadonlyArray, - ) => { - delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId]; - const currentPreviewUrls = - previewUrls ?? attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? []; - setAttachmentPreviewHandoffByMessageId((existing) => { - if (!(messageId in existing)) { - return existing; - } - const next = { ...existing }; - delete next[messageId]; - attachmentPreviewHandoffByMessageIdRef.current = next; - return next; - }); - for (const previewUrl of currentPreviewUrls) { - revokeBlobPreviewUrl(previewUrl); - } - }; - const clearAttachmentPreviewHandoffStable = useStableCallback(clearAttachmentPreviewHandoff); - const clearAttachmentPreviewHandoffs = () => { - attachmentPreviewPromotionInFlightByMessageIdRef.current = {}; - for (const previewUrls of Object.values(attachmentPreviewHandoffByMessageIdRef.current)) { - for (const previewUrl of previewUrls) { - revokeBlobPreviewUrl(previewUrl); - } - } - attachmentPreviewHandoffByMessageIdRef.current = {}; - setAttachmentPreviewHandoffByMessageId({}); - }; - const clearAttachmentPreviewHandoffsStable = useStableCallback(clearAttachmentPreviewHandoffs); - useEffect(() => { - return () => { - clearAttachmentPreviewHandoffsStable(); - for (const message of optimisticUserMessagesRef.current) { - revokeUserMessagePreviewUrls(message); - } - }; - }, [clearAttachmentPreviewHandoffsStable]); - const handoffAttachmentPreviews = (messageId: MessageId, previewUrls: string[]) => { - if (previewUrls.length === 0) return; - - const previousPreviewUrls = attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? []; - const nextPreviewUrlSet = new Set(previewUrls); - for (const previewUrl of previousPreviewUrls) { - if (!nextPreviewUrlSet.has(previewUrl)) { - revokeBlobPreviewUrl(previewUrl); - } - } - setAttachmentPreviewHandoffByMessageId((existing) => { - const next = { - ...existing, - [messageId]: previewUrls, - }; - attachmentPreviewHandoffByMessageIdRef.current = next; - return next; - }); - }; - const handoffAttachmentPreviewsStable = useStableCallback(handoffAttachmentPreviews); const downloadFileAttachment = async (attachment: ChatFileAttachment) => { const connection = readPreparedConnection(environmentId); if (!connection) { @@ -1980,132 +1441,12 @@ export default function ChatView(props: ChatViewProps) { } }; const openFileAttachmentStable = useStableCallback(openFileAttachment); - const serverAttachmentResources = selectHandoffImageResources( - Object.keys(attachmentPreviewHandoffByMessageId).length === 0 - ? undefined - : serverVisibleTurnItems.flatMap(({ item }) => - item.type === "user_message" - ? [{ id: item.messageId, role: "user" as const, attachments: item.attachments }] - : [], - ), - attachmentPreviewHandoffByMessageId, - ); - const serverAttachmentUrls = useAssetUrls(environmentId, serverAttachmentResources); - const serverAttachmentUrlById = new Map( - serverAttachmentResources.flatMap((resource, index) => { - const url = serverAttachmentUrls[index]; - return url ? [[resource.attachmentId, url] as const] : []; - }), - ); - useEffect(() => { - if (typeof Image === "undefined" || serverVisibleTurnItems.length === 0) { - return; - } - - const cleanups: Array<() => void> = []; - const userMessagesById = new Map( - serverVisibleTurnItems.flatMap((row) => - row.item.type === "user_message" ? [[String(row.item.messageId), row.item] as const] : [], - ), - ); - - for (const [messageId, handoffPreviewUrls] of Object.entries( - attachmentPreviewHandoffByMessageId, - )) { - if (attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId]) { - continue; - } - - const serverMessage = userMessagesById.get(messageId); - if (serverMessage === undefined || serverMessage.attachments.length === 0) { - continue; - } - - const serverPreviewUrls = serverMessage.attachments.flatMap((attachment) => - attachment.type === "image" - ? [serverAttachmentUrlById.get(attachment.id)].filter( - (previewUrl): previewUrl is string => previewUrl !== undefined, - ) - : [], - ); - if ( - serverPreviewUrls.length === 0 || - serverPreviewUrls.length !== handoffPreviewUrls.length || - serverPreviewUrls.some((previewUrl) => previewUrl.startsWith("blob:")) - ) { - continue; - } - - attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId] = true; - - let cancelled = false; - const imageInstances: HTMLImageElement[] = []; - - const preloadServerPreviews = Promise.all( - serverPreviewUrls.map( - (previewUrl) => - new Promise((resolve, reject) => { - const image = new Image(); - imageInstances.push(image); - const handleLoad = () => resolve(); - const handleError = () => - reject(new Error(`Failed to load server preview for ${messageId}.`)); - image.addEventListener("load", handleLoad, { once: true }); - image.addEventListener("error", handleError, { once: true }); - image.src = previewUrl; - }), - ), - ); - - void preloadServerPreviews - .then(() => { - if (cancelled) { - return; - } - clearAttachmentPreviewHandoffStable(messageId as MessageId, handoffPreviewUrls); - }) - .catch(() => { - if (!cancelled) { - delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId]; - } - }); - - cleanups.push(() => { - cancelled = true; - delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId]; - for (const image of imageInstances) { - image.src = ""; - } - }); - } - - return () => { - for (const cleanup of cleanups) { - cleanup(); - } - }; - }, [ - attachmentPreviewHandoffByMessageId, - clearAttachmentPreviewHandoffStable, - serverAttachmentUrlById, - serverVisibleTurnItems, - ]); - const timelineAttachmentUrlById = (() => { - const urls = new Map(serverAttachmentUrlById); - for (const row of serverVisibleTurnItems) { - if (row.item.type !== "user_message") continue; - const handoffUrls = attachmentPreviewHandoffByMessageId[row.item.messageId]; - if (handoffUrls === undefined) continue; - let imageIndex = 0; - for (const attachment of row.item.attachments) { - if (attachment.type !== "image") continue; - const handoffUrl = handoffUrls[imageIndex]; - imageIndex += 1; - if (handoffUrl !== undefined) urls.set(attachment.id, handoffUrl); - } - } - return urls; - })(); + const { handoffAttachmentPreviewsStable, timelineAttachmentUrlById } = + useAttachmentPreviewHandoff({ + environmentId, + serverVisibleTurnItems, + optimisticUserMessages, + }); const anchoredTimelineMessages = feedbackSubmissions.flatMap((submission) => submission.status === "interrupted" ? [] @@ -2196,70 +1537,16 @@ export default function ChatView(props: ChatViewProps) { panelAnimationDurationMs, ); const turnDiffSummaries = useThreadCheckpointSummaries(routeThreadDetailRef); - const availableRevertTurnCounts = (() => { - const available = new Set(); - const providerThread = serverProjection?.providerThreads.find( - (candidate) => candidate.id === serverProjection.thread.activeProviderThreadId, - ); - if ( - !providerThread?.providerSessionId || - providerThread.providerInstanceId !== serverProjection?.thread.modelSelection.instanceId - ) - return available; - available.add(0); - const attemptsById = new Map(serverProjection.attempts.map((attempt) => [attempt.id, attempt])); - const providerTurnsById = new Map< - OrchestrationV2ProviderTurn["id"], - OrchestrationV2ProviderTurn - >(); - const latestTurnByAttempt = new Map(); - for (const turn of serverProjection.providerTurns) { - providerTurnsById.set(turn.id, turn); - if (turn.runAttemptId === null) continue; - const latest = latestTurnByAttempt.get(turn.runAttemptId); - if (latest === undefined || turn.ordinal > latest.ordinal) { - latestTurnByAttempt.set(turn.runAttemptId, turn); - } - } - for (const run of serverProjection.runs) { - if (run.activeAttemptId === null) continue; - const attempt = attemptsById.get(run.activeAttemptId); - const providerTurn = - latestTurnByAttempt.get(run.activeAttemptId) ?? - (attempt?.providerTurnId == null - ? undefined - : providerTurnsById.get(attempt.providerTurnId)); - // A ready file checkpoint alone cannot restore the provider conversation. - if (providerTurn?.providerThreadId === providerThread.id) available.add(run.ordinal); - } - return available; - })(); + const availableRevertTurnCounts = deriveAvailableRevertTurnCounts(serverProjection); // A paged history window cannot identify the first loaded run as the thread start. const threadStartCheckpointReady = !serverThreadHistory.hasMoreHistory && findRevertCheckpoint(serverProjection?.checkpoints ?? [], 0) !== undefined; - /** - * File tools are explicit; completed commands are included because a shell - * command can mutate the workspace without reporting the paths it touched. - */ - const workspaceMutationId = (() => { - let itemId: string | null = null; - for (let index = serverVisibleTurnItems.length - 1; index >= 0; index -= 1) { - const item = serverVisibleTurnItems[index]?.item; - if (!item) continue; - if (item.type !== "command_execution" && item.type !== "file_change") continue; - if (item.status === "pending" || item.status === "running" || item.status === "waiting") { - continue; - } - itemId = item.id; - break; - } - const latestCheckpointCompletedAt = turnDiffSummaries.at(-1)?.completedAt ?? null; - return itemId === null && latestCheckpointCompletedAt === null - ? null - : JSON.stringify([itemId, latestCheckpointCompletedAt]); - })(); + const workspaceMutationId = deriveWorkspaceMutationId( + serverVisibleTurnItems, + turnDiffSummaries.at(-1)?.completedAt ?? null, + ); const gitCwd = activeProject ? projectScriptCwd({ @@ -2449,18 +1736,6 @@ export default function ChatView(props: ChatViewProps) { "terminal.close", terminalShortcutLabelOptions, ); - const onToggleDiff = () => { - if (!isServerThread) { - return; - } - if (!diffOpen) { - onDiffPanelOpen?.(); - } - if (activeThreadRef) { - useRightPanelStore.getState().toggle(activeThreadRef, "diff"); - } - }; - const onToggleDiffStable = useStableCallback(onToggleDiff); const { needsLoadBalancing, @@ -2489,17 +1764,6 @@ export default function ChatView(props: ChatViewProps) { sendInFlightRef, }); - const activeTerminalGroup = - terminalUiState.terminalGroups.find( - (group) => group.id === terminalUiState.activeTerminalGroupId, - ) ?? - terminalUiState.terminalGroups.find((group) => - group.terminalIds.includes(terminalUiState.activeTerminalId), - ) ?? - null; - const hasReachedSplitLimit = - (activeTerminalGroup?.terminalIds.length ?? 0) >= MAX_TERMINALS_PER_GROUP; - const focusComposer = () => { composerRef.current?.focusAtEnd(); }; @@ -2570,199 +1834,38 @@ export default function ChatView(props: ChatViewProps) { }; const sendAppMessageStable = useStableCallback(sendAppMessage); const queuedRunsControlRef = useRef(null); - const addTerminalContextToDraft = (selection: TerminalContextSelection) => { - composerRef.current?.addTerminalContext(selection); - }; - const addTerminalContextToDraftStable = useStableCallback(addTerminalContextToDraft); - const setTerminalOpen = (open: boolean) => { - if (!activeThreadRef) return; - storeSetTerminalOpen(activeThreadRef, open); - }; - const setTerminalOpenStable = useStableCallback(setTerminalOpen); - const toggleTerminalVisibility = () => { - if (!activeThreadRef) return; - const nextOpen = !terminalUiState.terminalOpen; - if ( - nextOpen && - !readEnvironmentScope(environmentId, AuthTerminalReadScope) && - !hasTerminalWriteAccess() - ) - return; - if (nextOpen && hasTerminalWriteAccess() && terminalUiState.terminalIds.length === 0) { - // Server-created setup terminals exist before this client's drawer mounts. - // Reuse them before allocating a shell from the still-empty UI state. - const existingTerminalId = - runningTerminalIds.find((id) => !panelTerminalIds.has(id)) ?? - activeServerOrderedTerminalIds.find((id) => !panelTerminalIds.has(id)); - if (existingTerminalId !== undefined) { - storeEnsureTerminal(activeThreadRef, existingTerminalId, { open: true, active: true }); - return; - } - void terminalActions.launchTerminal({ - place: (terminalId) => storeEnsureTerminal(activeThreadRef, terminalId, { open: true }), - })?.result; - return; - } - setTerminalOpen(nextOpen); - }; - const toggleTerminalVisibilityStable = useStableCallback(toggleTerminalVisibility); - const splitTerminal = (direction: "horizontal" | "vertical" = "horizontal") => { - if (!activeThreadRef || hasReachedSplitLimit) return; - const launched = terminalActions.launchTerminal({ - place: (terminalId) => - direction === "vertical" - ? storeSplitTerminalVertical(activeThreadRef, terminalId) - : storeSplitTerminal(activeThreadRef, terminalId), - }); - if (!launched) return; - setTerminalFocusRequestId((value) => value + 1); - void launched.result; - }; - const splitTerminalStable = useStableCallback(splitTerminal); - const createNewTerminal = () => { - if (!activeThreadRef) return; - const launched = terminalActions.launchTerminal({ - place: (terminalId) => storeNewTerminal(activeThreadRef, terminalId), - }); - if (!launched) return; - setTerminalFocusRequestId((value) => value + 1); - void launched.result; - }; - const createNewTerminalStable = useStableCallback(createNewTerminal); - const closeTerminal = (terminalId: string) => { - if (!hasTerminalWriteAccess() || !activeThreadRef) return; - terminalActions.closeTerminalSession(terminalId); - storeCloseTerminal(activeThreadRef, terminalId); - setTerminalFocusRequestId((value) => value + 1); - }; - const runProjectScript = async ( - script: ProjectScript, - options?: { - cwd?: string; - env?: Record; - worktreePath?: string | null; - preferNewTerminal?: boolean; - rememberAsLastInvoked?: boolean; - shellHistory?: "preserve" | "suppress"; - }, - ) => { - if (!hasTerminalWriteAccess() || !activeThreadId || !activeProject || !activeThread) return; - if (options?.rememberAsLastInvoked !== false) { - setLastInvokedScriptByProjectId((current) => { - if (current[activeProject.id] === script.id) return current; - return { ...current, [activeProject.id]: script.id }; - }); - } - const targetCwd = options?.cwd ?? gitCwd ?? activeProject.workspaceRoot; - const reusableTerminalId = - options?.preferNewTerminal || - !canReuseTerminal || - !readEnvironmentScope(environmentId, AuthTerminalReadScope) - ? null - : findReusableProjectScriptTerminal({ - // Server sessions cover drawer terminals this client has not opened yet, such as a - // worktree setup shell; the helper drops the panel-owned ones. - drawerTerminalIds: [ - ...new Set([...terminalUiState.terminalIds, ...activeServerOrderedTerminalIds]), - ], - activeTerminalId: terminalUiState.activeTerminalId, - panelTerminalIds, - runningTerminalIds, - }); - const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null; - - setTerminalUiLaunchContext({ - threadId: activeThreadId, - cwd: targetCwd, - worktreePath: targetWorktreePath, - }); - if (!activeThreadRef) { - return; - } - setTerminalFocusRequestId((value) => value + 1); - - const launched = terminalActions.launchTerminal({ - // The drawer opens with the target already placed: opening it empty would claim - // DEFAULT_THREAD_TERMINAL_ID, which a right-panel terminal may already own. - place: (terminalId) => - reusableTerminalId === null - ? storeNewTerminal(activeThreadRef, terminalId) - : storeEnsureTerminal(activeThreadRef, terminalId, { open: true }), - ...(reusableTerminalId === null - ? { size: { cols: SCRIPT_TERMINAL_COLS, rows: SCRIPT_TERMINAL_ROWS } } - : { terminalId: reusableTerminalId }), - location: { cwd: targetCwd, worktreePath: targetWorktreePath }, - ...(options?.env ? { extraEnv: options.env } : {}), - }); - if (!launched) return; - const targetTerminalId = launched.terminalId; - const openResult = await launched.result; - if (openResult._tag === "Failure") { - if (!isAtomCommandInterrupted(openResult)) { - const error = squashAtomCommandFailure(openResult); - setThreadError( - activeThreadId, - error instanceof Error ? error.message : `Failed to run script "${script.name}".`, - ); - } - return; - } - - const writeResult = await terminalActions.writeToTerminal( - targetTerminalId, - options?.shellHistory === "preserve" - ? `${script.command}\r` - : projectScriptTerminalInput(script.command), - ); - if (!writeResult) return; - if (writeResult._tag === "Failure") { - if (!isAtomCommandInterrupted(writeResult)) { - const error = squashAtomCommandFailure(writeResult); - setThreadError( - activeThreadId, - error instanceof Error ? error.message : `Failed to run script "${script.name}".`, - ); - } - return; - } - if (script.autoOpenPreview && script.previewUrl && isPreviewSupportedInRuntime()) { - const previewResult = await openUrlInPreview({ - threadRef: activeThreadRef, - url: resolveDiscoveredServerUrl(activeThreadRef.environmentId, script.previewUrl), - openPreview, - }); - if (previewResult._tag === "Failure" && !isAtomCommandInterrupted(previewResult)) { - const error = squashAtomCommandFailure(previewResult); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Could not open preview", - description: error instanceof Error ? error.message : "An unexpected error occurred.", - }), - ); - } - } - }; - const runProjectScriptStable = useStableCallback(runProjectScript); - - const runProjectScriptRef = useRef(runProjectScriptStable); - useLayoutEffect(() => { - runProjectScriptRef.current = runProjectScriptStable; - }, [runProjectScriptStable]); - const runShellCommand = (command: string) => { - void runProjectScriptRef.current( - { - id: "chat-code-block", - name: "Chat code block", - command, - icon: "play", - runOnWorktreeCreate: false, - }, - { rememberAsLastInvoked: false, shellHistory: "preserve" }, - ); - }; - const runShellCommandStable = useStableCallback(runShellCommand); + const { + activatePanelTerminalStable, + addTerminalContextToDraftStable, + addTerminalSurfaceStable, + closePanelTerminalStable, + lastInvokedScriptByProjectId, + runProjectScriptStable, + runShellCommandStable, + splitPanelTerminalStable, + splitPanelTerminalVerticalStable, + toggleTerminalVisibilityStable, + shortcuts: terminalShortcuts, + } = useChatTerminalActions({ + environmentId, + composerRef, + terminalUiState, + activeThread, + activeThreadId, + activeThreadRef, + activeProject, + activeRightPanelSurface, + runningTerminalIds, + activeServerOrderedTerminalIds, + activeTerminalLabelsById, + panelTerminalIds, + canReuseTerminal, + gitCwd, + setTerminalFocusRequestId, + setTerminalUiLaunchContext, + setThreadError, + }); const { saveProjectScript: saveProjectScriptStable, updateProjectScript: updateProjectScriptStable, @@ -2773,80 +1876,10 @@ export default function ChatView(props: ChatViewProps) { scripts: activeProjectScripts, settings, }); - - const handleRuntimeModeChange = (mode: RuntimeMode) => { - if (mode === runtimeMode) return; - setComposerDraftRuntimeMode(composerDraftTarget, mode); - if (isLocalDraftThread) { - setDraftThreadContext(composerDraftTarget, { runtimeMode: mode }); - } - scheduleComposerFocus(); - }; - const handleRuntimeModeChangeStable = useStableCallback(handleRuntimeModeChange); - - const handleInteractionModeChange = (mode: ProviderInteractionMode) => { - if (mode === "plan" && !interactionModeEnabled) return; - if (mode === interactionMode) return; - setComposerDraftInteractionMode(composerDraftTarget, mode); - if (isLocalDraftThread) { - setDraftThreadContext(composerDraftTarget, { interactionMode: mode }); - } - scheduleComposerFocus(); - }; - const handleInteractionModeChangeStable = useStableCallback(handleInteractionModeChange); - const toggleInteractionMode = () => { - if (!interactionModeEnabled) return; - handleInteractionModeChange(interactionMode === "plan" ? "default" : "plan"); - }; - const toggleInteractionModeStable = useStableCallback(toggleInteractionMode); - const openProviderSetup = (instanceId: ProviderInstanceId) => { - void navigate({ - to: "/settings/providers", - search: { environmentId, instanceId }, - }); - }; - const openProviderSetupStable = useStableCallback(openProviderSetup); const canOperatePreview = useEnvironmentScope( activeThreadRef?.environmentId ?? null, AuthPreviewOperateScope, ); - const createBrowserSurface = (profileId?: string) => { - if (!activeThreadRef || !canOperatePreview) return; - void addBrowserSurface({ - threadRef: activeThreadRef, - openPreview, - ...(profileId === undefined ? {} : { profileId }), - }).then((result) => { - if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return; - const error = squashAtomCommandFailure(result); - if (error instanceof BrowserSettingsReadError) { - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Unable to open browser", - description: error.message, - }), - ); - } - }); - }; - const createBrowserSurfaceStable = useStableCallback(createBrowserSurface); - const addDiffSurface = () => { - if (!activeThreadRef || !isServerThread || !isGitRepo) return; - useDiffPanelStore.getState().selectGitScope(activeThreadRef, "branch"); - useRightPanelStore.getState().open(activeThreadRef, "diff"); - onDiffPanelOpen?.(); - }; - const addDiffSurfaceStable = useStableCallback(addDiffSurface); - const openChangesFromThreadPanel = () => { - addDiffSurface(); - }; - const openChangesFromThreadPanelStable = useStableCallback(openChangesFromThreadPanel); - const addFilesSurface = () => { - if (!activeThreadRef || !activeProject) return; - useRightPanelStore.getState().open(activeThreadRef, "files"); - }; - const addFilesSurfaceStable = useStableCallback(addFilesSurface); const supportsThreadPullRequests = serverConfig?.environment.capabilities.threadPullRequests === true; const visiblePullRequests = visibleThreadPullRequests( @@ -2855,23 +1888,9 @@ export default function ChatView(props: ChatViewProps) { const visiblePullRequestCount = visiblePullRequests.length; const pullRequestsSurfaceAvailable = isServerThread && supportsThreadPullRequests && visiblePullRequestCount > 0; - const addPullRequestsSurface = () => { - if (!activeThreadRef || !pullRequestsSurfaceAvailable) return; - useRightPanelStore.getState().open(activeThreadRef, "pull-requests"); - }; - const addPullRequestsSurfaceStable = useStableCallback(addPullRequestsSurface); const { state: deviceState, loaded: deviceStateLoaded } = useDeviceState( activeThreadRef?.environmentId ?? null, ); - const addDeviceSurface = () => { - if (!activeThreadRef) return; - if (!deviceState.onboardingCompleted || deviceState.hostStatus === "disabled") { - openDeviceSetupDialog(scopedThreadKey(activeThreadRef)); - return; - } - useRightPanelStore.getState().open(activeThreadRef, "device"); - }; - const addDeviceSurfaceStable = useStableCallback(addDeviceSurface); useAgentOpenedPreviews({ threadRef: activeThreadRef, deviceState, @@ -2882,11 +1901,6 @@ export default function ChatView(props: ChatViewProps) { miniPlayerSource: activePreviewMiniPlayer?.source ?? null, sheetLayout: shouldUsePlanSidebarSheet, }); - const openFileSurface = (relativePath: string) => { - if (!activeThreadRef || !activeProject) return; - useRightPanelStore.getState().openFile(activeThreadRef, relativePath); - }; - const openFileSurfaceStable = useStableCallback(openFileSurface); // The thread's own change request, placed against the project it belongs to. Without a // project there is nothing to resolve it against, so the caller falls back to the browser. const activeProjectRepository = sourceControlRepositorySelector( @@ -2932,159 +1946,12 @@ export default function ChatView(props: ChatViewProps) { visiblePullRequestCount, onDiffPanelOpen, }); - const closePreviewPanel = () => { - if (activeThreadRef) { - if (activeRightPanelSurface?.kind === "preview" && activeRightPanelSurface.resourceId) { - usePreviewMiniPlayerStore - .getState() - .open(activeThreadRef, browserMiniPlayerSource(activeRightPanelSurface.resourceId)); - } else if (activeRightPanelSurface?.kind === "device" && activeRightPanelSurface.target) { - usePreviewMiniPlayerStore - .getState() - .open(activeThreadRef, { kind: "device", ...activeRightPanelSurface.target }); - } - useRightPanelStore.getState().setMaximized(activeThreadRef, false); - useRightPanelStore.getState().close(activeThreadRef); - } - }; - const closePreviewPanelStable = useStableCallback(closePreviewPanel); - const togglePreviewPanel = () => { - if (!activeThreadRef || !browserAvailable) return; - if (previewPanelOpen) { - closePreviewPanel(); - return; - } - if (!canOperatePreview) return; - const activeTabId = activePreviewState.activeTabId; - if (activeTabId) { - useRightPanelStore.getState().openBrowser(activeThreadRef, activeTabId); - } else { - createBrowserSurface(); - } - }; - const togglePreviewPanelStable = useStableCallback(togglePreviewPanel); - const addTerminalSurface = () => { - if (!activeThreadRef) return; - const launched = terminalActions.launchTerminal({ - place: (terminalId) => - useRightPanelStore.getState().openTerminal(activeThreadRef, terminalId), - }); - if (!launched) return; - setTerminalFocusRequestId((value) => value + 1); - void launched.result; - }; - const addTerminalSurfaceStable = useStableCallback(addTerminalSurface); - const splitPanelTerminal = (direction: "horizontal" | "vertical" = "horizontal") => { - if ( - !activeThreadRef || - activeRightPanelSurface?.kind !== "terminal" || - activeRightPanelSurface.terminalIds.length >= MAX_TERMINALS_PER_GROUP - ) { - return; - } - const surfaceId = activeRightPanelSurface.id; - const launched = terminalActions.launchTerminal({ - place: (terminalId) => - useRightPanelStore - .getState() - .splitTerminal(activeThreadRef, surfaceId, terminalId, direction), - }); - if (!launched) return; - setTerminalFocusRequestId((value) => value + 1); - void launched.result; - }; - const splitPanelTerminalStable = useStableCallback(splitPanelTerminal); - const splitPanelTerminalVertical = () => { - splitPanelTerminal("vertical"); - }; - const splitPanelTerminalVerticalStable = useStableCallback(splitPanelTerminalVertical); - const activatePanelTerminal = (terminalId: string) => { - if (!activeThreadRef || activeRightPanelSurface?.kind !== "terminal") return; - useRightPanelStore - .getState() - .activateTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId); - setTerminalFocusRequestId((value) => value + 1); - }; - const activatePanelTerminalStable = useStableCallback(activatePanelTerminal); - const closePanelTerminal = (terminalId: string) => { - if ( - !hasTerminalWriteAccess() || - !activeThreadRef || - activeRightPanelSurface?.kind !== "terminal" - ) - return; - terminalActions.closeTerminalSession(terminalId); - storeCloseTerminal(activeThreadRef, terminalId); - useRightPanelStore - .getState() - .closeTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId); - setTerminalFocusRequestId((value) => value + 1); - }; - const closePanelTerminalStable = useStableCallback(closePanelTerminal); - const requestCloseTerminal = (terminalId: string) => { - if (!hasTerminalWriteAccess()) return; - const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId); - void confirmTerminalClose([label]).then((confirmed) => { - if (confirmed && readEnvironmentScope(environmentId, AuthTerminalOperateScope)) { - closeTerminal(terminalId); - } - }); - }; - const requestCloseTerminalStable = useStableCallback(requestCloseTerminal); - const requestClosePanelTerminal = (terminalId: string) => { - if (!hasTerminalWriteAccess()) return; - const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId); - void confirmTerminalClose([label]).then((confirmed) => { - if (confirmed && readEnvironmentScope(environmentId, AuthTerminalOperateScope)) { - closePanelTerminal(terminalId); - } - }); - }; - const requestClosePanelTerminalStable = useStableCallback(requestClosePanelTerminal); - const activateRightPanelSurface = (surface: RightPanelSurface) => { - if (!activeThreadRef) return; - explicitDiffOpenRef.current = resolveExplicitDiffOpenOnActivate({ - surfaceKind: surface.kind, - diffOpen, - activeThreadRef, - }); - useRightPanelStore.getState().activateSurface(activeThreadRef, surface.id); - if (surface.kind === "preview" && surface.resourceId) { - setActivePreviewTab(activeThreadRef, surface.resourceId); - } - if (surface.kind === "terminal") { - setTerminalFocusRequestId((value) => value + 1); - } - if (surface.kind === "diff" && !diffOpen) { - onDiffPanelOpen?.(); - } - }; - const activateRightPanelSurfaceStable = useStableCallback(activateRightPanelSurface); - const toggleRightPanel = () => { - if (!activeThreadRef) return; - if (rightPanelOpen) { - closePreviewPanel(); - return; - } - useRightPanelStore.getState().toggleVisibility(activeThreadRef); - }; - const toggleRightPanelStable = useStableCallback(toggleRightPanel); - const toggleThreadPanel = () => { - if (!activeThreadRef) return; - useRightPanelStore.getState().toggleThreadPanel(activeThreadRef, threadPanelPresentation); - }; - const toggleThreadPanelStable = useStableCallback(toggleThreadPanel); useEffect(() => { if (!canMaximizeRightPanel) return; if (useRightPanelStore.getState().consumeMaximizeRequest(routeThreadRef)) { useRightPanelStore.getState().setMaximized(routeThreadRef, true); } }, [canMaximizeRightPanel, routeThreadRef]); - const toggleRightPanelMaximized = () => { - if (!canMaximizeRightPanel || !activeThreadRef) return; - useRightPanelStore.getState().setMaximized(activeThreadRef, !rightPanelMaximized); - }; - const toggleRightPanelMaximizedStable = useStableCallback(toggleRightPanelMaximized); const { closeSurface: closeRightPanelSurface, closeOtherSurfaces: closeOtherRightPanelSurfacesStable, @@ -3095,54 +1962,6 @@ export default function ChatView(props: ChatViewProps) { terminalLabelsById: activeTerminalLabelsById, }); const closeRightPanelSurfaceStable = closeRightPanelSurface; - const moveRightPanelSurface = (surfaceId: string, toIndex: number) => { - if (activeThreadRef) - useRightPanelStore.getState().moveSurface(activeThreadRef, surfaceId, toIndex); - }; - const moveRightPanelSurfaceStable = useStableCallback(moveRightPanelSurface); - const copyRightPanelFilePath = (relativePath: string) => { - if (typeof window === "undefined" || !navigator.clipboard?.writeText) { - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to copy path", - description: "Clipboard API unavailable.", - }), - ); - return; - } - - const clipboardPath = formatFilePathForClipboard( - relativePath, - resolvePathLinkTarget(relativePath, gitCwd ?? activeProjectCwd ?? ""), - ); - void navigator.clipboard.writeText(clipboardPath).then( - () => { - toastManager.add({ - type: "success", - title: "Path copied", - description: clipboardPath, - }); - }, - (error) => { - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to copy path", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - }, - ); - }; - const copyRightPanelFilePathStable = useStableCallback(copyRightPanelFilePath); - useEffect( - () => - subscribePreviewAction((action) => { - if (action === "toggle-panel") togglePreviewPanelStable(); - }), - [togglePreviewPanelStable], - ); const persistThreadSettingsForNextTurn = async (input: { threadId: ThreadId; createdAt: string; @@ -3552,7 +2371,6 @@ export default function ChatView(props: ChatViewProps) { }, ); }; - const copyActiveThreadReferenceStable = useStableCallback(copyActiveThreadReference); const pullRequestPanelTarget = activeThread ? threadPullRequestPanelTarget({ projectId: activeThread.projectId, @@ -3561,412 +2379,103 @@ export default function ChatView(props: ChatViewProps) { branchPullRequest: activeThreadShell?.branchPullRequest ?? activeThread.branchPullRequest, }) : null; - const addPullRequestSurface = () => { - if (!supportsPullRequests || activeThreadRef === null || pullRequestPanelTarget === null) - return; - useRightPanelStore.getState().openPullRequest(activeThreadRef, pullRequestPanelTarget); - }; - const addPullRequestSurfaceStable = useStableCallback(addPullRequestSurface); - const pullRequestSurfaceAvailable = supportsPullRequests && pullRequestPanelTarget !== null; - const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true; - const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true; - const supportsPinning = serverConfig?.environment.capabilities.threadPinning === true; - const activeThreadPinned = supportsPinning && activeThreadShell?.pinnedAt != null; - // The compiler caches render results on their inputs, so a clock read in render - // stays frozen until the shell changes. The clock is state: reset with the shell, - // and moved by the wake timer. - const [snoozeClockState, setSnoozeClockState] = useState(() => ({ - shell: activeThreadShell, - now: new Date().toISOString(), - })); - if (snoozeClockState.shell !== activeThreadShell) { - setSnoozeClockState({ shell: activeThreadShell, now: new Date().toISOString() }); - } - const snoozeClock = snoozeClockState.now; - const activeThreadSnoozed = - activeThreadShell !== null && - supportsSnooze && - effectiveSnoozed(activeThreadShell, { now: snoozeClock }); - useEffect(() => { - if (!activeThreadSnoozed) return; - const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? ""); - if (!Number.isFinite(wakeAtMs)) return; - const id = window.setTimeout( - () => setSnoozeClockState((clock) => ({ ...clock, now: new Date().toISOString() })), - Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647), - ); - return () => window.clearTimeout(id); - // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A clock that lands before the wake time (timer clamping, clock skew) re-arms the timer. - }, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeClock]); - const activeThreadWokeAt = - activeThreadShell !== null && supportsSnooze - ? threadWokeAt(activeThreadShell, { now: snoozeClock }) - : null; - const acknowledgeThreadWoke = useAcknowledgeThreadWoke(); - const acknowledgeActiveThreadWoke = () => { - if (activeThreadRef === null || activeThreadWokeAt === null) return; - acknowledgeThreadWoke(activeThreadRef, activeThreadWokeAt); - }; - const acknowledgeActiveThreadWokeStable = useStableCallback(acknowledgeActiveThreadWoke); - const activeThreadLocalVisitedAt = useUiStateStore((store) => - activeThreadKey === null ? undefined : store.threadLastVisitedAtById[activeThreadKey], - ); - const activeThreadLastVisitedAt = resolveThreadLastVisitedAt( - activeThreadShell?.lastVisitedAt, - activeThreadLocalVisitedAt, - ); - const activeThreadWokeVisible = isThreadWokeUnseen({ - wokeAt: activeThreadWokeAt, - settled: activeThreadShell?.settledOverride === "settled", - lastVisitedAt: activeThreadLastVisitedAt, - latestRunCompletedAt: activeLatestRun?.completedAt ?? null, - }); - const activeThreadSettled = - supportsSettlement && activeThreadShell?.settledOverride === "settled"; - const unsettleThreadMutation = useOrchestrationCommand(threadEnvironment.unsettle, { - reportFailure: false, - }); - const [unsettlingThreadKey, setUnsettlingThreadKey] = useState(null); - const isUnsettling = unsettlingThreadKey !== null && unsettlingThreadKey === activeThreadKey; - const handleUnsettleActiveThread = async () => { - if ( - !activeThreadRef || - !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope) - ) - return; - const threadKey = scopedThreadKey(activeThreadRef); - setUnsettlingThreadKey(threadKey); - // Commands settle into a result, so this always runs. - const result = await unsettleThreadMutation({ - environmentId: activeThreadRef.environmentId, - input: { threadId: activeThreadRef.threadId, reason: "user" }, - }); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to un-settle thread", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - setUnsettlingThreadKey((current) => (current === threadKey ? null : current)); - }; - const handleUnsettleActiveThreadStable = useStableCallback(handleUnsettleActiveThread); - const unsnoozeThreadMutation = useOrchestrationCommand(threadEnvironment.unsnooze, { - reportFailure: false, + const { + activateRightPanelSurfaceStable, + addDeviceSurfaceStable, + addDiffSurfaceStable, + addFilesSurfaceStable, + addPullRequestSurfaceStable, + addPullRequestsSurfaceStable, + closePreviewPanelStable, + copyRightPanelFilePathStable, + createBrowserSurface, + createBrowserSurfaceStable, + moveRightPanelSurfaceStable, + onOpenTurnDiffStable, + openChangesFromThreadPanelStable, + openFileSurfaceStable, + toggleRightPanelMaximizedStable, + toggleRightPanelStable, + toggleThreadPanelStable, + shortcuts: rightPanelShortcuts, + } = useRightPanelActions({ + activeThreadRef, + activeProject, + activeRightPanelSurface, + activePreviewState, + deviceState, + pullRequestPanelTarget, + threadPanelPresentation, + isServerThread, + isGitRepo, + browserAvailable, + canOperatePreview, + diffOpen, + previewPanelOpen, + rightPanelOpen, + canMaximizeRightPanel, + rightPanelMaximized, + supportsPullRequests, + pullRequestsSurfaceAvailable, + gitCwd, + activeProjectCwd, + explicitDiffOpenRef, + setTerminalFocusRequestId, + onDiffPanelOpen, + closeRightPanelSurface, }); - const [unsnoozingThreadKey, setUnsnoozingThreadKey] = useState(null); - const isUnsnoozing = unsnoozingThreadKey !== null && unsnoozingThreadKey === activeThreadKey; - const handleUnsnoozeActiveThread = async () => { - if ( - !activeThreadRef || - !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope) - ) - return; - const threadKey = scopedThreadKey(activeThreadRef); - setUnsnoozingThreadKey(threadKey); - // Commands settle into a result, so this always runs. - const recovery = activeThreadShell?.limitRecovery; - const recoveryOwnsSnooze = - recovery?.snooze === true && - recovery.runId === activeThreadShell?.latestRun?.runId && - activeThreadShell?.snoozedUntil != null && - Date.parse(activeThreadShell.snoozedUntil) === Date.parse(recovery.resetAt); - const result = recoveryOwnsSnooze - ? await updateThreadMetadata({ - environmentId: activeThreadRef.environmentId, - input: { - threadId: activeThreadRef.threadId, - limitRecovery: { runId: recovery.runId, resetAt: recovery.resetAt, snooze: false }, - }, - }) - : await unsnoozeThreadMutation({ - environmentId: activeThreadRef.environmentId, - input: { threadId: activeThreadRef.threadId, reason: "user" }, - }); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to wake thread", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - setUnsnoozingThreadKey((current) => (current === threadKey ? null : current)); - }; - const handleUnsnoozeActiveThreadStable = useStableCallback(handleUnsnoozeActiveThread); - const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false); - const [revealedBranchMismatchKey, setRevealedBranchMismatchKey] = useState(null); - const [, setBranchMismatchDismissTick] = useState(0); - const composerHasDraftContent = useComposerDraftStore((store) => - composerDraftHasUserContent(store.getComposerDraft(composerDraftTarget)), - ); + const pullRequestSurfaceAvailable = supportsPullRequests && pullRequestPanelTarget !== null; const nowMinute = useNowMinute(); - const activeBranchMismatchKey = branchMismatchKey( - activeThread?.id ?? null, + const { + acknowledgeActiveThreadWoke, + activeBranchMismatchKey, + backgroundWorkBanner, + childInputBanner, + goalBanner, + handleSwitchCheckoutToThread, + handleSwitchCheckoutToThreadStable, + isRestoringThreadBranch, + onOpenRelatedThread, + onOpenRelatedThreadStable, + sendStandaloneCommand, + setBranchMismatchDismissTick, + showBranchMismatchBanner, + threadStatusLine, + shortcuts: threadLifecycleShortcuts, + } = useThreadLifecycle({ + environmentId, + routeThreadKey, + currentRouteThreadKeyRef, + canOperateThread, + clientSettingsHydrated, + activeThread, + activeThreadId, + activeThreadRef, + activeThreadKey, + activeThreadShell, + activeLatestRun, + activeProjectCwd, + serverConfig, + runtimeMode, + isWorking, + pendingBackgroundTasks, + activePendingApproval, + activePendingUserInput, localCheckoutBranchMismatch, - ); - const showBranchMismatchBanner = shouldShowBranchMismatchBanner({ - hasMismatch: localCheckoutBranchMismatch !== null, - isDismissed: isBranchMismatchDismissedForSession(activeBranchMismatchKey), - composerHasContent: composerHasDraftContent, - wasShownForCurrentMismatch: - revealedBranchMismatchKey !== null && revealedBranchMismatchKey === activeBranchMismatchKey, - }); - const nextRevealedBranchMismatchKey = showBranchMismatchBanner - ? activeBranchMismatchKey - : revealedBranchMismatchKey !== activeBranchMismatchKey - ? null - : revealedBranchMismatchKey; - if (nextRevealedBranchMismatchKey !== revealedBranchMismatchKey) { - setRevealedBranchMismatchKey(nextRevealedBranchMismatchKey); - } - const handleSwitchCheckoutToThread = async () => { - if (!canWriteSourceControl) return; - if ( - !activeProjectCwd || - !activeThread || - !localCheckoutBranchMismatch || - isRestoringThreadBranch - ) { - return; - } - setIsRestoringThreadBranch(true); - const checkoutResult = await switchGitRef({ - environmentId, - input: { - cwd: activeProjectCwd, - refName: localCheckoutBranchMismatch.threadBranch, - }, - }); - if (checkoutResult._tag === "Failure") { - setIsRestoringThreadBranch(false); - if (!isAtomCommandInterrupted(checkoutResult)) { - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to switch checkout", - description: chatActionErrorMessage(squashAtomCommandFailure(checkoutResult)), - }), - ); - } - return; - } - - if (!readEnvironmentScope(environmentId, AuthSourceControlWriteScope)) { - setIsRestoringThreadBranch(false); - return; - } - const nextBranch = checkoutResult.value.refName ?? localCheckoutBranchMismatch.threadBranch; - if (nextBranch !== activeThread.branch) { - const updateResult = await updateThreadMetadata({ - environmentId, - input: { threadId: activeThread.id, branch: nextBranch, worktreePath: null }, - }); - if (updateResult._tag === "Failure") { - setIsRestoringThreadBranch(false); - if (!isAtomCommandInterrupted(updateResult)) { - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Checkout switched, but the thread could not be updated", - description: chatActionErrorMessage(squashAtomCommandFailure(updateResult)), - }), - ); - } - gitStatusQuery.refresh(); - return; - } - } - gitStatusQuery.refresh(); - setIsRestoringThreadBranch(false); - scheduleComposerFocus(); - }; - const handleSwitchCheckoutToThreadStable = useStableCallback(() => { - void handleSwitchCheckoutToThread(); - }); - // The interrupt path also accepts a completed run while its provider still - // has background work. - const activeBackgroundTasks = !isWorking && activeThread ? pendingBackgroundTasks : []; - const [stoppingBackgroundWorkKey, setStoppingBackgroundWorkKey] = useState(null); - const isStoppingBackgroundWork = - stoppingBackgroundWorkKey === `${environmentId}:${activeThreadId}`; - const handleStopBackgroundWork = async () => { - if (!activeThread || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) - return; - const requestKey = `${environmentId}:${activeThread.id}`; - setStoppingBackgroundWorkKey(requestKey); - const result = await interruptThreadTurn({ - environmentId, - input: { threadId: activeThread.id }, - }); - // Acceptance does not confirm termination. Allow retry while the provider - // finishes stopping the tasks or reports a failure. - setStoppingBackgroundWorkKey((current) => (current === requestKey ? null : current)); - if (result._tag === "Failure") { - if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - setThreadError( - activeThread.id, - error instanceof Error ? error.message : "Failed to stop background work.", - ); - } - } - }; - const handleStopBackgroundWorkStable = useStableCallback(handleStopBackgroundWork); - const openRelatedThreadGenerationRef = useRef(0); - const onOpenRelatedThread = async (threadId: ThreadId) => { - const generation = ++openRelatedThreadGenerationRef.current; - const threadRef = scopeThreadRef(environmentId, threadId); - const isEnvironmentLive = () => - appAtomRegistry.get(environmentShell.stateValueAtom(environmentId)).status === "live"; - // A just-launched child can reach this timeline before its shell syncs. - if (isEnvironmentLive() && readThreadShell(threadRef) === null) { - const location = router.latestLocation; - await waitForThreadShell(threadRef, RELATED_THREAD_SHELL_WAIT_MS); - if ( - generation !== openRelatedThreadGenerationRef.current || - currentRouteThreadKeyRef.current !== routeThreadKey || - router.latestLocation !== location - ) { - return; - } - } - const shell = readThreadShell(threadRef); - if (shell === null ? isEnvironmentLive() : shell.deletedAt != null) { - toastManager.add({ type: "info", title: "This thread is no longer available" }); - return; - } - void navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(threadRef), - }); - }; - const onOpenRelatedThreadStable = useStableCallback(onOpenRelatedThread); - const childThreadInputs = useChildThreadInputs(activeThreadRef); - const childInputBanner = childInputBannerItem({ - childThreadInputs, - parentAwaitingUser: Boolean( - activePendingApproval || activePendingUserInput || activeThreadShell?.hasPendingUserInput, - ), - onOpenThread: onOpenRelatedThreadStable, + gitStatusQuery, + nowMinute, + composerRef, + composerDraftTarget, + sendInFlightRef, + setOptimisticUserMessages, + setThreadError, + clearUsageLimitsFor, + beginLocalDispatch, + resetLocalDispatch, + scheduleComposerFocus, + scrollToEnd, + persistThreadSettingsForNextTurn, }); - - const sendStandaloneCommand = async (text: string, failureMessage: string) => { - if (!activeThread || !clientSettingsHydrated || sendInFlightRef.current) return; - const context = composerRef.current?.getSendContext(); - if (!context?.providerAvailable) return; - - const threadId = activeThread.id; - const messageId = newMessageId(); - const createdAt = new Date().toISOString(); - sendInFlightRef.current = true; - beginLocalDispatch(); - setThreadError(threadId, null); - setOptimisticUserMessages((messages) => [ - ...messages, - { - id: messageId, - role: "user", - text, - runId: null, - createdAt, - updatedAt: createdAt, - streaming: false, - }, - ]); - scrollToEnd(); - // Commands settle into a result, so this always runs. - const settingsResult = await persistThreadSettingsForNextTurn({ - threadId, - createdAt, - ...(localCheckoutBranchMismatch ? { branch: localCheckoutBranchMismatch.currentBranch } : {}), - runtimeMode, - interactionMode: context.interactionMode, - }); - const result = - settingsResult._tag === "Failure" - ? settingsResult - : await startThreadTurn({ - environmentId, - input: { - threadId, - message: { messageId, role: "user", text, attachments: [] }, - modelSelection: context.selectedModelSelection, - runtimeMode, - interactionMode: context.interactionMode, - createdAt, - }, - }); - if (result._tag === "Failure") { - setOptimisticUserMessages((messages) => - messages.filter((message) => message.id !== messageId), - ); - resetLocalDispatch(); - if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - setThreadError(threadId, error instanceof Error ? error.message : failureMessage); - } - } else { - clearUsageLimitsFor(routeThreadKey); - } - sendInFlightRef.current = false; - }; - const sendStandaloneCommandStable = useStableCallback(sendStandaloneCommand); - const activeGoal = activeThreadShell?.goal ?? null; - const goalBanner = - activeThread && activeGoal !== null - ? goalBannerItem({ - threadId: activeThread.id, - goal: activeGoal, - isWorking, - onSendCommand: sendStandaloneCommandStable, - }) - : null; - - const backgroundWorkBanner = activeThread - ? backgroundWorkBannerItem({ - threadId: activeThread.id, - tasks: activeBackgroundTasks, - stopDisabled: !canOperateThread || isStoppingBackgroundWork, - stopping: isStoppingBackgroundWork, - onStop: handleStopBackgroundWorkStable, - onOpenThread: onOpenRelatedThreadStable, - }) - : null; - // The relative times read the clock; nowMinute re-renders them on the minute. - const snoozedUntil = activeThreadShell?.snoozedUntil ?? null; - const settledAt = activeThreadShell?.settledAt ?? null; - const threadStatusLine = activeThreadSnoozed ? ( - } - label={snoozedUntil ? `Snoozed, ${formatRelativeTimeUntilLabel(snoozedUntil)}` : "Snoozed"} - clockMinute={nowMinute} - actionLabel={isUnsnoozing ? "Waking..." : "Wake now"} - actionDisabled={!canOperateThread || isUnsnoozing} - onAction={() => void handleUnsnoozeActiveThreadStable()} - /> - ) : activeThreadSettled ? ( - } - label={settledAt ? `Settled ${formatRelativeTimeLabel(settledAt)}` : "Settled"} - clockMinute={nowMinute} - actionLabel={isUnsettling ? "Un-settling..." : "Un-settle"} - actionDisabled={!canOperateThread || isUnsettling} - onAction={() => void handleUnsettleActiveThreadStable()} - /> - ) : activeThreadWokeVisible ? ( - } - label="Woke from snooze" - actionLabel="Dismiss" - onAction={acknowledgeActiveThreadWokeStable} - /> - ) : null; const activeThreadHasCompactableConversation = serverVisibleTurnItems.some( ({ item }) => item.type === "user_message" && @@ -4181,120 +2690,31 @@ export default function ChatView(props: ChatViewProps) { const threadFindControlsRef = useRef(null); const [isThreadFindActive, setIsThreadFindActive] = useState(false); const openThreadFind = () => threadFindControlsRef.current?.open(); - const openThreadFindStable = useStableCallback(openThreadFind); const closeThreadFind = () => threadFindControlsRef.current?.close(); - const closeThreadFindStable = useStableCallback(closeThreadFind); - const toastPinFailure = (title: string) => (result: AtomCommandResult) => { - if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return; - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title, - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - }; - const openTerminalIfClosed = () => { - if (!terminalUiState.terminalOpen) setTerminalOpenStable(true); - }; - const openComposerControl = (command: Parameters[0]) => - (({ event }) => { - if (!event.repeat) composerRef.current?.openControl(command); - }) satisfies ChatShortcutHandler; useChatShortcuts({ enabled: activeThreadId !== null, keybindings, scriptKeybindings, - getShortcutContext: getShortcutContextStable, + getShortcutContext, threadFindActive: isThreadFindActive, - typeIntoComposer: (key) => composerRef.current?.insertTextAtEnd(key) === true, + composerRef, + branchToolbarRef, closeThreadFind: () => { - closeThreadFindStable(); + closeThreadFind(); focusComposerStable(); }, commands: { + ...terminalShortcuts, + ...rightPanelShortcuts, + ...threadLifecycleShortcuts, "thread.copyReference": ({ event }) => { - if (!event.repeat) copyActiveThreadReferenceStable(); - }, - "thread.settle": () => { - if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false; - if (!isServerThread || !activeThreadRef || !supportsSettlement) return; - if (activeThreadSettled) { - void handleUnsettleActiveThreadStable(); - return; - } - if (settleAndAdvance(activeThreadRef)) return; - void settleThread(activeThreadRef).then(toastPinFailure("Failed to settle thread")); - }, - "thread.pin": () => { - if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false; - if (!isServerThread || !activeThreadRef || !supportsPinning) return; - void ( - activeThreadPinned ? confirmAndUnpinThread(activeThreadRef) : pinThread(activeThreadRef) - ).then( - toastPinFailure(activeThreadPinned ? "Failed to unpin thread" : "Failed to pin thread"), - ); - }, - "terminal.toggle": () => { - if (!terminalUiState.terminalOpen && !canReadTerminal && !canOperateTerminal) return false; - toggleTerminalVisibilityStable(); + if (!event.repeat) copyActiveThreadReference(); }, "chat.find": () => { if (!isServerThread || serverConfig?.threadFind !== true) return false; - openThreadFindStable(); - }, - "rightPanel.toggle": () => toggleRightPanelStable(), - "rightPanel.toggleMaximized": ({ event }) => { - if (!event.repeat) toggleRightPanelMaximizedStable(); - }, - "threadPanel.toggle": () => toggleThreadPanelStable(), - "rightPanel.close": ({ event }) => { - if (!activeRightPanelSurface) return false; - if (!event.repeat) closeRightPanelSurfaceStable(activeRightPanelSurface); - }, - "terminal.split": ({ terminalFocusOwner }) => { - if (!canOperateTerminal) return false; - if (terminalFocusOwner === "right-panel") return void splitPanelTerminalStable(); - openTerminalIfClosed(); - splitTerminalStable(); - }, - "terminal.splitVertical": ({ terminalFocusOwner }) => { - if (!canOperateTerminal) return false; - if (terminalFocusOwner === "right-panel") return void splitPanelTerminalStable("vertical"); - openTerminalIfClosed(); - splitTerminalStable("vertical"); - }, - "terminal.close": ({ terminalFocusOwner }) => { - if (!canOperateTerminal) return false; - if (terminalFocusOwner === "right-panel" && activeRightPanelSurface?.kind === "terminal") { - requestClosePanelTerminalStable(activeRightPanelSurface.activeTerminalId); - return; - } - if (terminalUiState.terminalOpen) - requestCloseTerminalStable(terminalUiState.activeTerminalId); - }, - "terminal.new": ({ terminalFocusOwner }) => { - if (!canOperateTerminal) return false; - if (terminalFocusOwner === "right-panel") return void addTerminalSurfaceStable(); - openTerminalIfClosed(); - createNewTerminalStable(); - }, - "diff.toggle": () => onToggleDiffStable(), - "modelPicker.toggle": ({ event }) => { - if (!event.repeat) composerRef.current?.toggleModelPicker(); + openThreadFind(); }, - "composer.increaseEffort": ({ event }) => { - if (!event.repeat) composerRef.current?.stepReasoningEffort(1); - }, - "composer.decreaseEffort": ({ event }) => { - if (!event.repeat) composerRef.current?.stepReasoningEffort(-1); - }, - "composer.host": openComposerControl("composer.host"), - "composer.effort": openComposerControl("composer.effort"), - "composer.mode": openComposerControl("composer.mode"), - "composer.workspace": openComposerControl("composer.workspace"), "composer.cycleHost": ({ event }) => { if (!canChangeEnvironment) return false; if (event.repeat) return; @@ -4305,12 +2725,6 @@ export default function ChatView(props: ChatViewProps) { const next = logicalProjectEnvironments[(index + 1) % logicalProjectEnvironments.length]; if (next) onEnvironmentChangeStable(next.environmentId); }, - "composer.branch": ({ event }) => { - if (!event.repeat) branchToolbarRef.current?.openBranchPicker(); - }, - "composer.previousWorktree": ({ event }) => { - if (!event.repeat) branchToolbarRef.current?.usePreviousWorktree(); - }, "thread.steerQueuedMessage": ({ event }) => routeKind !== "draft" && queuedRunsControlRef.current?.steerNext(event.repeat) === true, "thread.editQueuedMessage": ({ event }) => @@ -4338,1868 +2752,179 @@ export default function ChatView(props: ChatViewProps) { }); }, [toggleRightPanelStable, toggleRightPanelMaximizedStable]); - // Paste-to-focus: the resting composer blurs on a click into the timeline, - // so a paste that follows has no editable target and would be dropped. - useEffect(() => { - const keyHandler = (event: KeyboardEvent) => { - if ( - shouldRedirectInputToComposer(event) && - isPasteAsTextShortcut(event, isMacPlatform(navigator.platform)) - ) { - pasteAsTextShortcutUntilRef.current = Date.now() + 1_000; - } - }; - const handler = (event: ClipboardEvent) => { - if (!activeThreadId || isCommandPaletteOpen()) return; - if (getTerminalFocusOwner() !== null) return; - if (composerRef.current?.isModelPickerOpen()) return; - const text = pasteTextToFocusComposer(event); - const clipboardData = event.clipboardData; - if (text === null || clipboardData === null) return; - const bypassAutoAttachment = Date.now() <= pasteAsTextShortcutUntilRef.current; - pasteAsTextShortcutUntilRef.current = 0; - if ( - ((readPastedComposerContext(clipboardData)?.records.length ?? 0) === 0 && - composerRef.current?.pasteTextAtEnd(text, { bypassAutoAttachment })) || - composerRef.current?.insertTextAtEnd(text, { clipboardData }) - ) { - event.preventDefault(); - event.stopPropagation(); - } - }; - window.addEventListener("keydown", keyHandler, true); - window.addEventListener("paste", handler, true); - return () => { - window.removeEventListener("keydown", keyHandler, true); - window.removeEventListener("paste", handler, true); - }; - }, [activeThreadId, composerRef]); - - const onRevertToTurnCount = async ( - turnCount: number, - messageId: MessageId, - restoreFiles?: boolean, - ) => { - const localApi = readLocalApi(); - if ( - !localApi || - !activeThread || - isRevertingCheckpoint || - !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) - ) - return; - const message = timelineMessages.find((message) => message.id === messageId); - if (!message || message.role !== "user") return; - - if (!supportsConversationRollback) { - setThreadError( - activeThread.id, - "This provider does not support reverting conversation history. Start a new thread instead.", - ); - return; - } - if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) { - setThreadError( - activeThread.id, - `Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`, - ); - return; - } - if (phase === "running" || isSendBusy || isConnecting) { - setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints."); - return; - } - if (restoreFiles === undefined) { - openRevertConfirm(routeThreadKey, { turnCount, messageId }); - return; - } - - useComposerDraftStore.setState((store) => ({ - rewindingThreadKeys: new Set(store.rewindingThreadKeys).add(routeThreadKey), - })); - setThreadError(activeThread.id, null); - const rewind = await rewindToMessage({ - message, - environmentId, - routeThreadRef, - threadId: activeThread.id, - turnCount, - restoreFiles, - // Keep the live checkpoint identity when command context refetches a bounded window. - checkpoint: findRevertCheckpoint(serverProjection?.checkpoints ?? [], turnCount), - draftTarget: composerDraftTarget, - composerHasPendingAttachments: composerRef.current?.hasPendingAttachments() === true, - createAssetUrl: createAttachmentAssetUrl, - revertThreadCheckpoint, - }); - useComposerDraftStore.setState((store) => { - const remaining = new Set(store.rewindingThreadKeys); - remaining.delete(routeThreadKey); - return { rewindingThreadKeys: remaining }; - }); - if (rewind.error !== null) { - setThreadError(activeThread.id, rewind.error); - return; - } - if (currentRouteThreadKeyRef.current === routeThreadKey) { - const nextPrompt = rewind.prompt; - promptRef.current = nextPrompt; - composerRef.current?.resetCursorState({ prompt: nextPrompt, cursor: nextPrompt.length }); - requestAnimationFrame(() => { - if (currentRouteThreadKeyRef.current === routeThreadKey) composerRef.current?.focusAtEnd(); - }); - } - }; - const onRevertToTurnCountStable = useStableCallback(onRevertToTurnCount); - const onConfirmRevert = (turnCount: number, messageId: MessageId, restoreFiles: boolean) => { - void onRevertToTurnCount(turnCount, messageId, restoreFiles); - }; - const onConfirmRevertStable = useStableCallback(onConfirmRevert); - - const onRollbackCheckpoint = async (input: { - readonly checkpointId: string; - readonly scopeId: string; - }) => { - if (!activeThread || isRevertingCheckpoint) return; - if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) { - setThreadError( - activeThread.id, - `Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`, - ); - return; - } - if (phase === "running" || isSendBusy || isConnecting) { - setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints."); - return; - } - const localApi = readLocalApi(); - const confirmed = - localApi == null - ? window.confirm("Roll back this thread to the selected checkpoint?") - : await localApi.dialogs.confirm( - "Roll back this thread to the selected checkpoint?\nThis action cannot be undone.", - ); - if (!confirmed) return; - - useComposerDraftStore.setState((store) => ({ - rewindingThreadKeys: new Set(store.rewindingThreadKeys).add(routeThreadKey), - })); - setThreadError(activeThread.id, null); - const result = await revertThreadCheckpoint({ - environmentId, - input: { - threadId: activeThread.id, - checkpointId: input.checkpointId, - scopeId: input.scopeId, - }, - }); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - setThreadError( - activeThread.id, - error instanceof Error ? error.message : "Failed to revert thread state.", - ); - } - useComposerDraftStore.setState((store) => { - const remaining = new Set(store.rewindingThreadKeys); - remaining.delete(routeThreadKey); - return { rewindingThreadKeys: remaining }; - }); - }; - - const onForkFromRun = async (input: { - readonly sourceThreadId: ThreadId; - readonly runId: RunId; - }) => { - if (!activeThread || activeEnvironmentUnavailable) return; - const targetThreadId = newThreadId(); - const targetThreadRef = scopeThreadRef(environmentId, targetThreadId); - const result = await forkThreadFromRun({ - environmentId, - input: { - sourceThreadId: input.sourceThreadId, - targetThreadId, - runId: input.runId, - title: `${activeThread.title} fork`, - }, - }); - if (result._tag === "Failure") { - if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - setThreadError( - activeThread.id, - error instanceof Error ? error.message : "Failed to fork this response.", - ); - } - return; - } - const targetThreadReady = await waitForThreadShell(targetThreadRef); - if (!targetThreadReady) { - setThreadError( - activeThread.id, - "The fork was created, but its thread data did not reach this client. Reconnect and try opening it from the sidebar.", - ); - return; - } - await navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(targetThreadRef), - }); - }; - const onForkFromRunStable = useStableCallback(onForkFromRun); - const onCompactContext = () => { - if (compactDisabled) return; - void sendStandaloneCommand("/compact", "Failed to compact context."); - }; - - const onResume = async () => { - if ( - !activeThread || - (resumableRunId === null && !hasHeldQueuedRuns) || - isSendBusy || - isResuming || - isConnecting || - isRevertingCheckpoint || - threadDetailLoading || - activeEnvironmentUnavailable || - sendInFlightRef.current - ) { - return; - } - const threadId = activeThread.id; - sendInFlightRef.current = true; - setResumingThreadKeys((current) => new Set(current).add(routeThreadKey)); - setThreadError(threadId, null); - // Commands settle into a result, so this always runs. - const resume = async () => { - if (resumableRunId === null) { - return resumeThreadQueue({ environmentId, input: { threadId } }); - } - const createdAt = new Date().toISOString(); - const settingsResult = await persistThreadSettingsForNextTurn({ - threadId, - createdAt, - ...(localCheckoutBranchMismatch - ? { branch: localCheckoutBranchMismatch.currentBranch } - : {}), - runtimeMode, - interactionMode, - }); - if (settingsResult._tag === "Failure") return settingsResult; - const modelSelection = composerRef.current?.getSendContext().selectedModelSelection; - const turnResult = await startThreadTurn({ - environmentId, - input: { - threadId, - manualContinuationOfRunId: resumableRunId, - ...(modelSelection ? { modelSelection } : {}), - message: { - messageId: newMessageId(), - role: "user", - text: "Continue where you left off.", - attachments: [], - }, - runtimeMode, - interactionMode, - dispatchMode: "start", - }, - }); - if (turnResult._tag === "Failure" || !hasHeldQueuedRuns) return turnResult; - clearUsageLimitsFor(routeThreadKey); - return resumeThreadQueue({ environmentId, input: { threadId } }); - }; - const result = await resume(); - if (result._tag === "Failure") { - if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - setThreadError( - threadId, - error instanceof Error ? error.message : "Could not resume thread.", - ); - } - } else { - clearUsageLimitsFor(routeThreadKey); - if (currentRouteThreadKeyRef.current === routeThreadKey) scrollToEnd(); - } - sendInFlightRef.current = false; - setResumingThreadKeys((current) => { - const next = new Set(current); - next.delete(routeThreadKey); - return next; - }); - }; - - const onSend = async ( - e?: { preventDefault: () => void }, - dispatchMode: ComposerDispatchMode = "auto", - submissionIntent: ComposerSubmissionIntent = "foreground", - directAnnotation?: { - annotation: PreviewAnnotationPayload; - image: ComposerImageAttachment | null; - }, - ) => { - e?.preventDefault(); - // What the user pressed send on; uploads below can take a while, and a redirect must not - // decline approvals for a draft that changed meanwhile. - const promptAtSend = promptRef.current; - if ( - usageLimitsOffered && - usageLimitsKey !== null && - !directAnnotation && - !composerHasNonPromptContent && - isUsageLimitsCommand(promptRef.current) - ) { - if (openUsageLimits()) { - promptRef.current = ""; - setComposerDraftPrompt(composerDraftTarget, ""); - composerRef.current?.resetCursorState(); - } - return; - } - - const notifyDirectAnnotationAttached = () => { - if (!directAnnotation) return; - toastManager.add( - stackedThreadToast({ - type: "info", - title: "Annotation attached to draft", - description: "Sending is unavailable right now. Finish the current action, then send.", - }), - ); - }; - if ( - !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) || - !activeThread || - (isSendBusy && !sendQueuesBehindSetup) || - isConnecting || - isRevertingCheckpoint || - !clientSettingsHydrated || - threadDetailLoading || - readPendingEnvironmentChange() !== null || - sendInFlightRef.current || - feedbackUploadsInFlightRef.current.has(routeThreadKey) - ) { - notifyDirectAnnotationAttached(); - return; - } - if (needsLoadBalancing) { - toastManager.add({ - type: "warning", - title: loadBalancing.pending - ? "Checking machine resources" - : "Choose a machine to continue", - description: loadBalancing.pending - ? "Resource checks are still running. You can choose a machine in the composer." - : referencedThreadContexts.length > 0 && - !logicalProjectEnvironments.some((candidate) => - referencedThreadContexts.every( - (record) => record.environmentId === candidate.environmentId, - ), - ) - ? "No machine can read every attached thread. Choose a machine in the composer or remove the threads." - : "No eligible machine has available resources. Choose a machine in the composer to override.", - }); - return; - } - if (activeEnvironmentUnavailable) { - const toastSlot = environmentUnavailableSendToastSlotRef.current; - environmentUnavailableSendToastSlotRef.current = - (toastSlot + 1) % ENVIRONMENT_UNAVAILABLE_SEND_TOAST_TRAIL_SIZE; - toastManager.add({ - ...stackedThreadToast({ - type: "warning", - title: "Not connected: message not sent", - description: "Reconnecting to the environment. Try again once it is connected.", - }), - id: `chat-send-environment-unavailable:${toastSlot}`, - }); - return; - } - const sendCtx = composerRef.current?.getSendContext(); - if (activePendingProgress && sendCtx?.answeringPendingUserInput !== false) { - if (directAnnotation) { - notifyDirectAnnotationAttached(); - return; - } - onAdvanceActivePendingUserInput(); - return; - } - if (!sendCtx?.providerAvailable) { - notifyDirectAnnotationAttached(); - return; - } - const multipleModelSelections = sendCtx.multipleModelSelections; - if ( - multipleModelSelections !== null && - serverConfig?.environment.capabilities.requiredWorktreeBootstrap !== true - ) { - setThreadError(activeThread.id, "Update this server before starting multiple models."); - return; - } - if ( - multipleModelSelections !== null && - (!isLocalDraftThread || - !isGitRepo || - !activeThreadBranch || - multipleModelSelections.length === 0) - ) { - toastManager.add( - stackedThreadToast({ - type: "warning", - title: "Choose models and a base branch", - description: - "Multiple models need a new thread in a Git project. Each gets its own worktree.", - }), - ); - return; - } - const { - images: sendContextImages, - files: composerFiles, - terminalContexts: composerTerminalContexts, - previewAnnotations: sendContextPreviewAnnotations, - reviewComments: composerReviewComments, - threadContexts: composerThreadContexts, - selectedProvider: ctxSelectedProvider, - selectedModel: ctxSelectedModel, - selectedProviderModels: ctxSelectedProviderModels, - selectedPromptEffort: ctxSelectedPromptEffort, - selectedModelSelection: ctxSelectedModelSelection, - interactionMode: sendInteractionMode, - interactionModeEnabled: sendInteractionModeEnabled, - } = sendCtx; - const { images: composerImages, previewAnnotations: composerPreviewAnnotations } = - mergeDirectPreviewAnnotation({ - images: sendContextImages, - fileCount: composerFiles.length, - previewAnnotations: sendContextPreviewAnnotations, - direct: directAnnotation, - }); - // A direct "send annotation" writes the draft and sends in the same tick; the reference - // must be in the text now, not after the next render. - const promptForSend = directAnnotation - ? ensureInlineContextReferences(promptRef.current, [ - previewAnnotationContextReference(directAnnotation.annotation), - ]) - : promptRef.current; - const strandedThread = threadContextsOutsideEnvironment({ - text: promptForSend, - records: composerThreadContexts, - environmentId, - })[0]; - if (strandedThread) { - const owner = environmentById.get(strandedThread.environmentId)?.label ?? "its machine"; - toastManager.add( - stackedThreadToast({ - type: "warning", - title: "Attached thread is on another machine", - description: `This machine's agent can't read "${strandedThread.title}". Remove it, or switch back to ${owner} to send.`, - }), - ); - return; - } - if (queuedRunEdit.isEditing) { - // Edit mode repurposes the composer: sending saves the queued message - // in place instead of dispatching a new turn. - await queuedRunEdit.saveEdit( - { - prompt: promptForSend, - images: composerImages, - files: composerFiles, - terminalContexts: composerTerminalContexts, - reviewComments: composerReviewComments, - previewAnnotations: composerPreviewAnnotations, - threadContexts: composerThreadContexts, - }, - setThreadError, - ); - return; - } - const { - trimmedPrompt: trimmed, - sendableTerminalContexts: sendableComposerTerminalContexts, - expiredTerminalContextCount, - hasSendableContent, - } = deriveComposerSendState({ - prompt: promptForSend, - imageCount: composerImages.length + composerFiles.length, - terminalContexts: composerTerminalContexts, - elementContextCount: - composerPreviewAnnotations.length + - composerReviewComments.length + - composerThreadContexts.length, - }); - const feedbackCommand = - ctxSelectedProvider === "codex" && - composerImages.length === 0 && - composerFiles.length === 0 && - sendableComposerTerminalContexts.length === 0 && - composerPreviewAnnotations.length === 0 && - composerReviewComments.length === 0 && - composerThreadContexts.length === 0 - ? parseCodexFeedbackCommand(trimmed) - : null; - if (feedbackCommand && multipleModelSelections === null) { - if (!isServerThread || activeThread.activeProviderThreadId === null) { - toastManager.add( - stackedThreadToast({ - type: "warning", - title: "Start a Codex thread first", - description: "Send a message before you submit feedback.", - }), - ); - return; - } - feedbackUploadsInFlightRef.current.add(routeThreadKey); - await submitCodexFeedback({ - submission: { - id: newMessageId(), - command: trimmed, - createdAt: new Date().toISOString(), - }, - clearDraft: () => { - promptRef.current = ""; - clearComposerDraftContent(composerDraftTarget); - composerRef.current?.resetCursorState(); - }, - onUpdate: (submission) => { - setFeedbackSubmissionsByThreadKey((current) => { - const existing = current[routeThreadKey] ?? []; - const found = existing.some((entry) => entry.id === submission.id); - return { - ...current, - [routeThreadKey]: found - ? existing.map((entry) => (entry.id === submission.id ? submission : entry)) - : [...existing, submission], - }; - }); - }, - upload: () => - uploadThreadFeedback({ - environmentId: activeThread.environmentId, - input: { threadId: activeThread.id, ...feedbackCommand }, - }), - }).finally(() => { - feedbackUploadsInFlightRef.current.delete(routeThreadKey); - }); - - return; - } - if ( - !directAnnotation && - sendInteractionModeEnabled && - showPlanFollowUpPrompt && - activeProposedPlan && - composerImages.length === 0 && - composerFiles.length === 0 - ) { - const followUp = resolvePlanFollowUpSubmission({ - draftText: promptForSend, - planMarkdown: activeProposedPlan.planMarkdown, - }); - const outgoingFollowUpText = formatOutgoingPrompt({ - provider: ctxSelectedProvider, - model: ctxSelectedModel, - models: ctxSelectedProviderModels, - effort: ctxSelectedPromptEffort, - text: followUp.text.trim(), - }); - if (composerRef.current?.validateProviderInput(outgoingFollowUpText) === false) { - return; - } - const followUpPromptSnapshot = promptRef.current; - const followUpTerminalContexts = [...sendableComposerTerminalContexts]; - const followUpReviewComments = [...composerReviewComments]; - const followUpPreviewAnnotations = [...composerPreviewAnnotations]; - const followUpThreadContexts = [...composerThreadContexts]; - promptRef.current = ""; - clearComposerDraftContent(composerDraftTarget); - composerRef.current?.resetCursorState(); - const followUpSent = await onSubmitPlanFollowUp({ - text: followUp.text, - context: buildMessageContext({ - terminalContexts: sendableComposerTerminalContexts, - reviewComments: composerReviewComments, - previewAnnotations: composerPreviewAnnotations, - threadContexts: composerThreadContexts, - }), - interactionMode: followUp.interactionMode, - }); - if (!followUpSent) { - promptRef.current = followUpPromptSnapshot; - composerTerminalContextsRef.current = [...followUpTerminalContexts]; - restorePlanFollowUpComposer({ - snapshot: { - prompt: followUpPromptSnapshot, - terminalContexts: followUpTerminalContexts, - reviewComments: followUpReviewComments, - previewAnnotations: followUpPreviewAnnotations, - threadContexts: followUpThreadContexts, - }, - writePrompt: (prompt) => setComposerDraftPrompt(composerDraftTarget, prompt), - writeTerminalContexts: (contexts) => - setComposerDraftTerminalContexts(composerDraftTarget, [...contexts]), - writeReviewComments: (comments) => - setComposerDraftReviewComments(composerDraftTarget, [...comments]), - writePreviewAnnotations: (annotations) => - setComposerDraftPreviewAnnotations(composerDraftTarget, [...annotations]), - writeThreadContexts: (records) => - setComposerDraftThreadContexts(composerDraftTarget, [...records]), - resetCursor: (options) => composerRef.current?.resetCursorState(options), - }); - } else if ( - submissionIntent === "background" && - currentRouteThreadKeyRef.current === routeThreadKey - ) { - handleNewThreadInActiveProject(); - } - return; - } - const standaloneSlashCommand = - sendInteractionModeEnabled && - composerImages.length === 0 && - composerFiles.length === 0 && - sendableComposerTerminalContexts.length === 0 && - composerPreviewAnnotations.length === 0 && - composerReviewComments.length === 0 && - composerThreadContexts.length === 0 - ? parseStandaloneComposerSlashCommand(trimmed) - : null; - if (standaloneSlashCommand && multipleModelSelections === null) { - handleInteractionModeChange(standaloneSlashCommand); - promptRef.current = ""; - clearComposerDraftContent(composerDraftTarget); - composerRef.current?.resetCursorState(); - return; - } - if (!hasSendableContent) { - if (expiredTerminalContextCount > 0) { - const toastCopy = buildExpiredTerminalContextToastCopy( - expiredTerminalContextCount, - "empty", - ); - toastManager.add( - stackedThreadToast({ - type: "warning", - title: toastCopy.title, - description: toastCopy.description, - }), - ); - } - return; - } - if (!activeProject) { - toastManager.add( - stackedThreadToast({ - type: "warning", - title: "Choose a project first", - description: "This draft no longer points to an available project.", - }), - ); - return; - } - const threadIdForSend = activeThread.id; - const sendSnapshot = snapshotComposerSend({ - prompt: promptForSend, - images: composerImages, - files: composerFiles, - terminalContexts: composerTerminalContexts, - sendableTerminalContexts: sendableComposerTerminalContexts, - previewAnnotations: composerPreviewAnnotations, - reviewComments: composerReviewComments, - threadContexts: composerThreadContexts, - }); - const { - files: composerFilesSnapshot, - attachments: composerAttachmentsSnapshot, - terminalContexts: composerTerminalContextsSnapshot, - previewAnnotations: composerPreviewAnnotationsSnapshot, - reviewComments: composerReviewCommentsSnapshot, - threadContexts: composerThreadContextsSnapshot, - messageText: messageTextForSend, - } = sendSnapshot; - const { - missingWorktreeBaseBranch, - baseBranchForWorktree, - compactBeforeSend, - turnDispatchMode, - shouldQueueBehindActiveRun, - } = planComposerTurn({ - messageText: messageTextForSend, - sendQueuesBehindSetup, - isServerThread, - activeMessageCount, - sendEnvMode, - worktreePath: activeThread.worktreePath, - activeThreadBranch, - resumeCompactionTokens, - keepFullHistory, - phase, - dispatchMode, - }); - if (missingWorktreeBaseBranch) { - setThreadError(threadIdForSend, "Select a base branch before sending in New worktree mode."); - return; - } - // Records bind attachments by the id each side knows: the local id for the optimistic - // row, the upload id (or local id on the data-URL path) on the wire; the server - // rebinds them to the persisted id. - const buildOutgoingMessageContext = (attachmentIds: ReadonlyArray) => - buildMessageContext({ - terminalContexts: composerTerminalContextsSnapshot, - reviewComments: composerReviewCommentsSnapshot, - previewAnnotations: composerPreviewAnnotationsSnapshot, - threadContexts: composerThreadContextsSnapshot, - attachments: composerAttachmentsSnapshot.map((attachment, index) => ({ - attachment, - attachmentId: attachmentIds[index] ?? attachment.id, - })), - }); - const outgoingMessageContext = buildOutgoingMessageContext( - composerAttachmentsSnapshot.map((attachment) => attachment.id), - ); - const messageIdForSend = newMessageId(); - const messageCreatedAt = new Date().toISOString(); - const outgoingMessageText = formatOutgoingPrompt({ - provider: ctxSelectedProvider, - model: ctxSelectedModel, - models: ctxSelectedProviderModels, - effort: ctxSelectedPromptEffort, - text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, - }); - if (composerRef.current?.validateProviderInput(outgoingMessageText) === false) { - return; - } - - const readLiveAttachmentCapabilities = () => { - const config = appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null; - const liveSupportsAttachmentUploads = - config?.environment.capabilities.attachmentUploads === true; - return { - supportsAttachmentUploads: liveSupportsAttachmentUploads, - fileBlockReason: fileAttachmentCapabilityBlockReason({ - files: composerFilesSnapshot, - attachmentUploadsCapabilityKnown: config !== null, - supportsAttachmentUploads: liveSupportsAttachmentUploads, - maxFileAttachmentBytes: - config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null, - }), - }; - }; - - const multipleTargets: MultipleModelTarget[] = []; - for (const resolved of resolveMultipleModelTargets({ - selections: multipleModelSelections ?? [], - providerInstanceEntries, - messageText: messageTextForSend, - planModeEnabled: settings.planModeEnabled, - interactionMode: sendInteractionMode, - })) { - if ("error" in resolved) { - setThreadError(threadIdForSend, resolved.error); - return; - } - if (composerRef.current?.validateProviderInput(resolved.text) === false) return; - multipleTargets.push(resolved); - } - - sendInFlightRef.current = true; - const sendGeneration = ++composerSendGenerationRef.current; - const attachmentCapabilitiesBeforeUpload = readLiveAttachmentCapabilities(); - if (attachmentCapabilitiesBeforeUpload.fileBlockReason !== null) { - sendInFlightRef.current = false; - setThreadError(threadIdForSend, attachmentCapabilitiesBeforeUpload.fileBlockReason); - return; - } - const turnUsesAttachmentUploads = - composerFilesSnapshot.length > 0 - ? attachmentCapabilitiesBeforeUpload.supportsAttachmentUploads - : supportsAttachmentUploads; - if (turnUsesAttachmentUploads && composerAttachmentsSnapshot.length > 0) { - for (const attachment of composerAttachmentsSnapshot) { - const upload = - readAttachmentUpload(attachment.id)?.status === "failed" - ? retryAttachmentUpload - : startAttachmentUpload; - upload({ - environmentId, - image: attachment, - draftTarget: composerDraftTarget, - }); - } - await awaitAttachmentUploads(composerAttachmentsSnapshot.map((attachment) => attachment.id)); - const attachmentCapabilitiesAfterUpload = readLiveAttachmentCapabilities(); - if (attachmentCapabilitiesAfterUpload.fileBlockReason !== null) { - sendInFlightRef.current = false; - setThreadError(threadIdForSend, attachmentCapabilitiesAfterUpload.fileBlockReason); - return; - } - if (getUploadedAttachments({ environmentId, images: composerAttachmentsSnapshot }) === null) { - sendInFlightRef.current = false; - setThreadError(threadIdForSend, "Retry or remove failed uploads before sending."); - return; - } - } - - if ( - multipleModelSelections === null && - shouldDockDraftHeroForSubmission({ isDraftHeroState, activeThreadKey, submissionIntent }) && - activeThreadKey - ) { - let resolveDockStarted: (() => void) | undefined; - const dockStarted = new Promise((resolve) => { - resolveDockStarted = resolve; - }); - const dockTransition = runMobileComposerTransition( - () => { - flushSync(() => { - captureDraftHeroComposerRect(); - setDockedDraftHeroThreadKey(activeThreadKey); - }); - resolveDockStarted?.(); - }, - { - active: panelAnimationsActive, - durationMs: panelAnimationDurationMs, - }, - ); - void dockTransition.catch(() => resolveDockStarted?.()); - await dockStarted; - } - - const attachmentCapabilitiesBeforeDispatch = readLiveAttachmentCapabilities(); - if ( - !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) || - attachmentCapabilitiesBeforeDispatch.fileBlockReason !== null - ) { - sendInFlightRef.current = false; - setThreadError( - threadIdForSend, - attachmentCapabilitiesBeforeDispatch.fileBlockReason ?? - "This connection cannot change threads.", - ); - setDockedDraftHeroThreadKey((currentThreadKey) => - currentThreadKey === activeThreadKey ? null : currentThreadKey, - ); - return; - } - // A message sent while approvals are pending redirects the agent. They are declined only - // here, after everything above has accepted the send, so local commands and rejected - // drafts leave them alone. After navigating away during an upload, the shown approvals - // are another thread's, so this send leaves them alone too. - const approvalsToDecline = - currentRouteThreadKeyRef.current === routeThreadKey - ? pendingApprovalsRef.current.filter((approval) => - sendCtx?.shownPendingApprovalIds.includes(approval.requestId), - ) - : []; - if (approvalsToDecline.length > 0) { - // A draft edited since send, or a paste still landing in it, is no longer the message - // the user sent. - const attachmentIdsAtSend = composerAttachmentsSnapshot.map((attachment) => attachment.id); - // A direct annotation send writes its image and reference into the draft as it sends, - // so the live draft may still lack them; anything else differing is a real edit. - const annotationImageId = directAnnotation?.image?.id; - const attachmentIdsBeforeAnnotation = attachmentIdsAtSend.filter( - (id) => id !== annotationImageId, - ); - const sameIds = (left: ReadonlyArray, right: ReadonlyArray) => - left.length === right.length && left.every((id, index) => id === right[index]); - const draftChangedSinceSend = () => { - if (composerRef.current?.hasPendingAttachments() === true) return true; - const sendContext = composerRef.current?.getSendContext(); - const attachmentIds = sendContext - ? [...sendContext.images, ...sendContext.files].map((attachment) => attachment.id) - : attachmentIdsAtSend; - const promptUnchanged = - promptRef.current === promptAtSend || promptRef.current === promptForSend; - const attachmentsUnchanged = - sameIds(attachmentIds, attachmentIdsAtSend) || - (annotationImageId !== undefined && - sameIds(attachmentIds, attachmentIdsBeforeAnnotation)); - return !promptUnchanged || !attachmentsUnchanged; - }; - const draftBeforeDecline = useComposerDraftStore - .getState() - .getComposerDraft(composerDraftTarget); - const changedBeforeDecline = draftChangedSinceSend(); - const pendingIdsBeforeDecline = pendingApprovalsRef.current.map( - (approval) => approval.requestId, - ); - const approvalResponding = approvalsToDecline.some((approval) => - respondingRequestIdsRef.current.includes(approval.requestId), - ); - const declined = - !changedBeforeDecline && - !approvalResponding && - (await declinePendingApprovals(approvalsToDecline, onRespondToApprovalStable).catch( - () => false, - )); - const draftChanged = - changedBeforeDecline || - draftChangedSinceSend() || - useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) !== - draftBeforeDecline; - // An approval that arrived during the decline would block the redirect; keep the draft so - // the next send declines it too. - const approvalArrived = pendingApprovalsRef.current.some( - (approval) => !pendingIdsBeforeDecline.includes(approval.requestId), - ); - if ( - !declined || - draftChanged || - approvalArrived || - currentRouteThreadKeyRef.current !== routeThreadKey - ) { - sendInFlightRef.current = false; - setDockedDraftHeroThreadKey((currentThreadKey) => - currentThreadKey === activeThreadKey ? null : currentThreadKey, - ); - if (draftChanged || approvalResponding || (declined && approvalArrived)) { - toastManager.add({ - type: "info", - title: draftChanged - ? declined - ? "Approval declined. Your message changed, so it wasn't sent." - : "Your message changed, so it wasn't sent." - : approvalResponding - ? "An approval is already being answered, so your message wasn't sent." - : "Another approval arrived, so your message wasn't sent.", - description: "Send again when it's ready.", - }); - } - return; - } - } - if (sendQueuesBehindSetup) { - setSetupQueueSendThreadKey(activeThreadKey); - } else { - beginLocalDispatch({ - preparingWorktree: multipleModelSelections !== null || Boolean(baseBranchForWorktree), - submissionIntent: - submissionIntent === "background" && !isLocalDraftThread - ? "foreground" - : submissionIntent, - }); - beginWorktreeSetup( - multipleModelSelections === null && baseBranchForWorktree - ? { environmentId: activeThread.environmentId, threadId: threadIdForSend } - : null, - ); - } - - const turnAttachmentsPromise = Promise.all( - composerAttachmentsSnapshot.map(async (attachment) => { - if (turnUsesAttachmentUploads) { - const uploaded = getUploadedAttachments({ environmentId, images: [attachment] })?.[0]; - if (!uploaded) { - throw new Error(`Attachment '${attachment.name}' did not finish uploading.`); - } - return uploaded; - } - if (attachment.type !== "image") { - throw new Error("This server does not support file attachments."); - } - return { - type: "image" as const, - id: attachment.id, - name: attachment.name, - mimeType: attachment.mimeType, - sizeBytes: attachment.sizeBytes, - dataUrl: await readFileAsDataUrl(attachment.file), - ...(attachment.source ? { source: attachment.source } : {}), - }; - }), - ); - if (multipleModelSelections !== null) { - const failedSelections: ModelSelection[] = []; - let clearedDraft = false; - let releasedComposer = false; - let canRestoreDraft = () => false; - let startedCount = 0; - // Anything thrown here (an attachment the server can no longer take) - // fails every selection; the draft restore below still runs. - const sendResult = await settlePromise(async () => { - const attachments = await turnAttachmentsPromise; - const fileBlockReason = readLiveAttachmentCapabilities().fileBlockReason; - if (fileBlockReason !== null) throw new Error(fileBlockReason); - const context = buildOutgoingMessageContext( - boundAttachmentIds(attachments, composerAttachmentsSnapshot), - ); - const title = deriveThreadTitleSeed({ - text: messageTextForSend, - attachments: composerAttachmentsSnapshot, - }); - promptRef.current = ""; - clearComposerDraftContent(composerDraftTarget); - composerRef.current?.resetCursorState(); - clearedDraft = true; - const clearedDraftSnapshot = useComposerDraftStore - .getState() - .getComposerDraft(composerDraftTarget); - const submittedSelections = readMultipleModelSelections(); - canRestoreDraft = () => - currentRouteThreadKeyRef.current === routeThreadKey && - composerSendGenerationRef.current === sendGeneration && - useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) === - clearedDraftSnapshot && - readMultipleModelSelections() === submittedSelections; - setThreadError(threadIdForSend, null); - const starts = Promise.all( - multipleTargets.map(async (target) => { - const started = await startFanoutThread({ - retryKey: JSON.stringify([ - routeThreadKey, - target.selection.instanceId, - target.selection.model, - ]), - model: target.selection.model, - uncertainSubmissions: uncertainMultipleSubmissionsRef.current, - start: (targetThreadId) => { - const supportsInlineMessageContext = - appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment - .capabilities.inlineMessageContext === true; - return startThreadTurn({ - environmentId, - input: { - threadId: targetThreadId, - message: { - messageId: newMessageId(), - role: "user", - attachments, - ...withMessageContext({ - text: target.text, - context, - supportsInlineMessageContext, - }), - }, - modelSelection: target.selection, - titleSeed: title, - runtimeMode, - interactionMode: target.interactionMode, - bootstrap: { - createThread: { - projectId: activeProject.id, - title, - modelSelection: target.selection, - runtimeMode, - interactionMode: target.interactionMode, - branch: activeThreadBranch, - worktreePath: null, - createdAt: messageCreatedAt, - }, - prepareWorktree: { - projectCwd: activeProject.workspaceRoot, - baseBranch: activeThreadBranch!, - requireWorktree: true, - ...(startFromOrigin ? { startFromOrigin: true } : {}), - }, - runSetupScript: true, - }, - createdAt: messageCreatedAt, - }, - }); - }, - openThread: (threadId) => - void navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(scopeThreadRef(environmentId, threadId)), - }), - }); - if (started) startedCount += 1; - else failedSelections.push(target.selection); - }), - ); - sendInFlightRef.current = false; - resetLocalDispatch(); - releasedComposer = true; - await starts; - if (startedCount > 0) { - toastManager.add( - stackedThreadToast({ - type: "success", - title: `Started ${startedCount} ${startedCount === 1 ? "thread" : "threads"} in background`, - }), - ); - } - if (failedSelections.length === 0 && turnUsesAttachmentUploads) { - releaseDraftAttachments(composerAttachmentsSnapshot); - } - }); - if (sendResult._tag === "Failure") { - const error = squashAtomCommandFailure(sendResult); - failedSelections.push(...multipleModelSelections); - setThreadError( - threadIdForSend, - error instanceof Error ? error.message : "Failed to send messages.", - ); - } - const restoreFailedDraft = () => { - setMultipleModelSelections(failedSelections); - if (clearedDraft) { - restoreComposerDraft(composerDraftTarget, sendSnapshot); - if (composerRef.current && currentRouteThreadKeyRef.current === routeThreadKey) { - promptRef.current = messageTextForSend; - composerRef.current.resetCursorState({ - cursor: collapseExpandedComposerCursor(messageTextForSend, messageTextForSend.length), - prompt: messageTextForSend, - detectTrigger: true, - }); - } - } - }; - if (failedSelections.length > 0) { - if (canRestoreDraft() && composerRef.current) { - restoreFailedDraft(); - } else if (clearedDraft) { - const recoveryToastId = toastManager.add( - stackedThreadToast({ - type: "error", - title: "A background prompt could not be sent", - description: - "Your newer draft is unchanged. Restore the failed prompt when this composer is empty.", - timeout: 0, - actionProps: { - children: "Restore prompt", - onClick: () => { - if ( - !draftId || - !useComposerDraftStore.getState().getDraftSession(draftId) || - sendInFlightRef.current || - composerDraftHasUserContent( - useComposerDraftStore.getState().getComposerDraft(composerDraftTarget), - ) - ) { - toastManager.update(recoveryToastId, { - description: - "Return to the original draft and send or clear its current prompt before restoring.", - }); - return; - } - restoreFailedDraft(); - void navigate({ to: "/draft/$draftId", params: { draftId } }); - toastManager.close(recoveryToastId); - }, - }, - }), - ); - } - } - if (!releasedComposer) { - sendInFlightRef.current = false; - resetLocalDispatch(); - } - return; - } - const optimisticAttachments = optimisticMessageAttachments(composerAttachmentsSnapshot); - if (!shouldQueueBehindActiveRun) { - anchorNewTurn( - scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)), - messageIdForSend, - ); - } - setOptimisticUserMessages((existing) => [ - ...existing, - { - id: messageIdForSend, - role: "user", - text: outgoingMessageText, - ...(optimisticAttachments.length > 0 ? { attachments: optimisticAttachments } : {}), - ...(outgoingMessageContext !== undefined ? { context: outgoingMessageContext } : {}), - runId: null, - createdAt: messageCreatedAt, - updatedAt: messageCreatedAt, - streaming: false, - ...(shouldQueueBehindActiveRun - ? { inputIntent: "queued_turn" as const } - : phase === "running" && dispatchMode === "steer" - ? { inputIntent: "steer" as const } - : {}), - }, - ]); - setThreadError(threadIdForSend, null); - if (expiredTerminalContextCount > 0) { - const toastCopy = buildExpiredTerminalContextToastCopy( - expiredTerminalContextCount, - "omitted", - ); - toastManager.add( - stackedThreadToast({ - type: "warning", - title: toastCopy.title, - description: toastCopy.description, - }), - ); - } - const sentDraftThreadRef = isLocalDraftThread - ? scopeThreadRef(environmentId, threadIdForSend) - : null; - // Keep new-thread flows from reusing this draft while attachments and worktree setup settle. - if (sentDraftThreadRef) markPromotedDraftThreadByRef(sentDraftThreadRef); - promptRef.current = ""; - clearComposerDraftContent(composerDraftTarget); - composerRef.current?.resetCursorState(); - - const title = deriveThreadTitleSeed({ - text: messageTextForSend, - attachments: composerAttachmentsSnapshot, - fallbackLabels: sendTitleFallbackLabels(sendSnapshot), - }); - const threadCreateModelSelection = createModelSelection( - ctxSelectedModelSelection.instanceId, - ctxSelectedModel || activeProjectDefaultModelSelection?.model || DEFAULT_MODEL, - ctxSelectedModelSelection.options, - ); - - let failure: AtomCommandResult | null = null; - - if (failure === null && isServerThread) { - const settingsResult = await persistThreadSettingsForNextTurn({ - threadId: threadIdForSend, - createdAt: messageCreatedAt, - ...(localCheckoutBranchMismatch - ? { branch: localCheckoutBranchMismatch.currentBranch } - : {}), - runtimeMode, - interactionMode: sendInteractionMode, - }); - if (settingsResult._tag === "Failure") { - failure = settingsResult; - } - } - - const turnAttachmentsResult = await settlePromise(async () => { - const turnAttachments = await turnAttachmentsPromise; - const liveFileBlockReason = readLiveAttachmentCapabilities().fileBlockReason; - if (liveFileBlockReason !== null) { - throw new Error(liveFileBlockReason); - } - return turnAttachments; - }); - if (failure === null && turnAttachmentsResult._tag === "Failure") { - failure = turnAttachmentsResult; - } - - if (failure === null && compactBeforeSend) { - const compactResult = await startThreadTurn({ - environmentId, - input: { - threadId: threadIdForSend, - message: { messageId: newMessageId(), role: "user", text: "/compact", attachments: [] }, - modelSelection: ctxSelectedModelSelection, - runtimeMode, - interactionMode: sendInteractionMode, - }, - }); - if (compactResult._tag === "Failure") { - failure = compactResult; - } - } - - let backgroundDraftOpened = false; - let turnStartSucceeded = false; - if (failure === null && turnAttachmentsResult._tag === "Success") { - const bootstrap = - isLocalDraftThread || baseBranchForWorktree - ? { - ...(isLocalDraftThread - ? { - createThread: { - projectId: activeProject.id, - title, - modelSelection: threadCreateModelSelection, - runtimeMode, - interactionMode: sendInteractionMode, - branch: activeThreadBranch, - worktreePath: activeThread.worktreePath, - createdAt: activeThread.createdAt, - }, - } - : {}), - ...(baseBranchForWorktree - ? { - prepareWorktree: { - projectCwd: activeProject.workspaceRoot, - baseBranch: baseBranchForWorktree, - ...(startFromOrigin ? { startFromOrigin: true } : {}), - }, - runSetupScript: true, - } - : {}), - } - : undefined; - const backgroundThreadRef = - submissionIntent === "background" && isLocalDraftThread - ? scopeThreadRef(environmentId, threadIdForSend) - : null; - if (backgroundThreadRef) beginBackgroundDraftSubmissionByRef(backgroundThreadRef); - const startPromise = startThreadTurn({ - environmentId, - input: { - threadId: threadIdForSend, - message: { - messageId: messageIdForSend, - role: "user", - attachments: turnAttachmentsResult.value, - ...withMessageContext({ - text: outgoingMessageText, - context: buildOutgoingMessageContext( - boundAttachmentIds(turnAttachmentsResult.value, composerAttachmentsSnapshot), - ), - // Read at dispatch time: the upload and persistence awaits above can - // span a server reconnect that changes it. - supportsInlineMessageContext: - appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment - .capabilities.inlineMessageContext === true, - }), - }, - modelSelection: ctxSelectedModelSelection, - titleSeed: title, - runtimeMode, - interactionMode: sendInteractionMode, - dispatchMode: turnDispatchMode, - ...(bootstrap ? { bootstrap } : {}), - createdAt: messageCreatedAt, - }, - }); - if (backgroundThreadRef) { - try { - backgroundDraftOpened = Boolean( - await handleNewThread( - scopeProjectRef(activeProject.environmentId, activeProject.id), - resolveBackgroundDraftWorkspaceOptions({ - envMode: sendEnvMode, - branch: activeThreadBranch, - startFromOrigin, - }), - ), - ); - } catch (error) { - clearBackgroundDraftSubmissionByRef(backgroundThreadRef); - toastManager.add( - stackedThreadToast({ - type: "warning", - title: "Could not open a fresh composer", - description: error instanceof Error ? error.message : undefined, - }), - ); - } - } - const startResult = await startPromise; - if (startResult._tag === "Failure") { - failure = startResult; - } else { - turnStartSucceeded = true; - setKeepFullHistory(routeThreadKey, false); - clearUsageLimitsFor(routeThreadKey); - if (turnUsesAttachmentUploads) { - releaseDraftAttachments(composerAttachmentsSnapshot); - } - acknowledgeActiveThreadWoke(); - // A draft still on screen finalizes once its thread route takes over. - if (sentDraftThreadRef) { - if (backgroundDraftOpened || currentRouteThreadKeyRef.current !== routeThreadKey) { - finalizePromotedDraftThreadByRef(sentDraftThreadRef); - } else { - clearBackgroundDraftSubmissionByRef(sentDraftThreadRef); - } - } - if (backgroundThreadRef) { - if (backgroundDraftOpened) { - toastManager.add( - stackedThreadToast({ - type: "success", - title: "Started in background", - timeout: 5_000, - actionProps: { - children: "Open", - onClick: () => { - void navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(backgroundThreadRef), - }); - }, - }, - }), - ); - } - } else if ( - submissionIntent === "background" && - currentRouteThreadKeyRef.current === routeThreadKey - ) { - handleNewThreadInActiveProject(); - } - } - } - - if (failure !== null) { - if (isLocalDraftThread && draftId && draftThread) { - restoreFailedDraftThread( - draftId, - draftThread, - wasBootstrapThreadDeleted(squashAtomCommandFailure(failure)) - ? newThreadId() - : threadIdForSend, - ); - clearBackgroundDraftSubmissionByRef(scopeThreadRef(environmentId, threadIdForSend)); - } - if ( - !composerDraftHasUserContent( - useComposerDraftStore.getState().getComposerDraft(composerDraftTarget), - ) - ) { - setOptimisticUserMessages((existing) => { - const removed = existing.filter((message) => message.id === messageIdForSend); - for (const message of removed) { - revokeUserMessagePreviewUrls(message); - } - const next = existing.filter((message) => message.id !== messageIdForSend); - return next.length === existing.length ? existing : next; - }); - const retryComposerImages = restoreComposerDraft(composerDraftTarget, sendSnapshot); - if (currentRouteThreadKeyRef.current === routeThreadKey) { - promptRef.current = messageTextForSend; - composerImagesRef.current = retryComposerImages; - composerFilesRef.current = composerFilesSnapshot; - composerTerminalContextsRef.current = composerTerminalContextsSnapshot; - composerRef.current?.resetCursorState({ - cursor: collapseExpandedComposerCursor(messageTextForSend, messageTextForSend.length), - prompt: messageTextForSend, - detectTrigger: true, - }); - } - } - if (!isAtomCommandInterrupted(failure)) { - const error = squashAtomCommandFailure(failure); - setThreadError( - threadIdForSend, - error instanceof Error ? error.message : "Failed to send message.", - ); - if ( - draftId && - (backgroundDraftOpened || currentRouteThreadKeyRef.current !== routeThreadKey) - ) { - toastManager.add( - stackedThreadToast({ - type: "error", - title: - submissionIntent === "background" - ? "Background task failed" - : "Could not start thread", - description: error instanceof Error ? error.message : "Failed to send message.", - actionProps: { - children: "Open draft", - onClick: () => { - void navigate({ to: "/draft/$draftId", params: { draftId } }); - }, - }, - }), - ); - } - } - } - sendInFlightRef.current = false; - setSetupQueueSendThreadKey((current) => (current === activeThreadKey ? null : current)); - if (!turnStartSucceeded) { - setDockedDraftHeroThreadKey((currentThreadKey) => - currentThreadKey === activeThreadKey ? null : currentThreadKey, - ); - if (!sendQueuesBehindSetup) resetLocalDispatch(); - } + usePasteToFocusComposer(activeThreadId, composerRef); + const { + onConfirmRevertStable, + onForkFromRunStable, + onRevertTimelineTurnStable, + onTimelineRollbackCheckpointStable, + } = useTimelineRewind({ + environmentId, + routeThreadRef, + routeThreadKey, + currentRouteThreadKeyRef, + serverProjection, + activeThread, + timelineMessages, + paintOnlyDisplayedTimeline, + phase, + isConnecting, + isSendBusy, + isRevertingCheckpoint, + supportsConversationRollback, + activeEnvironmentUnavailable, + activeEnvironmentUnavailableLabel, + promptRef, + composerRef, + composerDraftTarget, + setThreadError, + }); + const onCompactContext = () => { + if (compactDisabled) return; + void sendStandaloneCommand("/compact", "Failed to compact context."); }; - async function onSubmitPlanFollowUp({ - text, - context, - interactionMode: nextInteractionMode, - }: { - text: string; - context?: ReturnType; - interactionMode: "default" | "plan"; - }) { - if ( - !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) || - !activeThread || - !isServerThread || - isSendBusy || - isConnecting || - sendInFlightRef.current - ) { - return false; - } - - const trimmed = text.trim(); - if (!trimmed) { - return false; - } - - const sendCtx = composerRef.current?.getSendContext(); - if (!sendCtx?.providerAvailable || !sendCtx.interactionModeEnabled) { - return false; - } - const { - selectedProvider: ctxSelectedProvider, - selectedModel: ctxSelectedModel, - selectedProviderModels: ctxSelectedProviderModels, - selectedPromptEffort: ctxSelectedPromptEffort, - selectedModelSelection: ctxSelectedModelSelection, - } = sendCtx; - - const threadIdForSend = activeThread.id; - const messageIdForSend = newMessageId(); - const messageCreatedAt = new Date().toISOString(); - const outgoingMessageText = formatOutgoingPrompt({ - provider: ctxSelectedProvider, - model: ctxSelectedModel, - models: ctxSelectedProviderModels, - effort: ctxSelectedPromptEffort, - text: trimmed, - }); - - sendInFlightRef.current = true; - beginLocalDispatch({ preparingWorktree: false }); - setThreadError(threadIdForSend, null); - - anchorNewTurn( - scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)), - messageIdForSend, - ); - - setOptimisticUserMessages((existing) => [ - ...existing, - { - id: messageIdForSend, - role: "user", - text: outgoingMessageText, - ...(context ? { context } : {}), - runId: null, - createdAt: messageCreatedAt, - updatedAt: messageCreatedAt, - streaming: false, - }, - ]); - - const settingsResult = await persistThreadSettingsForNextTurn({ - threadId: threadIdForSend, - createdAt: messageCreatedAt, - ...(localCheckoutBranchMismatch ? { branch: localCheckoutBranchMismatch.currentBranch } : {}), - runtimeMode, - interactionMode: nextInteractionMode, - }); - let failure: AtomCommandResult | null = - settingsResult._tag === "Failure" ? settingsResult : null; - - if (failure === null) { - setComposerDraftInteractionMode( - scopeThreadRef(activeThread.environmentId, threadIdForSend), - nextInteractionMode, - ); - - const startResult = await startThreadTurn({ - environmentId, - input: { - threadId: threadIdForSend, - message: { - messageId: messageIdForSend, - role: "user", - text: outgoingMessageText, - ...(context ? { context } : {}), - attachments: [], - }, - modelSelection: ctxSelectedModelSelection, - titleSeed: activeThread.title, - runtimeMode, - interactionMode: nextInteractionMode, - ...(nextInteractionMode === "default" && activeProposedPlan - ? { - sourceProposedPlan: { - threadId: activeThread.id, - planId: activeProposedPlan.id, - }, - } - : {}), - createdAt: messageCreatedAt, - }, - }); - failure = startResult._tag === "Failure" ? startResult : null; - } - - if (failure === null) { - sendInFlightRef.current = false; - resetLocalDispatch(); - return true; - } - - setOptimisticUserMessages((existing) => - existing.filter((message) => message.id !== messageIdForSend), - ); - if (!isAtomCommandInterrupted(failure)) { - const error = squashAtomCommandFailure(failure); - setThreadError( - threadIdForSend, - error instanceof Error ? error.message : "Failed to send plan follow-up.", - ); - } - sendInFlightRef.current = false; - resetLocalDispatch(); - return false; - } - - const onImplementPlanInNewThread = async () => { - if ( - !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) || - !activeThread || - !activeProject || - !activeProposedPlan || - !isServerThread || - isSendBusy || - isConnecting || - activeEnvironmentUnavailable || - sendInFlightRef.current - ) { - return; - } - - const sendCtx = composerRef.current?.getSendContext(); - if (!sendCtx?.providerAvailable || !sendCtx.interactionModeEnabled) { - return; - } - const { - selectedProvider: ctxSelectedProvider, - selectedModel: ctxSelectedModel, - selectedProviderModels: ctxSelectedProviderModels, - selectedPromptEffort: ctxSelectedPromptEffort, - selectedModelSelection: ctxSelectedModelSelection, - } = sendCtx; - - const createdAt = new Date().toISOString(); - const nextThreadId = newThreadId(); - const planMarkdown = activeProposedPlan.planMarkdown; - const implementationPrompt = buildPlanImplementationPrompt(planMarkdown); - const outgoingImplementationPrompt = formatOutgoingPrompt({ - provider: ctxSelectedProvider, - model: ctxSelectedModel, - models: ctxSelectedProviderModels, - effort: ctxSelectedPromptEffort, - text: implementationPrompt, - }); - const nextThreadTitle = truncate(buildPlanImplementationThreadTitle(planMarkdown)); - const nextThreadModelSelection: ModelSelection = ctxSelectedModelSelection; - - sendInFlightRef.current = true; - beginLocalDispatch({ preparingWorktree: false }); - const finish = () => { - sendInFlightRef.current = false; - resetLocalDispatch(); - }; - - const createResult = await createThread({ - environmentId, - input: { - threadId: nextThreadId, - projectId: activeProject.id, - title: nextThreadTitle, - modelSelection: nextThreadModelSelection, - runtimeMode: defaultRuntimeMode, - interactionMode: "default", - branch: activeThreadBranch, - worktreePath: activeThread.worktreePath, - createdAt, - }, - }); - let failure: AtomCommandResult | null = - createResult._tag === "Failure" ? createResult : null; - - if (failure === null) { - const startResult = await startThreadTurn({ - environmentId, - input: { - threadId: nextThreadId, - message: { - messageId: newMessageId(), - role: "user", - text: outgoingImplementationPrompt, - attachments: [], - }, - modelSelection: ctxSelectedModelSelection, - titleSeed: nextThreadTitle, - runtimeMode: defaultRuntimeMode, - interactionMode: "default", - sourceProposedPlan: { - threadId: activeThread.id, - planId: activeProposedPlan.id, - }, - createdAt, - }, - }); - failure = startResult._tag === "Failure" ? startResult : null; - } - - if (failure === null) { - const startedResult = await settlePromise(() => - waitForStartedServerThread(scopeThreadRef(activeThread.environmentId, nextThreadId)), - ); - failure = startedResult._tag === "Failure" ? startedResult : null; - } - - if (failure === null) { - const navigateResult = await settlePromise(() => - navigate({ - to: "/$environmentId/$threadId", - params: { - environmentId: activeThread.environmentId, - threadId: nextThreadId, - }, - }), - ); - failure = navigateResult._tag === "Failure" ? navigateResult : null; - } - - if (failure !== null) { - const cleanupResult = await deleteThread({ - environmentId, - input: { - threadId: nextThreadId, - }, - }); - if (cleanupResult._tag === "Failure" && !isAtomCommandInterrupted(cleanupResult)) { - console.warn( - "Failed to clean up implementation thread after start failure.", - squashAtomCommandFailure(cleanupResult), - ); - } - if (!isAtomCommandInterrupted(failure)) { - const error = squashAtomCommandFailure(failure); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Could not start implementation thread", - description: - error instanceof Error - ? error.message - : "An error occurred while creating the new thread.", - }), - ); - } - } - finish(); - }; + const { + getModelDisabledReason, + handleInteractionModeChange, + handleInteractionModeChangeStable, + handleRuntimeModeChangeStable, + onEnvModeChangeStable, + onProviderModelSelectStable, + onStartFromOriginChange, + openProviderSetupStable, + toggleInteractionModeStable, + } = useComposerSelection({ + environmentId, + composerDraftTarget, + draftThread, + activeThread, + activeRuntime, + activeProjectSettings, + settings, + providerStatuses, + lockedProvider, + supportsProviderSwitchingViaHandoff, + multipleModelSelections, + runtimeMode, + interactionMode, + interactionModeEnabled, + isLocalDraftThread, + canOverrideServerThreadEnvMode, + setPendingServerThreadEnvModeEntry, + setPendingServerThreadStartFromOriginByThreadId, + scheduleComposerFocus, + }); + const { onResume, isResuming } = useComposerResume({ + environmentId, + routeThreadKey, + currentRouteThreadKeyRef, + activeThread, + resumableRunId, + hasHeldQueuedRuns, + isSendBusy, + isConnecting, + isRevertingCheckpoint, + threadDetailLoading, + activeEnvironmentUnavailable, + runtimeMode, + interactionMode, + localCheckoutBranchMismatch, + composerRef, + persistThreadSettingsForNextTurn, + clearUsageLimitsFor, + scrollToEnd, + setThreadError, + }); + const onImplementPlanInNewThread = useImplementPlanInNewThread({ + environmentId, + routeThreadKey, + activeThread, + activeThreadBranch, + activeProposedPlan, + isServerThread, + isSendBusy, + isConnecting, + composerRef, + beginLocalDispatch, + resetLocalDispatch, + activeProject, + activeEnvironmentUnavailable, + defaultRuntimeMode, + }); + const { onSend } = useComposerSend({ + environmentId, + routeThreadKey, + currentRouteThreadKeyRef, + draftId, + draftThread, + activeThread, + activeThreadKey, + activeThreadBranch, + activeProject, + activeProjectDefaultModelSelection, + activeProposedPlan, + activeMessageCount, + isServerThread, + isLocalDraftThread, + isGitRepo, + phase, + runtimeMode, + sendEnvMode, + startFromOrigin, + localCheckoutBranchMismatch, + logicalProjectEnvironments, + providerInstanceEntries, + composerRef, + composerDraftTarget, + promptRef, + composerImagesRef, + composerFilesRef, + composerTerminalContextsRef, + feedbackUploadsInFlightRef, + queuedRunEdit, + isConnecting, + isRevertingCheckpoint, + threadDetailLoading, + activeEnvironmentUnavailable, + isSendBusy, + sendQueuesBehindSetup, + isDraftHeroState, + panelAnimationsActive, + panelAnimationDurationMs, + keepFullHistory, + resumeCompactionTokens, + showPlanFollowUpPrompt, + usageLimitsKey, + usageLimitsOffered, + openUsageLimits, + clearUsageLimitsFor, + needsLoadBalancing, + loadBalancing, + readPendingEnvironmentChange, + pendingApprovals, + respondingRequestIds, + activePendingProgress, + onAdvanceActivePendingUserInput, + onRespondToApproval: onRespondToApprovalStable, + beginLocalDispatch, + resetLocalDispatch, + beginWorktreeSetup, + captureDraftHeroComposerRect, + setDockedDraftHeroThreadKey, + setSetupQueueSendThreadKey, + setOptimisticUserMessages, + setFeedbackSubmissionsByThreadKey, + setThreadError, + setKeepFullHistory, + anchorNewTurn, + acknowledgeActiveThreadWoke, + handleInteractionModeChange, + handleNewThreadInActiveProject, + persistThreadSettingsForNextTurn, + }); const onImplementPlanInNewThreadStable = useStableCallback(onImplementPlanInNewThread); - // Keyed on the fields it reads: the thread and runtime objects change with - // every streamed event, and a new function re-renders the whole model picker. - const hasStartedSession = activeRuntime !== null; - const runtimeProviderInstanceId = activeRuntime?.providerInstanceId ?? null; - const currentModelSelection = activeThread?.modelSelection ?? null; - const getModelDisabledReason = makeModelDisabledReason( - currentModelSelection - ? { - providers: providerStatuses, - hasStartedSession, - supportsProviderSwitchingViaHandoff, - currentModelSelection, - currentProviderInstanceId: runtimeProviderInstanceId, - } - : null, - ); - - const onProviderModelSelect = ( - instanceId: ProviderInstanceId, - model: string, - options?: { focusComposer?: boolean }, - ) => { - if (!activeThread) return; - const entry = providerStatuses.find((snapshot) => snapshot.instanceId === instanceId); - const resolvedDriverKind = entry?.driver ?? null; - if ( - !supportsProviderSwitchingViaHandoff && - lockedProvider !== null && - resolvedDriverKind !== null && - resolvedDriverKind !== lockedProvider - ) { - if (options?.focusComposer !== false) scheduleComposerFocus(); - return; - } - if ( - !supportsProviderSwitchingViaHandoff && - lockedProvider !== null && - activeRuntime?.providerInstanceId - ) { - const currentEntry = providerStatuses.find( - (snapshot) => snapshot.instanceId === activeRuntime.providerInstanceId, - ); - if ( - currentEntry?.continuation?.groupKey && - entry?.continuation?.groupKey && - currentEntry.continuation.groupKey !== entry.continuation.groupKey - ) { - if (options?.focusComposer !== false) scheduleComposerFocus(); - return; - } - } - const resolvedModel = resolveAppModelSelectionForInstance( - instanceId, - settings, - providerStatuses, - model, - ); - if (!resolvedModel) { - if (options?.focusComposer !== false) scheduleComposerFocus(); - return; - } - const rememberedOptions = - useComposerDraftStore.getState().stickyOptionsByModelByProvider[instanceId]?.[resolvedModel]; - const nextModelSelection: ModelSelection = - rememberedOptions !== undefined && rememberedOptions.length > 0 - ? { instanceId, model: resolvedModel, options: [...rememberedOptions] } - : { instanceId, model: resolvedModel }; - const modelChangeBlockReason = getStartedThreadModelChangeBlockReason({ - providers: providerStatuses, - hasStartedSession: activeRuntime !== null, - supportsProviderSwitchingViaHandoff, - currentModelSelection: activeThread.modelSelection, - currentProviderInstanceId: activeRuntime?.providerInstanceId ?? null, - nextModelSelection, - }); - if (modelChangeBlockReason) { - toastManager.add({ - type: "warning", - title: modelChangeBlockReason.title, - description: modelChangeBlockReason.description, - }); - if (options?.focusComposer !== false) scheduleComposerFocus(); - return; - } - setComposerDraftModelSelection( - scopeThreadRef(activeThread.environmentId, activeThread.id), - nextModelSelection, - { explicit: true, replaceOptions: true }, - ); - setStickyComposerModelSelection(nextModelSelection); - if (options?.focusComposer !== false) scheduleComposerFocus(); - }; - const onProviderModelSelectStable = useStableCallback(onProviderModelSelect); - const onEnvModeChange = (mode: DraftThreadEnvMode) => { - if (multipleModelSelections !== null) return; - if (canOverrideServerThreadEnvMode) { - if (activeThread) setPendingServerThreadEnvModeEntry({ threadId: activeThread.id, mode }); - scheduleComposerFocus(); - return; - } - if (isLocalDraftThread) { - setDraftThreadContext(composerDraftTarget, { - envMode: mode, - startFromOrigin: resolveNewDraftStartFromOrigin({ - envMode: mode, - newWorktreesStartFromOrigin: activeProjectSettings.settings.newWorktreesStartFromOrigin, - }), - ...(mode === "worktree" && draftThread?.worktreePath ? { worktreePath: null } : {}), - }); - } - scheduleComposerFocus(); - }; - const onEnvModeChangeStable = useStableCallback(onEnvModeChange); - const onWorktreeSetupWorkLocally = () => { if (!worktreeSetup || worktreeSetup.phase !== "running" || !draftId) { return; @@ -6280,47 +3005,10 @@ export default function ChatView(props: ChatViewProps) { workLocallyResendReady, ]); - const onStartFromOriginChange = (nextStartFromOrigin: boolean) => { - if (canOverrideServerThreadEnvMode && activeThread) { - setPendingServerThreadStartFromOriginByThreadId((current) => - current[activeThread.id] === nextStartFromOrigin - ? current - : { ...current, [activeThread.id]: nextStartFromOrigin }, - ); - return; - } - if (isLocalDraftThread) { - setDraftThreadContext(composerDraftTarget, { - startFromOrigin: nextStartFromOrigin, - }); - } - }; - const onExpandTimelineImage = (preview: ExpandedImagePreview) => { openExpandedImagePreview(routeThreadKey, preview); }; const onExpandTimelineImageStable = useStableCallback(onExpandTimelineImage); - const onOpenTurnDiff = (runId: RunId, filePath?: string) => { - if (!isServerThread || !activeThreadRef) return; - const diffOpen = - selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, activeThreadRef) === "diff"; - explicitDiffOpenRef.current = diffOpen ? null : activeThreadRef; - useDiffPanelStore.getState().selectTurn(activeThreadRef, runId, filePath); - useRightPanelStore.getState().open(activeThreadRef, "diff"); - onDiffPanelOpen?.(); - }; - const onOpenTurnDiffStable = useStableCallback(onOpenTurnDiff); - const onTimelineRollbackCheckpoint = (input: { - readonly checkpointId: string; - readonly scopeId: string; - }) => { - if (!paintOnlyDisplayedTimeline) void onRollbackCheckpoint(input); - }; - const onTimelineRollbackCheckpointStable = useStableCallback(onTimelineRollbackCheckpoint); - const onRevertTimelineTurn = (targetTurnCount: number, messageId: MessageId) => { - void onRevertToTurnCountStable(targetTurnCount, messageId); - }; - const onRevertTimelineTurnStable = useStableCallback(onRevertTimelineTurn); const pendingSidebarFileDrops = useSidebarPendingFileDropStore((state) => state.pending); const consumePendingFileDrop = useSidebarPendingFileDropStore( @@ -6440,46 +3128,17 @@ export default function ChatView(props: ChatViewProps) { showThreadPanelControl={!inlineRightPanelOwnsTitleBar} /> ); - const threadPanelHeaderControl = ( -
- -
- ); + const threadPanelHeaderControl = ; const panelLayoutControls = ( -
- {!shouldUsePlanSidebarSheet ? ( - - - - ) : null} -
{panelToggleControls}
-
+ {panelToggleControls} + ); const workspaceFileDropHandlers = makeWorkspaceFileDropHandlers({ setDragActive: setIsWorkspaceFileDragActive, @@ -6567,40 +3226,23 @@ export default function ChatView(props: ChatViewProps) { onDrop={workspaceFileDropHandlers.onDrop} > - {isWorkspaceFileDragActive ? ( -
-
-
-
- ) : null} -
- setDismissedProviderStatusBannerKey(providerStatusBannerKey)} - onOpenProviderSetup={openProviderSetupStable} - /> - { - setThreadError(activeThread.id, null); - dismissThreadErrorBannerForSession(threadErrorBannerKey); - setThreadErrorBannerDismissTick((tick) => tick + 1); - }} - /> -
+ {isWorkspaceFileDragActive ? : null} +
{showScrollToBottom && !isThreadFindActive && ( -
- -
+ { + composerRef.current?.restoreAfterTimelineReachedEnd(); + scrollToEnd(true); + }} + /> )}
diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 5ee7676de3324..0d2b480e89c99 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -237,6 +237,7 @@ const EMPTY_BROWSE_ENTRIES: FilesystemBrowseResult["entries"] = []; export function CommandPalette({ children }: { children: ReactNode }) { const navigate = useNavigate(); + const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" }); const [state, dispatch] = useReducer(reduceCommandPaletteUiState, { open: false, mode: "command", @@ -287,6 +288,7 @@ export function CommandPalette({ children }: { children: ReactNode }) { previewFocus: isPreviewFocused(), previewOpen, modelPickerOpen: composerHandleRef.current?.isModelPickerOpen() ?? false, + usagePageOpen, }, }); if (command === "appearance.cycle") { @@ -352,6 +354,7 @@ export function CommandPalette({ children }: { children: ReactNode }) { theme, themeHalves, toggleMode, + usagePageOpen, ]); useEffect( diff --git a/apps/web/src/components/UsageToggleShortcut.browser.test.tsx b/apps/web/src/components/UsageToggleShortcut.browser.test.tsx new file mode 100644 index 0000000000000..1efaa2837b008 --- /dev/null +++ b/apps/web/src/components/UsageToggleShortcut.browser.test.tsx @@ -0,0 +1,52 @@ +import { compileResolvedKeybindingsConfig } from "@t3tools/shared/keybindings"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; + +import { render } from "../../test/render"; + +const state = vi.hoisted(() => ({ navigate: vi.fn() })); + +// One key toggles Usage: it opens Usage elsewhere and goes back from it. +const keybindings = compileResolvedKeybindingsConfig([ + { key: "mod+u", command: "navigation.back", when: "usagePageOpen" }, + { key: "mod+u", command: "usage.open", when: "!usagePageOpen" }, +]); + +vi.mock(import("@effect/atom-react"), async (original) => ({ + ...(await original()), + useAtomValue: (() => keybindings) as never, +})); +vi.mock(import("@tanstack/react-router"), async (original) => ({ + ...(await original()), + useNavigate: (() => state.navigate) as never, +})); + +import { NavigationHistoryShortcuts } from "./AppSidebarLayout"; +import { CommandPalette } from "./CommandPalette"; + +// regression: #21357 +describe("usage toggle shortcut on Usage", () => { + it("goes back", async () => { + vi.clearAllMocks(); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); + await using _screen = await render(, { router: "/usage" }); + + using back = vi.spyOn(window.history, "back").mockImplementation(() => undefined); + await userEvent.keyboard("{Control>}u{/Control}"); + + expect(back).toHaveBeenCalledOnce(); + }); + + // Both listeners sit on window, so the palette must not claim the key whatever their order. + it("does not reopen Usage from the command palette", async () => { + vi.clearAllMocks(); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); + await using _screen = await render({null}, { + router: "/usage", + }); + + await userEvent.keyboard("{Control>}u{/Control}"); + + expect(state.navigate).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx b/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx index 8dc91214b50a0..deee8d7afa69d 100644 --- a/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx +++ b/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx @@ -6,8 +6,10 @@ import { } from "@t3tools/contracts"; import { useState, type ReactNode } from "react"; import { describe, expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection"; +import "~/index.css"; import { act, render } from "../../../test/render"; const mocks = vi.hoisted(() => ({ observeSource: vi.fn(), dispose: vi.fn() })); @@ -125,3 +127,51 @@ describe("citation comment source disappearance", () => { expect(textarea()).toBeNull(); }); }); + +describe("citation comment popup position", () => { + it("stays on screen when the cited text ends in a code block's hidden overflow", async () => { + using _source = setup(); + const message = document.createElement("div"); + message.className = "chat-markdown"; + message.style.width = "240px"; + const pre = document.createElement("pre"); + const code = document.createElement("code"); + // Highlighted code is split into token spans, so the range's last client rect + // covers only the final token, wholly inside the hidden overflow. + for (let index = 0; index < 40; index += 1) { + const token = document.createElement("span"); + token.textContent = `token${index} `; + code.append(token); + } + pre.append(code); + message.append(pre); + document.body.prepend(message); + using _message = { [Symbol.dispose]: () => message.remove() }; + const range = document.createRange(); + range.selectNodeContents(code); + const rects = range.getClientRects(); + expect(rects.item(rects.length - 1)!.left).toBeGreaterThan(window.innerWidth); + const sourceAnchor = { + source: message, + range, + viewport: document.body, + } as AssistantCitationSourceAnchor; + + await using _screen = await mount( + sourceAnchor, + vi.fn(() => true), + ); + const popup = () => document.querySelector('[data-slot="popover-popup"]'); + await vi.waitFor(() => expect(popup()?.getBoundingClientRect().width).toBeGreaterThan(0)); + // Typing scrolls ancestors to reveal the caret, which shifts the whole app + // sideways when the box is off screen. + await userEvent.keyboard("note"); + + expect(textarea()?.value).toBe("note"); + expect(document.scrollingElement?.scrollLeft).toBe(0); + expect(document.body.scrollLeft).toBe(0); + const rect = popup()!.getBoundingClientRect(); + expect(rect.left).toBeGreaterThanOrEqual(0); + expect(rect.right).toBeLessThanOrEqual(window.innerWidth); + }); +}); diff --git a/apps/web/src/components/chat/AssistantCitationChip.tsx b/apps/web/src/components/chat/AssistantCitationChip.tsx index 741880d411614..dd21f7c466844 100644 --- a/apps/web/src/components/chat/AssistantCitationChip.tsx +++ b/apps/web/src/components/chat/AssistantCitationChip.tsx @@ -94,7 +94,15 @@ export function AssistantCitationChip({ contextElement: activeSourceAnchor.source, getBoundingClientRect: () => { const rects = activeSourceAnchor.range.getClientRects(); - return rects.item(rects.length - 1) ?? activeSourceAnchor.range.getBoundingClientRect(); + const rect = + rects.item(rects.length - 1) ?? activeSourceAnchor.range.getBoundingClientRect(); + // Code blocks and tables scroll sideways inside the message, so the cited + // text can end in their hidden overflow. Base UI only shifts the popup while + // it still touches the anchor, so clamp the anchor to the message's width. + const bounds = activeSourceAnchor.source.getBoundingClientRect(); + const left = Math.min(Math.max(rect.left, bounds.left), bounds.right); + const right = Math.max(Math.min(rect.right, bounds.right), left); + return new DOMRect(left, rect.top, right - left, rect.height); }, } : undefined; diff --git a/apps/web/src/components/chat/ChatBannerLane.tsx b/apps/web/src/components/chat/ChatBannerLane.tsx new file mode 100644 index 0000000000000..e0af10ea449eb --- /dev/null +++ b/apps/web/src/components/chat/ChatBannerLane.tsx @@ -0,0 +1,57 @@ +import type { + OrchestrationV2ProviderFailureClass, + ProviderInstanceId, + ServerProvider, + ThreadId, +} from "@t3tools/contracts"; +import type { Dispatch, SetStateAction } from "react"; +import { ProviderStatusBanner } from "./ProviderStatusBanner"; +import { dismissThreadErrorBannerForSession, ThreadErrorBanner } from "./ThreadErrorBanner"; + +/** + * The banners pinned above the timeline. The dismiss handlers are built here from plain + * values, so a ChatView render that changes neither banner leaves both cached. + */ +export function ChatBannerLane(props: { + providerStatus: ServerProvider | null; + providerStatusBannerKey: string | null; + setDismissedProviderStatusBannerKey: Dispatch>; + onOpenProviderSetup: (instanceId: ProviderInstanceId) => void; + threadId: ThreadId; + threadError: string | null; + threadErrorClass: OrchestrationV2ProviderFailureClass | null; + threadErrorBannerKey: string | null; + setThreadError: (threadId: ThreadId | null, error: string | null) => void; + setThreadErrorBannerDismissTick: Dispatch>; +}) { + const { + providerStatus, + providerStatusBannerKey, + setDismissedProviderStatusBannerKey, + onOpenProviderSetup, + threadId, + threadError, + threadErrorClass, + threadErrorBannerKey, + setThreadError, + setThreadErrorBannerDismissTick, + } = props; + return ( +
+ setDismissedProviderStatusBannerKey(providerStatusBannerKey)} + onOpenProviderSetup={onOpenProviderSetup} + /> + { + setThreadError(threadId, null); + dismissThreadErrorBannerForSession(threadErrorBannerKey); + setThreadErrorBannerDismissTick((tick) => tick + 1); + }} + /> +
+ ); +} diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 106d84fd1257a..b74e691ddd139 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -6,13 +6,10 @@ import { isLocalEnvironmentDisabled } from "../../localEnvironment"; import { usePrimaryEnvironmentId } from "../../state/environments"; import { useRightPanelStore } from "~/rightPanelStore"; import { importPastedComposerText, readPastedComposerContext } from "../composerInlineTokenPaste"; -import { elementContextToPreviewAnnotation } from "../../lib/elementContext"; import { questionAttachmentDraftId, - countQuestionAttachments, trackOpenQuestionAttachmentDraft, useQuestionAttachmentPreparation, - changeQuestionAttachmentPreparation, } from "../../questionAttachments"; import type { KeybindingCommand, @@ -39,19 +36,11 @@ import { ProviderDriverKind, ProviderInstanceId, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, - PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, - PROVIDER_SEND_TURN_MAX_INPUT_CHARS, - PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS, } from "@t3tools/contracts"; import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection"; import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import * as Schema from "effect/Schema"; -import { - isPasteAsTextShortcut, - nextPastedTextFileName, - pastedTextDisposition, - wouldTextPasteExceedLimit, -} from "@t3tools/client-runtime/text-paste"; +import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste"; import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger"; import { folderDropTarget, resolveDroppedFolderPath } from "./folderDrop"; import { splitTransferredFiles } from "./workspaceFileDrop"; @@ -67,7 +56,6 @@ import { useLayoutEffect, useRef, useState, - useSyncExternalStore, } from "react"; import { createPortal, flushSync } from "react-dom"; import { @@ -76,22 +64,20 @@ import { type ComposerSubmissionIntent, collapseExpandedComposerCursor, composerRequiresModifier, - composerSubmissionIntentForKey, composerStateAtPromptEnd, detectComposerTrigger, expandCollapsedComposerCursor, formatAssistantCitationForComposer, isPathSuggestionCurrent, + extendReplacementRangeForTrailingSpace, replaceTextRange, } from "../../composer-logic"; import { DISCONNECTED_COMPOSER_PLACEHOLDER } from "../../composerPlaceholder"; -import { listContinuationForEnter, listIndentForTab } from "../../composer-list-continuation"; import { deriveComposerSendState, getAntigravitySendBlockReason, readFileAsDataUrl, resolveComposerInteractionMode, - resolveComposerProviderSelection, threadShellHasStarted, } from "../ChatView.logic"; import { @@ -106,25 +92,13 @@ import { type ComposerFileAttachment, type ComposerImageAttachment, type DraftId, - type PersistedComposerFileAttachment, type PersistedComposerImageAttachment, - composerFileDedupKey, - composerFileMatchesReattachMarker, composerFileNeedsReattach, composerDraftHasUserContent, composerTargetKey, - hydrateImagesFromPersisted, useComposerDraftStore, useComposerThreadDraft, - deriveEffectiveComposerModelState, - useComposerDraftModelState, } from "../../composerDraftStore"; -import { - MAX_STASH_ENTRIES, - partitionStashAttachments, - usePromptStashStore, - type PromptStashEntry, -} from "../../promptStashStore"; import { ComposerStashBadge } from "./ComposerStashBadge"; import { ComposerStashMenu } from "./ComposerStashMenu"; import { useComposerTriggerState } from "./useComposerTriggerState"; @@ -151,51 +125,33 @@ import { type ComposerBannerStackContent, type ComposerBannerStackItem, } from "./ComposerBannerStack"; -import { compressImageForStash, prepareImageForAttachment } from "../../lib/imageCompression"; -import { - fileAttachmentTooLargeMessage, - formatAttachmentSize, -} from "@t3tools/client-runtime/state/attachments"; import { attachmentsToReleaseOnUploadCapabilityLoss, composerOtherFilesForPresentation, - classifyComposerAttachmentFile, fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, isPreviewableComposerVideo, - normalizeComposerImageFileMimeType, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; import { - readAttachmentUpload, releaseAttachmentUpload, releaseDraftAttachment, - releasePersistedAttachmentUpload, startAttachmentUpload, useAttachmentUploadStore, - verifyStashedAttachmentUpload, } from "../../lib/attachmentUploadQueue"; import { attachmentUploadBlockReason } from "../../lib/attachmentUploadState"; -import { isCommandPaletteOpen } from "../../commandPaletteBus"; -import { getTerminalFocusOwner } from "../../lib/terminalFocus"; import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection"; -import { resolveShortcutCommand, shortcutLabelForCommand } from "../../keybindings"; +import { shortcutLabelForCommand } from "../../keybindings"; import { type TerminalContextDraft, type TerminalContextSelection, } from "../../lib/terminalContext"; +import { toKindScopedComposerContextId } from "@t3tools/shared/composerContextReferences"; import { - replaceComposerContextReferences, - toKindScopedComposerContextId, -} from "@t3tools/shared/composerContextReferences"; -import { - resolveRestingComposerControlsLayout, - shouldAnimateComposerRestingTransition, shouldUseCompactComposerPrimaryActions, shouldUseCompactComposerFooter, shouldUseRestingComposerLayout, } from "../composerFooterLayout"; -import { measureRestingComposerControls } from "./restingComposerControlsMeasurement"; import { type ComposerCitationCommentRequest, type ComposerPromptEditorHandle, @@ -204,12 +160,10 @@ import { import { ComposerContextActionsContext, composerContextRecordsFromDraft, - uploadedContextRecordFromDraft, } from "../composerContextPresentation"; import { useOpenPrLink } from "~/lib/openPullRequestLink"; import { collectInlineContextIds, - stripInlineContextReferences, type ComposerContextReference, ensureInlineContextReferences, formatInlineContextReference, @@ -217,44 +171,23 @@ import { inlineContextReferenceReplacement, } from "~/lib/composerContextReferences"; import { - asKnownContextRecord, attachmentContextRecord, - composerContextImportLookupIds, - isSameComposerContextPayload, uploadedAttachmentContextRecord, - fileContextReference, - imageContextReference, previewAnnotationContextId, previewAnnotationContextRecord, - previewAnnotationFromRecord, reviewCommentContextId, reviewCommentContextReference, reviewCommentContextRecord, - reviewCommentFromRecord, - terminalContextDraftFromRecord, terminalContextReference, terminalContextRecord, threadContextRecord, threadContextReference, } from "~/lib/composerContextRecords"; -import { - copiedComposerAttachmentFile, - rememberCopiedComposerAttachments, -} from "~/lib/copiedComposerAttachments"; +import { rememberCopiedComposerAttachments } from "~/lib/copiedComposerAttachments"; import { useThreadContextDrop, threadContextDropTargetProps } from "./threadContextDrag"; import { readThreadShell } from "~/state/entities"; -import { requestConfirmDialog } from "~/confirmDialog"; import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard"; -import type { - ComposerContextClipboardFragment, - ComposerContextRecord, - ThreadPullRequestLink, -} from "@t3tools/contracts"; -import { resolveAssetUrl } from "~/assets/assetUrls"; -import { assetEnvironment } from "~/state/assets"; -import { readPreparedConnection } from "~/state/session"; -import { useAtomQueryRunner } from "~/state/use-atom-query-runner"; -import { orchestrationEnvironment } from "~/state/orchestration"; +import type { ComposerContextRecord, ThreadPullRequestLink } from "@t3tools/contracts"; import { threadContextAttachment } from "~/lib/threadContextAttachment"; import { type ComposerCommandItem, @@ -262,7 +195,6 @@ import { composerSuggestionOptionId, } from "./ComposerCommandMenu"; import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions"; -import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu"; import { ComposerAttachButton, ComposerAttachmentFileList, @@ -272,24 +204,14 @@ import { ComposerRestingImagePreviews, } from "./ComposerAttachmentStrip"; import { ComposerPrimaryActions } from "./ComposerPrimaryActions"; -import { - ComposerFooterModeControls, - ComposerFooterPrimaryActions, - ComposerModelPicker, -} from "./ComposerFooterControls"; +import { ComposerFooterPrimaryActions } from "./ComposerFooterControls"; import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel"; import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel"; import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner"; -import { ComposerControl, ComposerControlSeparator } from "./ComposerControl"; import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight"; import { buildPullRequestReferenceContext } from "../pullRequest/pullRequestDetail.logic"; -import { - getComposerPromptInjectionState, - getComposerProviderState, - getComposerReasoningStep, - renderProviderTraitsMenuContent, - renderProviderTraitsPicker, -} from "./composerProviderState"; +import { getComposerPromptInjectionState, getComposerReasoningStep } from "./composerProviderState"; +import { readPromptUltrathink } from "./TraitsPicker"; import { providerSupportsManualCompaction, resolveContextWindowModelDisplayName, @@ -300,12 +222,6 @@ import { buildExpandedImagePreview, type ExpandedImagePreview, } from "./ExpandedImagePreview"; -import { - getPendingSnapShotAnimations, - pendingSnapShotAnimationIdsForTarget, - subscribeToPendingSnapShotAnimations, -} from "../../lib/snapShotAnimation"; -import { resizeSnapShotSource } from "../../lib/snapShotSource"; import { cn, isMacPlatform, randomUUID } from "~/lib/utils"; import { getComposerPromptLengthValidationMessage, @@ -314,10 +230,7 @@ import { } from "./composerSubmission"; import { ComposerPromptLengthValidation } from "./ComposerPromptLengthValidation"; import { pendingDraftWork } from "./pendingDraftWork"; -import { - importComposerThreadAttachment, - remainingComposerAttachmentSlots, -} from "./composerThreadImport"; +import { importComposerThreadAttachment } from "./composerThreadImport"; import { isTimelineScrollTarget } from "./timelineScrollTarget"; import { createComposerScrollGestureState, @@ -328,631 +241,14 @@ import { } from "./composerScrollGesture"; import { observeResize } from "~/lib/observeResize"; -type ComposerCommandMenuPosition = { - bottom: number; - left: number; - maxHeight: number; - width: number; -}; - const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError); const COMPOSER_SCROLL_COLLAPSE_THRESHOLD_PX = 24; const COMPOSER_SCROLL_GESTURE_RESET_MS = 120; -const COMPOSER_RESTING_TRANSITION_CLEANUP_BUFFER_MS = 50; -const COMPOSER_RESTING_TRANSITION_EASING = "cubic-bezier(0.32, 0.72, 0, 1)"; -const COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX = 4; - -function useComposerRestingTransition( - isCollapsed: boolean, - isResting: boolean, - restingControlsRef: React.RefObject, - onOverlayHeightChange: (height: number) => void, - animationsActive: boolean, - animationDurationMs: number, -) { - const elementRef = useRef(null); - const isCollapsedRef = useRef(isCollapsed); - const previousCollapsedRef = useRef(isCollapsed); - const previousRestingRef = useRef(isResting); - const previousHeightRef = useRef(null); - const previousModelStripHeightRef = useRef(null); - const previousContentOffsetsRef = useRef<{ - promptFromTop: number | null; - promptHeight: number | null; - actionFromBottom: number | null; - controlsFromBottom: number | null; - controlsFromLeft: number | null; - surfaceBottomInset: number | null; - }>({ - promptFromTop: null, - promptHeight: null, - actionFromBottom: null, - controlsFromBottom: null, - controlsFromLeft: null, - surfaceBottomInset: null, - }); - const animationRef = useRef(null); - const animationTargetHeightRef = useRef(null); - const contentAnimationsRef = useRef([]); - const stateChangeAnimationsRef = useRef([]); - const pinnedOverlayRef = useRef(null); - const transitionCleanupTimeoutRef = useRef(null); - const transitionLayoutRequestRef = useRef(0); - const hasCompletedInitialLayoutRef = useRef(false); - - const clearOverlayPin = () => { - // The overlay belongs to the chat view and outlives this composer, so it - // is remembered from pin time rather than re-resolved through a ref that - // React may already have detached during unmount. - const overlay = pinnedOverlayRef.current; - pinnedOverlayRef.current = null; - overlay?.style.removeProperty("height"); - overlay?.style.removeProperty("display"); - overlay?.style.removeProperty("flex-direction"); - overlay?.style.removeProperty("justify-content"); - }; - - const clearTransitionStyles = () => { - const element = elementRef.current; - const footer = element?.querySelector('[data-chat-composer-footer="true"]'); - element?.style.removeProperty("overflow"); - element?.style.removeProperty("clip-path"); - element?.style.removeProperty("overflow-clip-margin"); - element - ?.querySelector('[data-chat-composer-surface="true"]') - ?.style.removeProperty("height"); - footer?.style.removeProperty("position"); - footer?.style.removeProperty("top"); - footer?.style.removeProperty("bottom"); - footer?.style.removeProperty("left"); - footer?.style.removeProperty("right"); - footer?.style.removeProperty("height"); - const shell = element?.closest('[data-slot="composer-shell"]'); - shell?.removeAttribute("data-model-strip-transition"); - const modelStrip = shell?.querySelector('[data-composer-model-strip="true"]'); - for (const property of [ - "position", - "top", - "visibility", - "height", - "min-height", - "padding-top", - "align-items", - "z-index", - "pointer-events", - ]) { - modelStrip?.style.removeProperty(property); - } - clearOverlayPin(); - }; - - useLayoutEffect(() => { - isCollapsedRef.current = isCollapsed; - }); - - const transitionToCurrentGeometry = (stateChanged: boolean) => { - const element = elementRef.current; - const surface = element?.querySelector('[data-chat-composer-surface="true"]'); - if (!element || !surface) return; - - const nextIsCollapsed = isCollapsedRef.current; - - const visibleTransitionElement = (selector: string) => - Array.from(element.querySelectorAll(selector)).find( - (candidate) => candidate.getClientRects().length > 0, - ) ?? null; - const prompt = visibleTransitionElement( - '[data-composer-prompt-surface="true"], [data-chat-composer-transition-prompt="true"]', - ); - const action = visibleTransitionElement('[data-chat-composer-transition-actions="true"]'); - const footer = element.querySelector('[data-chat-composer-footer="true"]'); - const continuousControls = - element.dataset.inlineRestingControls === "true" || element.dataset.modelOnlyStrip === "true"; - const controls = nextIsCollapsed - ? restingControlsRef.current - : element.querySelector('[data-chat-composer-controls="left"]'); - - const shell = element.closest('[data-slot="composer-shell"]'); - const modelStrip = shell?.querySelector('[data-composer-model-strip="true"]'); - const interruptedStripHeight = - animationRef.current && modelStrip ? modelStrip.getBoundingClientRect().height : null; - const interruptedAnimation = animationRef.current; - const interruptedPromptTop = interruptedAnimation - ? (prompt?.getBoundingClientRect().top ?? null) - : null; - const interruptedActionTop = interruptedAnimation - ? (action?.getBoundingClientRect().top ?? null) - : null; - const interruptedControlsLeft = interruptedAnimation - ? (controls?.getBoundingClientRect().left ?? null) - : null; - const interruptedControlsTop = interruptedAnimation - ? (controls?.getBoundingClientRect().top ?? null) - : null; - const interruptedHeight = interruptedAnimation ? element.getBoundingClientRect().height : null; - const interruptedTargetHeight = animationTargetHeightRef.current; - const interruptedCurrentTime = - typeof interruptedAnimation?.currentTime === "number" - ? interruptedAnimation.currentTime - : null; - const interruptedDuration = interruptedAnimation?.effect?.getComputedTiming().duration; - if (transitionCleanupTimeoutRef.current !== null) { - window.clearTimeout(transitionCleanupTimeoutRef.current); - transitionCleanupTimeoutRef.current = null; - } - interruptedAnimation?.cancel(); - animationRef.current = null; - for (const animation of contentAnimationsRef.current) animation.cancel(); - contentAnimationsRef.current = []; - if (stateChanged) { - for (const animation of stateChangeAnimationsRef.current) animation.cancel(); - stateChangeAnimationsRef.current = []; - } - clearTransitionStyles(); - - const nextRect = element.getBoundingClientRect(); - const nextHeight = nextRect.height; - const nextModelStripHeight = modelStrip?.getBoundingClientRect().height ?? null; - // The chat view resize-observes the overlay to place the timeline - // inset, the scroll-to-end pill, and the mini player. Publishing the - // destination height here turns that feedback into one update instead - // of a ChatView re-render on every animation frame. - const overlay = element.closest('[data-chat-composer-overlay="true"]'); - const overlayRect = overlay?.getBoundingClientRect(); - const overlayHeight = overlayRect?.height ?? null; - if (overlayHeight !== null) { - onOverlayHeightChange(overlayHeight); - } - const nextPromptRect = prompt?.getBoundingClientRect() ?? null; - const nextPromptTop = nextPromptRect?.top ?? null; - const nextActionTop = action?.getBoundingClientRect().top ?? null; - const nextControlsRect = controls?.getBoundingClientRect() ?? null; - const nextControlsTop = nextControlsRect?.top ?? null; - const footerBottom = footer ? nextRect.bottom - footer.getBoundingClientRect().bottom : 1; - const previousHeight = interruptedHeight ?? previousHeightRef.current; - const targetChanged = - interruptedTargetHeight === null || Math.abs(interruptedTargetHeight - nextHeight) >= 0.5; - const shouldAnimate = shouldAnimateComposerRestingTransition({ - hasCompletedInitialLayout: hasCompletedInitialLayoutRef.current, - stateChanged, - hasInterruptedAnimation: interruptedHeight !== null, - }); - - if ( - shouldAnimate && - animationsActive && - previousHeight !== null && - Math.abs(previousHeight - nextHeight) >= 0.5 - ) { - const remainingDuration = - typeof interruptedDuration === "number" && interruptedCurrentTime !== null - ? Math.max(1, interruptedDuration - interruptedCurrentTime) - : animationDurationMs; - const duration = - interruptedHeight !== null && !targetChanged ? remainingDuration : animationDurationMs; - element.style.overflow = "clip"; - if (modelStrip) { - const controlsClearance = Math.max( - nextModelStripHeight ?? 0, - previousModelStripHeightRef.current ?? 0, - ); - element.style.overflowClipMargin = `${controlsClearance}px`; - element.style.clipPath = `inset(0 0 -${controlsClearance}px 0)`; - } - surface.style.height = "100%"; - - if (overlay && overlayHeight !== null) { - overlay.style.height = `${String(overlayHeight)}px`; - overlay.style.display = "flex"; - overlay.style.flexDirection = "column"; - overlay.style.justifyContent = "flex-end"; - pinnedOverlayRef.current = overlay; - } - - if (footer) { - footer.style.position = "absolute"; - footer.style.top = "auto"; - footer.style.bottom = `${String(footerBottom)}px`; - footer.style.height = "3rem"; - if (nextIsCollapsed) { - footer.style.left = "auto"; - footer.style.right = "1px"; - } else { - footer.style.left = "1px"; - footer.style.right = "1px"; - } - } - - let stripAnimation: Animation | null = null; - if (modelStrip) { - const stripHeight = modelStrip.getBoundingClientRect().height; - const stripOverlap = -Number.parseFloat(getComputedStyle(modelStrip).marginTop); - const fromHeight = - interruptedStripHeight ?? - (previousCollapsedRef.current - ? (previousModelStripHeightRef.current ?? stripHeight) - : stripOverlap); - const toHeight = nextIsCollapsed ? stripHeight : stripOverlap; - modelStrip.style.position = "relative"; - modelStrip.style.top = "auto"; - modelStrip.style.visibility = "visible"; - modelStrip.style.minHeight = "0"; - modelStrip.style.paddingTop = "0"; - modelStrip.style.alignItems = "flex-end"; - modelStrip.style.pointerEvents = "none"; - modelStrip.style.zIndex = "20"; - shell?.setAttribute("data-model-strip-transition", "true"); - stripAnimation = modelStrip.animate( - [{ height: `${fromHeight}px` }, { height: `${toHeight}px` }], - { duration, easing: COMPOSER_RESTING_TRANSITION_EASING, fill: "both" }, - ); - } - - const animation = element.animate( - [{ height: `${previousHeight}px` }, { height: `${nextHeight}px` }], - { - duration, - easing: COMPOSER_RESTING_TRANSITION_EASING, - fill: "both", - }, - ); - animationRef.current = animation; - animationTargetHeightRef.current = nextHeight; - - const animatedRect = element.getBoundingClientRect(); - const previousBottom = - overlayRect && previousContentOffsetsRef.current.surfaceBottomInset !== null - ? overlayRect.bottom - previousContentOffsetsRef.current.surfaceBottomInset - : animatedRect.bottom; - const bottomShift = previousBottom - animatedRect.bottom; - const previousPromptTop = - interruptedPromptTop ?? - (previousContentOffsetsRef.current.promptFromTop === null - ? null - : animatedRect.top + bottomShift + previousContentOffsetsRef.current.promptFromTop); - const previousActionTop = - interruptedActionTop ?? - (previousContentOffsetsRef.current.actionFromBottom === null - ? null - : previousBottom - previousContentOffsetsRef.current.actionFromBottom); - const contentAnimations: Animation[] = stripAnimation ? [stripAnimation] : []; - const animateContentPosition = ( - content: HTMLElement | null, - previousTop: number | null, - previousLeft: number | null = null, - ) => { - if (!content || previousTop === null) return; - const rect = content.getBoundingClientRect(); - const offset = previousTop - rect.top; - const offsetX = previousLeft === null ? 0 : previousLeft - rect.left; - if (Math.abs(offset) < 0.5 && Math.abs(offsetX) < 0.5) return; - contentAnimations.push( - content.animate( - [{ transform: `translate(${offsetX}px, ${offset}px)` }, { transform: "none" }], - { - duration, - easing: COMPOSER_RESTING_TRANSITION_EASING, - }, - ), - ); - }; - animateContentPosition(prompt, previousPromptTop); - animateContentPosition(action, previousActionTop); - if (continuousControls) { - const previousControlsTop = - interruptedControlsTop ?? - (previousContentOffsetsRef.current.controlsFromBottom === null - ? null - : previousBottom - previousContentOffsetsRef.current.controlsFromBottom); - const previousControlsLeft = - interruptedControlsLeft ?? - (previousContentOffsetsRef.current.controlsFromLeft === null - ? null - : animatedRect.left + previousContentOffsetsRef.current.controlsFromLeft); - animateContentPosition(controls, previousControlsTop, previousControlsLeft); - } - contentAnimationsRef.current = contentAnimations; - - if (stateChanged) { - const stateChangeAnimations: Animation[] = []; - - const previousPromptHeight = previousContentOffsetsRef.current.promptHeight; - if ( - !nextIsCollapsed && - prompt && - nextPromptRect && - previousPromptHeight !== null && - nextPromptRect.height - previousPromptHeight >= 0.5 - ) { - const hiddenHeight = nextPromptRect.height - previousPromptHeight; - stateChangeAnimations.push( - prompt.animate( - [ - { clipPath: `inset(0 0 ${String(hiddenHeight)}px 0)` }, - { clipPath: "inset(0 0 0 0)" }, - ], - { - duration, - easing: COMPOSER_RESTING_TRANSITION_EASING, - }, - ), - ); - } - - const arrivingControls = nextIsCollapsed - ? restingControlsRef.current - : element.querySelector('[data-chat-composer-controls="left"]'); - if (arrivingControls && !continuousControls) { - const drift = nextIsCollapsed - ? -COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX - : COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX; - stateChangeAnimations.push( - arrivingControls.animate( - [ - { opacity: 0, transform: `translateY(${String(drift)}px)` }, - { opacity: 1, transform: "none" }, - ], - { - duration: nextIsCollapsed ? duration : duration / 2, - delay: nextIsCollapsed ? 0 : duration / 2, - fill: "backwards", - easing: COMPOSER_RESTING_TRANSITION_EASING, - }, - ), - ); - } - - const arrivingImagePreviews = nextIsCollapsed - ? Array.from( - element.querySelectorAll('[data-chat-composer-resting-images="true"]'), - ) - : Array.from( - element.querySelectorAll('[data-chat-composer-expanded-image="true"]'), - ); - for (const imagePreview of arrivingImagePreviews) { - stateChangeAnimations.push( - imagePreview.animate([{ opacity: 0 }, { opacity: 1 }], { - duration: nextIsCollapsed ? duration : duration / 2, - delay: nextIsCollapsed ? 0 : duration / 2, - fill: "backwards", - easing: COMPOSER_RESTING_TRANSITION_EASING, - }), - ); - } - stateChangeAnimationsRef.current = stateChangeAnimations; - } - - const finishTransition = (cancelAnimations: boolean) => { - if (animationRef.current !== animation) return; - if (transitionCleanupTimeoutRef.current !== null) { - window.clearTimeout(transitionCleanupTimeoutRef.current); - transitionCleanupTimeoutRef.current = null; - } - if (cancelAnimations) { - animation.cancel(); - for (const contentAnimation of contentAnimationsRef.current) { - contentAnimation.cancel(); - } - for (const stateChangeAnimation of stateChangeAnimationsRef.current) { - stateChangeAnimation.cancel(); - } - } - animationRef.current = null; - animationTargetHeightRef.current = null; - contentAnimationsRef.current = []; - stateChangeAnimationsRef.current = []; - animation.cancel(); - stripAnimation?.cancel(); - clearTransitionStyles(); - }; - void animation.finished.catch(() => undefined).then(() => finishTransition(false)); - // A suspended document timeline can leave `finished` pending while - // these measurement styles remain active. Wall-clock cleanup makes - // the natural layout the eventual source of truth in that case. - transitionCleanupTimeoutRef.current = window.setTimeout( - () => finishTransition(true), - duration + COMPOSER_RESTING_TRANSITION_CLEANUP_BUFFER_MS, - ); - } else { - animationTargetHeightRef.current = null; - } - - previousCollapsedRef.current = nextIsCollapsed; - previousHeightRef.current = nextHeight; - previousModelStripHeightRef.current = nextModelStripHeight; - previousContentOffsetsRef.current = { - promptFromTop: nextPromptTop === null ? null : nextPromptTop - nextRect.top, - promptHeight: nextPromptRect?.height ?? null, - actionFromBottom: nextActionTop === null ? null : nextRect.bottom - nextActionTop, - controlsFromBottom: nextControlsTop === null ? null : nextRect.bottom - nextControlsTop, - controlsFromLeft: nextControlsRect === null ? null : nextControlsRect.left - nextRect.left, - surfaceBottomInset: overlayRect ? overlayRect.bottom - nextRect.bottom : null, - }; - }; - - useLayoutEffect(() => { - const requestId = transitionLayoutRequestRef.current + 1; - transitionLayoutRequestRef.current = requestId; - const stateChanged = previousCollapsedRef.current !== isCollapsed; - // A non-Git context strip enters or leaves flow through ChatView state in - // an earlier layout effect. Let React flush that parent update before the - // FLIP reads its destination geometry, while still running before paint. - queueMicrotask(() => { - if (transitionLayoutRequestRef.current !== requestId) return; - transitionToCurrentGeometry(stateChanged); - }); - return () => { - if (transitionLayoutRequestRef.current === requestId) { - transitionLayoutRequestRef.current += 1; - } - }; - }, [isCollapsed, transitionToCurrentGeometry]); - - useLayoutEffect(() => { - if (previousRestingRef.current === isResting) return; - previousRestingRef.current = isResting; - if (animationRef.current) return; - const overlay = elementRef.current?.closest('[data-chat-composer-overlay="true"]'); - if (overlay) onOverlayHeightChange(overlay.getBoundingClientRect().height); - }, [isResting, onOverlayHeightChange]); - - useLayoutEffect(() => { - const element = elementRef.current; - if (!element) return; - - const body = element.querySelector('[data-chat-composer-body="true"]'); - return observeResize(body ? [element, body] : element, (entries) => { - if (animationRef.current) { - if (body && entries.some((entry) => entry.target === body)) { - transitionToCurrentGeometry(false); - } - return; - } - const elementRect = element.getBoundingClientRect(); - const visibleTransitionElement = (selector: string) => - Array.from(element.querySelectorAll(selector)).find( - (candidate) => candidate.getClientRects().length > 0, - ) ?? null; - const promptRect = visibleTransitionElement( - '[data-composer-prompt-surface="true"], [data-chat-composer-transition-prompt="true"]', - )?.getBoundingClientRect(); - const actionTop = visibleTransitionElement( - '[data-chat-composer-transition-actions="true"]', - )?.getBoundingClientRect().top; - const controlsRect = ( - isCollapsedRef.current - ? restingControlsRef.current - : visibleTransitionElement('[data-chat-composer-controls="left"]') - )?.getBoundingClientRect(); - previousHeightRef.current = elementRect.height; - previousContentOffsetsRef.current = { - promptFromTop: promptRect === undefined ? null : promptRect.top - elementRect.top, - promptHeight: promptRect?.height ?? null, - actionFromBottom: actionTop === undefined ? null : elementRect.bottom - actionTop, - controlsFromBottom: - controlsRect === undefined ? null : elementRect.bottom - controlsRect.top, - controlsFromLeft: controlsRect === undefined ? null : controlsRect.left - elementRect.left, - surfaceBottomInset: - (element - .closest('[data-chat-composer-overlay="true"]') - ?.getBoundingClientRect().bottom ?? elementRect.bottom) - elementRect.bottom, - }; - }); - }, [restingControlsRef, transitionToCurrentGeometry]); - - useEffect(() => { - hasCompletedInitialLayoutRef.current = true; - return () => { - if (transitionCleanupTimeoutRef.current !== null) { - window.clearTimeout(transitionCleanupTimeoutRef.current); - transitionCleanupTimeoutRef.current = null; - } - animationRef.current?.cancel(); - animationRef.current = null; - animationTargetHeightRef.current = null; - for (const animation of contentAnimationsRef.current) animation.cancel(); - contentAnimationsRef.current = []; - for (const animation of stateChangeAnimationsRef.current) animation.cancel(); - stateChangeAnimationsRef.current = []; - clearTransitionStyles(); - }; - }, [clearTransitionStyles]); - - return elementRef; -} - -function composerCommandMenuPositionsEqual( - a: ComposerCommandMenuPosition, - b: ComposerCommandMenuPosition, -): boolean { - return ( - a.bottom === b.bottom && a.left === b.left && a.maxHeight === b.maxHeight && a.width === b.width - ); -} - -function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children: ReactNode }) { - const [position, setPosition] = useState(null); - - useLayoutEffect(() => { - const anchor = props.anchor; - if (!anchor) return; - - const updatePosition = () => { - const form = anchor.closest('[data-chat-composer-form="true"]'); - const mainSurface = form?.querySelector( - '[data-chat-composer-main-surface="true"]', - ); - const rect = (mainSurface ?? form ?? anchor).getBoundingClientRect(); - const rootFontSizePx = - Number.parseFloat(window.getComputedStyle(document.documentElement).fontSize) || 16; - const drawerInsetRem = Number.parseFloat( - window.getComputedStyle(form ?? anchor).getPropertyValue("--chat-composer-drawer-inset"), - ); - const drawerInset = drawerInsetRem * rootFontSizePx; - const width = rect.width - drawerInset * 2; - if (width <= 0) { - setPosition(null); - return; - } - const composerOverlap = rootFontSizePx + 1; - const next = { - bottom: window.innerHeight - rect.top - composerOverlap, - left: rect.left + drawerInset, - maxHeight: Math.max(96, rect.top - 24 + composerOverlap), - width, - }; - setPosition((current) => - current && composerCommandMenuPositionsEqual(current, next) ? current : next, - ); - }; - - updatePosition(); - window.addEventListener("resize", updatePosition); - window.addEventListener("scroll", updatePosition, true); - - const observed: Element[] = [anchor]; - for (let element = anchor.parentElement; element; element = element.parentElement) { - observed.push(element); - } - const stopObserving = observeResize(observed, updatePosition); - - return () => { - stopObserving(); - window.removeEventListener("resize", updatePosition); - window.removeEventListener("scroll", updatePosition, true); - }; - }, [props.anchor]); - - if (!props.anchor || !position) return null; - - return createPortal( -
- {props.children} -
, - document.body, - ); -} import { toastManager } from "../ui/toast"; -import { CircleAlertIcon, PlayIcon, ShieldIcon } from "lucide-react"; +import { PlayIcon, ShieldIcon } from "lucide-react"; import { proposedPlanTitle } from "@t3tools/shared/proposedPlanText"; import { hasProviderSetup } from "./ProviderStatusBanner"; -import { - applyProviderInstanceSettings, - deriveProviderInstanceEntries, - NO_PROVIDER_MODEL_SELECTION, - sortProviderInstanceEntries, - type ProviderInstanceEntry, -} from "../../providerInstances"; import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection"; import type { UnifiedSettings } from "@t3tools/contracts/settings"; import { @@ -961,13 +257,8 @@ import { type SessionPhase, type Thread, type ThreadShell, - videoMimeType, } from "../../types"; -import { - buildComposerPromptHistoryEntries, - stepComposerPromptHistory, - type ComposerPromptHistoryPosition, -} from "./composerPromptHistory"; +import { type ComposerPromptHistoryPosition } from "./composerPromptHistory"; import type { PendingUserInputDraftAnswer } from "../../pendingUserInput"; import type { LatestProposedPlanState, @@ -980,8 +271,6 @@ import { } from "@t3tools/client-runtime/state/composer-dispatch"; import type { ContextWindowSnapshot } from "../../lib/contextWindow"; import { - hasCompleteProviderWorkspaceSnapshot, - hasCurrentProviderWorkspaceSnapshot, resolveProviderSkillsForCwd, resolveProviderSlashCommandsForCwd, } from "@t3tools/client-runtime/providerSkills"; @@ -990,12 +279,19 @@ import { useMediaQuery } from "../../hooks/useMediaQuery"; import { useSoftwareKeyboardOpen } from "../../hooks/useSoftwareKeyboardOpen"; import { useStableCallback } from "../../hooks/useStableCallback"; import { usePanelAnimationSettings } from "../../panelAnimations"; -import { useAtomCommand } from "../../state/use-atom-command"; import { readEnvironmentScope } from "../../state/session"; -import { serverEnvironment } from "../../state/server"; import type { ReviewCommentContext } from "../../reviewCommentContext"; - -const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000; +import { useComposerRestingTransition } from "./useComposerRestingTransition"; +import { ComposerCommandMenuLayer } from "./ComposerCommandMenuLayer"; +import { useRestingComposerControlsLayout } from "./useRestingComposerControlsLayout"; +import { useProviderWorkspaceSnapshotRefresh } from "./useProviderWorkspaceSnapshotRefresh"; +import { useComposerProviderModel } from "./useComposerProviderModel"; +import { useComposerImageGroups } from "./useComposerImageGroups"; +import { useComposerStash } from "./useComposerStash"; +import { useComposerContextImport } from "./useComposerContextImport"; +import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; +import { ComposerControlsBar } from "./ComposerControlsBar"; +import { useComposerCommandKey } from "./useComposerCommandKey"; /** Reads and disarms a paste-as-text deadline: the shortcut applies to one paste only. */ function consumePasteAsTextShortcut(deadline: { current: number }): boolean { @@ -1004,103 +300,6 @@ function consumePasteAsTextShortcut(deadline: { current: number }): boolean { return armed; } -async function downloadAttachmentBlob(url: string): Promise { - try { - const response = await fetch(url, { signal: AbortSignal.timeout(60_000) }); - return response.ok ? await response.blob() : null; - } catch { - return null; - } -} - -const extendReplacementRangeForTrailingSpace = ( - text: string, - rangeEnd: number, - replacement: string, -): number => { - if (!replacement.endsWith(" ")) { - return rangeEnd; - } - return text[rangeEnd] === " " ? rangeEnd + 1 : rangeEnd; -}; - -function useRestingComposerControlsLayout(host: HTMLDivElement | null, useControlsAsHost = false) { - const [controls, setControls] = useState(null); - const controlsRef = useRef(null); - const attachControls = (element: HTMLDivElement | null) => { - controlsRef.current = element; - setControls(element); - }; - const [layout, setLayout] = useState<{ - hiddenCount: number; - iconOnlyCount?: number; - visible: boolean; - }>({ hiddenCount: 0, visible: true }); - - const measure = () => { - const currentHost = useControlsAsHost ? controls : host; - if (currentHost === null || !controls) return; - - const measurement = measureRestingComposerControls(controls); - if (!measurement) return; - const style = getComputedStyle(currentHost); - const hostWidth = - currentHost.clientWidth - - (Number.parseFloat(style.paddingInlineStart) || 0) - - (Number.parseFloat(style.paddingInlineEnd) || 0); - - setLayout((current) => { - const next = resolveRestingComposerControlsLayout({ - ...measurement, - hostWidth, - previous: current, - }); - return next.hiddenCount === current.hiddenCount && - next.iconOnlyCount === current.iconOnlyCount && - next.visible === current.visible - ? current - : next; - }); - }; - - useLayoutEffect(() => { - const currentHost = useControlsAsHost ? controls : host; - if (!currentHost || !controls) return; - let stopObserving = () => {}; - const observeControls = () => { - stopObserving(); - stopObserving = observeResize( - [ - currentHost, - controls, - ...controls.querySelectorAll( - "[data-resting-block], [data-composer-control-label], [data-chat-provider-model-picker-label]", - ), - ], - measure, - ); - measure(); - }; - observeControls(); - const mutations = new MutationObserver(observeControls); - mutations.observe(controls, { childList: true, subtree: true, characterData: true }); - document.fonts.addEventListener("loadingdone", measure); - return () => { - stopObserving(); - mutations.disconnect(); - document.fonts.removeEventListener("loadingdone", measure); - }; - }, [host, controls, useControlsAsHost, measure]); - - return { - controlsRef, - attachControls, - hiddenBlockCount: layout.hiddenCount, - iconOnlyBlockCount: layout.iconOnlyCount ?? 0, - controlsVisible: layout.visible, - }; -} - const runtimeModeOptions = runtimeModes.map((mode) => ({ mode, ...runtimeModeConfig[mode] })); export interface ChatComposerHandle { @@ -1329,237 +528,6 @@ export interface ChatComposerProps { onFileOpen: (attachment: ChatFileAttachment) => void; } -/** - * Keeps the selected provider's workspace snapshot fresh for the composer's - * cwd. Returns a check to run when the user types. - */ -function useProviderWorkspaceSnapshotRefresh(input: { - readonly environmentId: EnvironmentId; - readonly gitCwd: string | null; - readonly selectedProviderEntry: ProviderInstanceEntry | undefined; - readonly selectedProviderStatus: ServerProvider | null; -}) { - const { environmentId, gitCwd, selectedProviderEntry, selectedProviderStatus } = input; - const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, { - reportFailure: false, - }); - // The last scan this composer asked for. A request inside the TTL is not - // repeated, so a client clock ahead of the server's cannot loop rescans. - const workspaceRefreshKeyRef = useRef<{ key: string; requestedAt: number } | null>(null); - const [workspaceRefreshRetry, setWorkspaceRefreshRetry] = useState<{ - key: string; - notBefore: number; - } | null>(null); - const workspaceRefreshScopeKey = - gitCwd && selectedProviderEntry - ? `${environmentId}:${selectedProviderEntry.instanceId}:${gitCwd}` - : null; - const workspaceSlashCommandsPending = - selectedProviderStatus?.workspaceSnapshots?.some( - (snapshot) => snapshot.cwd === gitCwd && snapshot.slashCommandsPending === true, - ) ?? false; - useEffect(() => { - if ( - !workspaceSlashCommandsPending || - !workspaceRefreshRetry || - workspaceRefreshRetry.key !== workspaceRefreshScopeKey - ) - return; - const timeout = setTimeout( - () => { - setWorkspaceRefreshRetry((current) => (current === workspaceRefreshRetry ? null : current)); - }, - Math.max(0, workspaceRefreshRetry.notBefore - Date.now()), - ); - return () => clearTimeout(timeout); - }, [workspaceRefreshRetry, workspaceRefreshScopeKey, workspaceSlashCommandsPending]); - // Losing a snapshot (the server dropped it) lifts both the TTL and the retry - // cooldown so the next check rescans at once. - const hasWorkspaceSnapshot = hasCompleteProviderWorkspaceSnapshot(selectedProviderStatus, gitCwd); - const [hadWorkspaceSnapshot, setHadWorkspaceSnapshot] = useState(hasWorkspaceSnapshot); - const [workspaceSnapshotLossCount, setWorkspaceSnapshotLossCount] = useState(0); - if (hadWorkspaceSnapshot !== hasWorkspaceSnapshot) { - setHadWorkspaceSnapshot(hasWorkspaceSnapshot); - if (!hasWorkspaceSnapshot) { - setWorkspaceSnapshotLossCount((count) => count + 1); - setWorkspaceRefreshRetry(null); - } - } - const lastWorkspaceSnapshotLossRef = useRef(workspaceSnapshotLossCount); - const refreshWorkspaceSnapshotIfStale = ( - now: number, - key: string | null, - retry: { key: string; notBefore: number } | null, - snapshotLossCount: number, - ) => { - if (lastWorkspaceSnapshotLossRef.current !== snapshotLossCount) { - lastWorkspaceSnapshotLossRef.current = snapshotLossCount; - workspaceRefreshKeyRef.current = null; - } - if (key === null || !gitCwd || !selectedProviderEntry) return; - const lastRequest = workspaceRefreshKeyRef.current; - if ( - lastRequest?.key === key && - now - lastRequest.requestedAt < PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS - ) - return; - // A pending retry needs no clearing here: its cooldown lapses long before the TTL. - if (hasCurrentProviderWorkspaceSnapshot(selectedProviderStatus, gitCwd, now)) return; - if (retry?.key === key && now < retry.notBefore) return; - const request = { key, requestedAt: now }; - workspaceRefreshKeyRef.current = request; - const retryLater = () => { - if (workspaceRefreshKeyRef.current !== request) return; - workspaceRefreshKeyRef.current = null; - setWorkspaceRefreshRetry({ - key, - notBefore: Date.now() + WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS, - }); - }; - void refreshProviders({ - environmentId, - input: { instanceId: selectedProviderEntry.instanceId, cwd: gitCwd }, - }).then((result) => { - const refreshedSnapshot = - result._tag === "Success" && - hasCompleteProviderWorkspaceSnapshot( - result.value.providers.find( - (provider) => provider.instanceId === selectedProviderEntry.instanceId, - ), - gitCwd, - ); - if (!refreshedSnapshot) retryLater(); - }, retryLater); - }; - const refreshWorkspaceSnapshotOnChange = useEffectEvent(refreshWorkspaceSnapshotIfStale); - useEffect(() => { - refreshWorkspaceSnapshotOnChange( - Date.now(), - workspaceRefreshScopeKey, - workspaceRefreshRetry, - workspaceSnapshotLossCount, - ); - }, [workspaceRefreshScopeKey, workspaceRefreshRetry, workspaceSnapshotLossCount]); - return useStableCallback(() => - refreshWorkspaceSnapshotIfStale( - Date.now(), - workspaceRefreshScopeKey, - workspaceRefreshRetry, - workspaceSnapshotLossCount, - ), - ); -} - -const NO_PROVIDER_MODELS: ServerProvider["models"] = []; - -/** - * The provider instances the composer offers, which one is selected, and the model and options - * the draft resolves to on it. The draft store is read first so every derivation follows the only - * hook here; in the composer body they would straddle its later hooks and lose their cache. - */ -function useComposerProviderModel( - input: Omit[0], "entries"> & { - readonly providerStatuses: ReadonlyArray; - readonly settings: UnifiedSettings; - readonly activeProjectId: ProjectId | null; - readonly threadRef: ScopedThreadRef | DraftId; - readonly threadModelSelection: ModelSelection | null | undefined; - readonly projectModelSelection: ModelSelection | null | undefined; - readonly promptInjectionState: ReturnType; - }, -) { - const { - providerStatuses, - settings, - activeProjectId, - threadRef, - threadModelSelection, - projectModelSelection, - promptInjectionState, - candidateInstanceIds, - lockedProvider, - lockedInstanceId, - } = input; - const draftModelState = useComposerDraftModelState(threadRef); - const providerInstanceEntries: ReadonlyArray = sortProviderInstanceEntries( - applyProviderInstanceSettings( - deriveProviderInstanceEntries(providerStatuses), - settings, - activeProjectId, - ), - ); - const selection = resolveComposerProviderSelection({ - entries: providerInstanceEntries, - candidateInstanceIds, - lockedProvider, - lockedInstanceId, - }); - const selectedInstanceId = - selection.selectedProviderEntry?.instanceId ?? NO_PROVIDER_MODEL_SELECTION.instanceId; - const selectedProvider: ProviderDriverKind = - selection.selectedProviderEntry?.driverKind ?? selection.requestedDriverKind; - const modelState = deriveEffectiveComposerModelState({ - draft: draftModelState, - providers: providerStatuses, - selectedProvider, - selectedInstanceId, - threadModelSelection, - projectModelSelection, - settings, - }); - const selectedProviderModels = selection.selectedProviderEntry?.models ?? NO_PROVIDER_MODELS; - const composerProviderState = getComposerProviderState({ - provider: selectedProvider, - model: modelState.selectedModel, - models: selectedProviderModels, - promptInjectionState, - modelOptions: modelState.modelOptions?.[selectedInstanceId], - planModeEnabled: settings.planModeEnabled, - }); - return { - providerInstanceEntries, - ...selection, - selectedInstanceId, - selectedProvider, - selectedProviderModels, - composerModelOptions: modelState.modelOptions, - selectedModel: modelState.selectedModel, - composerProviderState, - }; -} - -/** - * Follows the SnapShots still animating into this draft and splits the draft's images into - * pending SnapShots and standalone images. - */ -function useComposerImageGroups( - composerDraftTarget: ScopedThreadRef | DraftId, - composerImages: ReadonlyArray, - composerPreviewAnnotations: ReadonlyArray<{ readonly id: string }>, -) { - const pendingSnapShotAnimations = useSyncExternalStore( - subscribeToPendingSnapShotAnimations, - getPendingSnapShotAnimations, - getPendingSnapShotAnimations, - ); - const pendingSnapShotIds = pendingSnapShotAnimationIdsForTarget( - pendingSnapShotAnimations, - composerDraftTarget, - ); - const previewAnnotationIds = new Set( - composerPreviewAnnotations.map((annotation) => annotation.id), - ); - return { - pendingSnapShotAnimations, - pendingSnapShotIds, - pendingSnapShotIdSet: new Set(pendingSnapShotIds), - uncommittedSnapShotIds: pendingSnapShotIds.filter( - (id) => !composerImages.some((image) => image.id === id), - ), - standaloneComposerImages: composerImages.filter((image) => !previewAnnotationIds.has(image.id)), - }; -} - const NO_PROVIDER_SKILLS: ServerProvider["skills"] = []; const NO_PROVIDER_SLASH_COMMANDS: ServerProvider["slashCommands"] = []; @@ -1876,12 +844,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const clearComposerDraftPersistedAttachments = useComposerDraftStore( (store) => store.clearPersistedAttachments, ); - const clearComposerDraftTerminalContexts = useComposerDraftStore( - (store) => store.clearTerminalContexts, - ); - const clearComposerDraftPromptAndImages = useComposerDraftStore( - (store) => store.clearComposerPromptAndImages, - ); const syncComposerDraftPersistedAttachments = useComposerDraftStore( (store) => store.syncPersistedAttachments, ); @@ -2135,12 +1097,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const [composerMenuAnchor, setComposerMenuAnchor] = useState(null); const hasWrappedPrompt = useComposerMultilinePrompt(composerMenuAnchor); const hasMultilinePrompt = prompt.includes("\n") || hasWrappedPrompt; - const [isStashMenuOpen, setIsStashMenuOpen] = useState(false); const [isTasksDrawerOpen, setIsTasksDrawerOpen] = useState(false); - const [stashPulse, setStashPulse] = useState<{ key: number; active: boolean }>({ - key: 0, - active: false, - }); // A pending question stays expanded: its card moves into the banner dock, // so collapsing would leave the surface empty and squashed beneath it. const isComposerCollapsedMobile = @@ -2152,10 +1109,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const composerEditorRef = useRef(null); const pasteAsTextShortcutUntilRef = useRef(0); - const pastedTextFileNamesRef = useRef<{ targetKey: string; names: Set }>({ - targetKey: "", - names: new Set(), - }); const composerFormRef = useRef(null); const composerSurfaceRef = useRef(null); const providerInputRejectedRef = useRef(false); @@ -2171,9 +1124,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const composerScrollCollapseEligibleRef = useRef(false); const windowRefocusInFlightRef = useRef(false); const composerScrollGestureRef = useRef(createComposerScrollGestureState()); - const stashPulseKeyRef = useRef(0); - const stashPulseTimeoutRef = useRef(null); - const stashInFlightRef = useRef>(new Set()); const pendingImageCompressionsRef = useRef>(new Map()); const pendingThreadImportsRef = useRef>(new Map()); const isRevertingCheckpointRef = useRef(isRevertingCheckpoint); @@ -2307,7 +1257,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activePendingProgress.activeQuestion?.allowCustomAnswer !== false)); const composerFooterHasWideActions = showPlanFollowUpPrompt || activePendingProgress !== null; - const setPromptFromTraits = (nextPrompt: string) => { + const editPromptFromTraits = (edit: (prompt: string) => string) => { + const currentPrompt = getComposerDraft(composerDraftTarget)?.prompt ?? ""; + const nextPrompt = edit(currentPrompt); + if (nextPrompt === currentPrompt) return; if (nextPrompt === promptRef.current) { scheduleComposerFocus(); return; @@ -2319,36 +1272,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) setComposerTrigger(detectComposerTrigger(nextPrompt, nextPrompt.length)); scheduleComposerFocus(); }; - const setPromptFromTraitsStable = useStableCallback(setPromptFromTraits); + const editPromptFromTraitsStable = useStableCallback(editPromptFromTraits); + const promptUltrathink = readPromptUltrathink(prompt); - const providerTraitsMenuContent = renderProviderTraitsMenuContent({ - provider: selectedProvider, - instanceId: selectedInstanceId, - ...(routeKind === "server" ? { threadRef: routeThreadRef } : {}), - ...(routeKind === "draft" && draftId ? { draftId } : {}), - model: selectedModel, - models: selectedProviderModels, - modelOptions: composerModelOptions?.[selectedInstanceId], - reportedModelSelection, - prompt, - onPromptChange: setPromptFromTraitsStable, - planModeEnabled: settings.planModeEnabled, - }); - const providerTraitsPickerInput = { - provider: selectedProvider, - instanceId: selectedInstanceId, - ...(routeKind === "server" ? { threadRef: routeThreadRef } : {}), - ...(routeKind === "draft" && draftId ? { draftId } : {}), - model: selectedModel, - models: selectedProviderModels, - modelOptions: composerModelOptions?.[selectedInstanceId], - reportedModelSelection, - prompt, - onPromptChange: setPromptFromTraitsStable, - planModeEnabled: settings.planModeEnabled, - isComposerOwned: true, - } satisfies Parameters[0]; - const providerTraitsPicker = renderProviderTraitsPicker(providerTraitsPickerInput); const [inlineRestingControlsHost, setInlineRestingControlsHost] = useState( null, ); @@ -2429,9 +1355,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) removeComposerDraftFile(attachmentDraftTarget, fileId); }; - const addComposerDraftTerminalContexts = useComposerDraftStore( - (store) => store.addTerminalContexts, - ); const addComposerDraftReviewComment = useComposerDraftStore((store) => store.addReviewComment); const addComposerDraftPreviewAnnotation = useComposerDraftStore( (store) => store.addPreviewAnnotation, @@ -2491,287 +1414,30 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return fragment; }; const buildContextClipboardFragmentStable = useStableCallback(buildContextClipboardFragment); - const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { reportFailure: false }); - const loadThreadTranscript = useAtomCommand(orchestrationEnvironment.threadTranscript, { - reportFailure: false, + const { + loadThreadTranscript, + countReservedAttachments, + countReservedAttachmentsStable, + importContextRecords, + importContextFragment, + importContextFragmentStable, + } = useComposerContextImport({ + environmentId, + activeThread, + activeThreadId, + composerDraftTarget, + attachmentDraftTarget, + attachmentTargetKey, + attachmentTargetKeyRef, + questionAttachmentTarget, + pendingUserInputs, + composerContextRecords, + composerImages, + composerFilesRef, + pendingImageCompressionsRef, + pendingThreadImportsRef, + addComposerFilesToDraft, }); - const countReservedAttachments = () => { - const questionRequest = pendingUserInputs[0]; - const otherQuestionKeys = - questionAttachmentTarget && questionRequest && activeThreadId - ? questionRequest.questions - .map((question) => - questionAttachmentDraftId( - environmentId, - activeThreadId, - questionRequest.requestId, - question.id, - ), - ) - .filter((key) => key !== questionAttachmentTarget) - : []; - const draft = getComposerDraft(attachmentDraftTarget); - return ( - (draft?.images.length ?? 0) + - (draft?.files.length ?? 0) + - (pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) + - (pendingThreadImportsRef.current.get(attachmentTargetKey) ?? 0) + - countQuestionAttachments(otherQuestionKeys) - ); - }; - const countReservedAttachmentsStable = useStableCallback(countReservedAttachments); - const runAttachmentImport = async ( - record: Extract, - localId: string, - sourceEnvironmentId: EnvironmentId, - importTargetKey: string, - ) => { - const fail = (reason: string) => { - toastManager.add({ - type: "error", - title: `Couldn't bring ${record.name} into this message`, - description: `${reason} Remove the chip or attach the file again.`, - }); - }; - let file = copiedComposerAttachmentFile(sourceEnvironmentId, record.attachmentId); - if (!file) { - const sourceConnection = readPreparedConnection(sourceEnvironmentId); - if (!sourceConnection) { - fail("The environment it came from is not connected."); - return; - } - const result = await createAssetUrl({ - environmentId: sourceEnvironmentId, - input: { resource: { _tag: "attachment", attachmentId: record.attachmentId } }, - }); - const url = - result._tag === "Success" - ? resolveAssetUrl(sourceConnection.httpBaseUrl, result.value.relativeUrl) - : null; - if (!url) { - fail("The original attachment is no longer available."); - return; - } - const blob = await downloadAttachmentBlob(url); - if (!blob) { - fail("Downloading it from the source failed."); - return; - } - file = new File([blob], record.name, { type: record.mimeType || blob.type }); - } - // The draft these bytes belong to may have been sent or switched away from while they - // downloaded. Dropping them here keeps them out of whatever draft is open now. - if (attachmentTargetKeyRef.current !== importTargetKey) return; - const replacesFileMarker = - record.kind === "file" && - composerFilesRef.current.some( - (candidate) => - composerFileNeedsReattach(candidate) && - composerFileMatchesReattachMarker(candidate, { - name: record.name, - mimeType: file.type, - sizeBytes: file.size, - }), - ); - if ( - !replacesFileMarker && - (pendingThreadImportsRef.current.get(importTargetKey) ?? 0) > 0 && - countReservedAttachments() >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS - ) { - fail("The attachment limit has been reached."); - return; - } - if (record.kind === "image") { - const accepted = addComposerDraftImages( - attachmentDraftTarget, - [ - { - type: "image", - id: localId, - name: record.name, - mimeType: file.type, - sizeBytes: file.size, - previewUrl: URL.createObjectURL(file), - file, - }, - ], - { - allowDuplicates: - getComposerDraft(composerDraftTarget)?.previewAnnotations.some( - (annotation) => annotation.id === localId, - ) ?? false, - }, - ); - if (!accepted.includes(localId)) - fail("The draft rejected this attachment (duplicate or attachment limit reached)."); - } else { - const accepted = addComposerFilesToDraft([ - { - type: "file", - id: localId, - name: record.name, - mimeType: file.type, - sizeBytes: file.size, - file, - }, - ]); - if (!accepted.includes(localId)) - fail("The draft rejected this attachment (duplicate or attachment limit reached)."); - } - }; - const importAttachmentRecord = async ( - record: Extract, - localId: string, - sourceEnvironmentId: EnvironmentId, - ) => { - // The chip lands in the draft immediately while these bytes are still downloading. Count - // the transfer against its own draft so a send cannot snapshot a message whose chip has no - // attachment behind it, and so bytes for an abandoned draft never enter the next one. - const importTargetKey = attachmentTargetKey; - pendingDraftWork.begin(importTargetKey); - await runAttachmentImport(record, localId, sourceEnvironmentId, importTargetKey).finally(() => - pendingDraftWork.end(importTargetKey), - ); - }; - const importContextRecords = ( - records: ReadonlyArray, - sourceEnvironmentId: EnvironmentId | null, - threadDraftTarget = attachmentDraftTarget, - ): ReadonlyMap => { - const rewritten = new Map(); - const dependentAttachmentLocalIds = new Map(); - const skippedDependentAttachmentIds = new Set(); - // Resolve annotations before their dependent screenshot records even if a foreign - // clipboard producer emitted the records in a different order. - const orderedRecords = records.toSorted((left, right) => - left.kind === "preview-annotation" && right.kind !== "preview-annotation" - ? -1 - : right.kind === "preview-annotation" && left.kind !== "preview-annotation" - ? 1 - : 0, - ); - for (const candidate of orderedRecords) { - // Producer ids fold into context ids, so two different excerpts can collide. Only skip - // when the draft already holds the same payload; a colliding but different record is - // re-minted under a fresh id so both survive the paste. - const record = asKnownContextRecord(candidate); - if (!record) continue; - // A reminted annotation needs its screenshot under the new annotation id. - const existing = dependentAttachmentLocalIds.has(record.contextId) - ? undefined - : composerContextImportLookupIds(record).flatMap((contextId) => { - const found = composerContextRecords.get(contextId); - return found ? [found] : []; - })[0]; - // Upload completion can change the server id since copy; the local bytes still match. - if ( - sourceEnvironmentId !== null && - (record.kind === "image" || record.kind === "file") && - (existing?.kind === "image" || existing?.kind === "file") && - existing.record.file !== null && - existing.record.file === - copiedComposerAttachmentFile(sourceEnvironmentId, record.attachmentId) - ) - continue; - const existingRecord = - existing?.kind === "terminal" - ? terminalContextRecord(existing.record) - : existing?.kind === "review-comment" - ? reviewCommentContextRecord(existing.record) - : existing?.kind === "preview-annotation" - ? previewAnnotationContextRecord(existing.record, { - screenshotContextId: composerImages.some( - (image) => image.id === existing.record.id, - ) - ? existing.record.id - : undefined, - }) - : existing?.kind === "thread" - ? existing.record - : existing - ? (uploadedContextRecordFromDraft(existing) ?? undefined) - : undefined; - if ( - existingRecord && - isSameComposerContextPayload(existingRecord, record) && - (record.kind !== "thread" || threadDraftTarget === attachmentDraftTarget) - ) { - if (record.kind === "preview-annotation" && record.screenshotContextId) { - skippedDependentAttachmentIds.add(record.screenshotContextId); - } - continue; - } - const conflicts = existing !== undefined; - switch (record.kind) { - case "terminal": { - const threadId = activeThread?.id ?? activeThreadId; - if (!threadId) break; - const imported = terminalContextDraftFromRecord(record, threadId); - const draft = conflicts ? { ...imported, id: randomUUID() } : imported; - addComposerDraftTerminalContexts(composerDraftTarget, [draft], { - appendReference: false, - }); - rewritten.set(record.contextId, terminalContextReference(draft).contextId); - break; - } - case "review-comment": { - const imported = reviewCommentFromRecord(record); - const comment = conflicts ? { ...imported, id: randomUUID() } : imported; - addComposerDraftReviewComment(composerDraftTarget, comment, { - appendReference: false, - }); - rewritten.set(record.contextId, reviewCommentContextId(comment.id)); - break; - } - case "element": - case "preview-annotation": { - const imported = - record.kind === "element" - ? elementContextToPreviewAnnotation(record, randomUUID(), new Date().toISOString()) - : previewAnnotationFromRecord(record); - const annotation = conflicts ? { ...imported, id: randomUUID() } : imported; - if (record.kind === "preview-annotation" && record.screenshotContextId) { - dependentAttachmentLocalIds.set(record.screenshotContextId, annotation.id); - } - addComposerDraftPreviewAnnotation(composerDraftTarget, annotation, { - appendReference: false, - }); - rewritten.set(record.contextId, previewAnnotationContextId(annotation.id)); - break; - } - case "thread": { - // The agent can only read threads on its own server; a pasted foreign one is dropped. - if (record.environmentId !== environmentId) break; - addComposerDraftThreadContexts(threadDraftTarget, [record], { - appendReference: false, - }); - rewritten.set(record.contextId, record.contextId); - break; - } - case "image": - case "file": { - if (skippedDependentAttachmentIds.has(record.contextId)) break; - if (sourceEnvironmentId === null && !conflicts) { - rewritten.set(record.contextId, record.contextId); - break; - } - if (sourceEnvironmentId === null) break; - const localId = dependentAttachmentLocalIds.get(record.contextId) ?? randomUUID(); - rewritten.set(record.contextId, toKindScopedComposerContextId(record.kind, localId)); - void importAttachmentRecord(record, localId, sourceEnvironmentId); - break; - } - default: - break; - } - } - return rewritten; - }; - const importContextFragment = ( - fragment: ComposerContextClipboardFragment, - ): ReadonlyMap => - importContextRecords(fragment.records, fragment.source.environmentId); - const importContextFragmentStable = useStableCallback(importContextFragment); useEffect(() => { if (isLiteralPendingAnswer) return; @@ -3577,678 +2243,82 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }; const expandMobileComposerStable = useStableCallback(expandMobileComposer); - // Entries are built on the keypress, not per render: the timeline changes - // on every streamed delta and ArrowUp is rare. - const promptHistoryMessagesRef = useRef(promptHistoryMessages); - useLayoutEffect(() => { - promptHistoryMessagesRef.current = promptHistoryMessages; + const { onComposerCommandKey } = useComposerCommandKey({ + keybindings, + sendShortcut: settings.sendShortcut, + routeKind, + phase, + isCompacting, + followUpBehavior, + isSoftwareKeyboardOpen, + planModeUiEnabled, + isLiteralPendingAnswer, + pendingUserInputs, + promptHistoryMessages, + promptHistoryPositionRef, + composerDraftTarget, + promptRef, + composerImagesRef, + composerFilesRef, + composerTerminalContextsRef, + composerPreviewAnnotations, + composerReviewComments, + composerEditorRef, + composerMenuOpenRef, + composerMenuItemsRef, + activeComposerMenuItemRef, + setComposerDraftPrompt, + setComposerCursor, + setComposerTrigger, + setComposerHighlightedItemId, + dismissComposerTrigger, + toggleInteractionMode, + nudgeComposerMenuHighlight, + onSelectComposerItem, + resolveActiveComposerTrigger, + readComposerSnapshot, + applyPromptReplacement, + submitComposer, }); - // The composer persists across threads. A recall from thread A must not - // be treated as active in thread B, where the text-match fallback could - // otherwise turn B's own draft into a browsing position. - const promptHistoryTargetKey = composerTargetKey(composerDraftTarget); - - const replacePromptFromHistory = (nextPrompt: string) => { - promptRef.current = nextPrompt; - setComposerDraftPrompt(composerDraftTarget, nextPrompt); - setComposerCursor(collapseExpandedComposerCursor(nextPrompt, nextPrompt.length)); - setComposerTrigger(null); - setComposerHighlightedItemId(null); - }; - - const navigatePromptHistory = ( - direction: "backward" | "forward", - event: KeyboardEvent, - ): boolean => { - if (event.shiftKey || event.altKey || event.metaKey || event.ctrlKey || event.isComposing) { - return false; - } - if (pendingUserInputs.length > 0) return false; - if ( - composerImagesRef.current.length > 0 || - composerFilesRef.current.length > 0 || - composerTerminalContextsRef.current.length > 0 || - composerPreviewAnnotations.length > 0 || - composerReviewComments.length > 0 - ) { - return false; - } - const recalled = promptHistoryPositionRef.current; - const position = recalled?.targetKey === promptHistoryTargetKey ? recalled.position : null; - if (position === null && promptRef.current.length > 0) { - return false; - } - const editor = composerEditorRef.current; - if (!editor?.isCaretOnVisualEdge(direction === "backward" ? "start" : "end")) { - return false; - } - const step = stepComposerPromptHistory({ - direction, - entries: buildComposerPromptHistoryEntries(promptHistoryMessagesRef.current), - position, - currentPrompt: promptRef.current, - }); - if (!step) return false; - promptHistoryPositionRef.current = step.position - ? { targetKey: promptHistoryTargetKey, position: step.position } - : null; - replacePromptFromHistory(step.prompt); - return true; - }; - - const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem = false) => { - const submissionIntent = composerSubmissionIntentForKey({ - event, - keybindings, - isSoftwareKeyboardOpen, - isDraftThread: routeKind === "draft", - isRunning: phase === "running", - sendShortcut: settings.sendShortcut, - prompt: promptRef.current, - }); - if (key === "Tab" && event.shiftKey && submissionIntent === null) { - if (!planModeUiEnabled) return false; - toggleInteractionMode(); - return true; - } - const { trigger } = resolveActiveComposerTrigger(); - const menuIsActive = - !isLiteralPendingAnswer && (composerMenuOpenRef.current || trigger !== null); - if (key === "Escape") { - if (!menuIsActive || event.isComposing || event.keyCode === 229) return false; - dismissComposerTrigger(trigger); - composerMenuOpenRef.current = false; - return true; - } - if (menuIsActive && (submissionIntent === null || submissionIntent === "foreground")) { - const currentItems = composerMenuItemsRef.current; - const selectedItem = activeComposerMenuItemRef.current ?? currentItems[0]; - if (key === "ArrowDown" && currentItems.length > 0) { - nudgeComposerMenuHighlight("ArrowDown"); - return true; - } - if (key === "ArrowUp" && currentItems.length > 0) { - nudgeComposerMenuHighlight("ArrowUp"); - return true; - } - if ((key === "Enter" || key === "Tab") && selectedItem) { - onSelectComposerItem(selectedItem); - return true; - } - } - if ((key === "ArrowUp" || key === "ArrowDown") && submissionIntent === null) { - return navigatePromptHistory(key === "ArrowUp" ? "backward" : "forward", event); - } - if (submissionIntent) { - submitComposer( - undefined, - resolveComposerDispatchMode({ - running: phase === "running", - alternateModifier: submissionIntent === "alternate", - activeTurnDefault: followUpBehavior, - canSteer: !isCompacting, - }), - submissionIntent, - ); - return true; - } - if (key === "Enter" && isTaskItem) return false; - if ( - !isLiteralPendingAnswer && - !event.isComposing && - (key === "Enter" || (key === "Tab" && !event.shiftKey)) - ) { - const selection = composerEditorRef.current?.readSelectionRange(); - const snapshot = readComposerSnapshot(); - if (selection && selection.start === selection.end && snapshot.value === promptRef.current) { - const edit = - key === "Enter" - ? listContinuationForEnter(snapshot.value, selection.start) - : listIndentForTab(snapshot.value, selection.start, selection.end); - if ( - edit && - applyPromptReplacement(edit.start, edit.end, edit.replacement, { - expandedCursorAfterReplace: edit.cursorAfter, - }) - ) { - return true; - } - } - } - return false; - }; - - const stashQueue = usePromptStashStore((state) => state.entries); - const stashEntryToQueue = usePromptStashStore((state) => state.stashEntry); - const takeStashEntry = usePromptStashStore((state) => state.takeEntry); - const finalizeStashEntryImages = usePromptStashStore((state) => state.finalizeEntryImages); - - useEffect(() => { - return () => { - if (stashPulseTimeoutRef.current !== null) { - window.clearTimeout(stashPulseTimeoutRef.current); - } - }; - }, []); - - const pulseStashBadge = () => { - stashPulseKeyRef.current += 1; - setStashPulse({ key: stashPulseKeyRef.current, active: true }); - if (stashPulseTimeoutRef.current !== null) { - window.clearTimeout(stashPulseTimeoutRef.current); - } - stashPulseTimeoutRef.current = window.setTimeout(() => { - stashPulseTimeoutRef.current = null; - setStashPulse((current) => ({ ...current, active: false })); - }, 1200); - }; - - const restoreStashEntry = async (menuEntry: PromptStashEntry) => { - const filesToVerify = menuEntry.files ?? []; - if (filesToVerify.some((file) => file.environmentId !== environmentId)) { - toastManager.add({ - type: "error", - title: "Stashed files belong to another environment", - description: "Restore this prompt in the environment that received its files.", - }); - return; - } - setIsStashMenuOpen(false); - - // An expired upload restores as a needs-reattach row instead of a reference - // the next send would fail to verify. Verify BEFORE taking: the take - // removes the entry from durable storage, and a tab closed during this - // await must still find it there after reload. - const verifications = await Promise.all( - filesToVerify.map((file) => - verifyStashedAttachmentUpload({ environmentId, attachmentId: file.attachmentId }), - ), - ); - const expiredAttachmentIds = new Set( - filesToVerify - .filter((_, index) => verifications[index]?.status === "missing") - .map((file) => file.attachmentId), - ); - - // A thread switch during the verify await would mix the new thread's - // prompt with this invocation's captured target. Nothing was taken yet, - // so abort and leave the entry restorable where the user now is. - if ( - isRevertingCheckpointRef.current || - composerTargetKey(composerDraftTarget) !== composerDraftTargetKeyRef.current - ) { - return; - } - - const { entry, durable } = takeStashEntry(menuEntry.id); - if (!entry) return; - if (!durable) { - toastManager.add({ - type: "warning", - title: "Restored prompt may reappear in the stash", - description: - "Browser storage rejected the update, so this entry could still be there after a reload.", - data: { hideCopyButton: true }, - }); - } - - const rewrittenContextIds = entry.records - ? importContextRecords(entry.records, null, composerDraftTarget) - : new Map(); - const restoredPrompt = replaceComposerContextReferences(entry.prompt, (reference) => { - const contextId = rewrittenContextIds.get(reference.contextId); - return contextId - ? formatInlineContextReference({ - ...reference, - contextId, - kind: reference.kind === "element" ? "preview-annotation" : reference.kind, - }) - : reference.source; - }); - const currentPrompt = promptRef.current; - const nextPrompt = - restoredPrompt.length === 0 - ? currentPrompt - : currentPrompt.trim().length - ? `${currentPrompt.replace(/\s+$/, "")}\n\n${restoredPrompt}` - : restoredPrompt; - let promptChanged = nextPrompt !== currentPrompt; - if (promptChanged) { - promptRef.current = nextPrompt; - setComposerDraftPrompt(composerDraftTarget, nextPrompt); - setComposerCursor(collapseExpandedComposerCursor(nextPrompt, nextPrompt.length)); - setComposerTrigger(null); - } - - let unrestoredFileNames: string[] = []; - const expiredFileNames: string[] = []; - let restoredFileCount = 0; - const stashedFiles = entry.files ?? []; - if (stashedFiles.length > 0) { - const composerFilesNow = composerFilesRef.current; - const existingFileIds = new Set(composerFilesNow.map((file) => file.id)); - const retainedUploadIds = new Set( - composerFilesNow.flatMap((file) => - file.uploadedAttachmentId ? [file.uploadedAttachmentId] : [], - ), - ); - const existingFileKeys = new Set(composerFilesNow.map(composerFileDedupKey)); - const reattachMarkers = composerFilesNow.filter(composerFileNeedsReattach); - const restoredMarkerIds = new Set(); - const duplicateFiles: PersistedComposerFileAttachment[] = []; - const markerReplacements: ComposerFileAttachment[] = []; - const appendedFiles: ComposerFileAttachment[] = []; - for (const file of stashedFiles) { - const expired = expiredAttachmentIds.has(file.attachmentId); - const key = composerFileDedupKey(file); - const restored: ComposerFileAttachment = { - type: "file", - id: file.id, - name: file.name, - mimeType: file.mimeType, - sizeBytes: file.sizeBytes, - file: null, - ...(file.source ? { source: file.source } : {}), - ...(expired - ? {} - : { uploadedAttachmentId: file.attachmentId, uploadEnvironmentId: environmentId }), - }; - if (existingFileIds.has(file.id)) { - if (!expired && !retainedUploadIds.has(file.attachmentId)) { - duplicateFiles.push(file); - } - continue; - } - const reattachMarker = reattachMarkers.find( - (marker) => - !restoredMarkerIds.has(marker.id) && composerFileMatchesReattachMarker(marker, file), - ); - if (reattachMarker) { - restoredMarkerIds.add(reattachMarker.id); - existingFileIds.add(file.id); - existingFileKeys.add(key); - if (expired) { - expiredFileNames.push(file.name); - } else { - retainedUploadIds.add(file.attachmentId); - markerReplacements.push(restored); - } - continue; - } - if (existingFileKeys.has(key)) { - if (!expired && !retainedUploadIds.has(file.attachmentId)) { - duplicateFiles.push(file); - } - continue; - } - existingFileIds.add(file.id); - existingFileKeys.add(key); - if (expired) { - expiredFileNames.push(file.name); - } else { - retainedUploadIds.add(file.attachmentId); - } - appendedFiles.push(restored); - } - const capacity = remainingComposerAttachmentSlots( - composerImagesRef.current.length + composerFilesNow.length, - pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0, - ); - const filesToAppend = appendedFiles.slice(0, capacity); - const skippedFiles = appendedFiles.slice(capacity); - unrestoredFileNames = skippedFiles.map((file) => file.name); - // A non-durable take can resurrect the stash entry after a reload; - // deleting these uploads would leave it pointing at nothing. - if (durable) { - for (const file of duplicateFiles) { - releasePersistedAttachmentUpload({ - id: file.id, - environmentId, - attachmentId: file.attachmentId, - }); - } - for (const file of skippedFiles) { - if (file.uploadedAttachmentId) { - releasePersistedAttachmentUpload({ - id: file.id, - environmentId, - attachmentId: file.uploadedAttachmentId, - }); - } - } - } - const restoredFiles = [...markerReplacements, ...filesToAppend]; - if (restoredFiles.length > 0) { - addComposerDraftFiles(composerDraftTarget, restoredFiles, { appendReference: true }); - const restoredFilePrompt = getComposerDraft(composerDraftTarget)?.prompt; - if (restoredFilePrompt !== undefined && restoredFilePrompt !== promptRef.current) { - promptRef.current = restoredFilePrompt; - setComposerCursor( - collapseExpandedComposerCursor(restoredFilePrompt, restoredFilePrompt.length), - ); - setComposerTrigger(null); - promptChanged = true; - } - restoredFileCount = filesToAppend.length; - } - } - - let unrestoredImageNames: string[] = []; - if (entry.attachments.length > 0) { - const existingIds = new Set(composerImagesRef.current.map((image) => image.id)); - // The draft store also dedupes by mimeType+sizeBytes+name, so filter - // on the same key here. Counting a duplicate against capacity would - // burn a slot the store then refuses to fill, pushing a genuinely - // unique image into the overflow list for nothing. - const existingDedupKeys = new Set( - composerImagesRef.current.map( - (image) => `${image.mimeType}\0${image.sizeBytes}\0${image.name}`, - ), - ); - const capacity = remainingComposerAttachmentSlots( - composerImagesRef.current.length + composerFilesRef.current.length + restoredFileCount, - pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0, - ); - const pending = entry.attachments.filter( - (attachment) => - !existingIds.has(attachment.id) && - !existingDedupKeys.has( - `${attachment.mimeType}\0${attachment.sizeBytes}\0${attachment.name}`, - ), - ); - unrestoredImageNames = pending.slice(capacity).map((attachment) => attachment.name); - const restoredImages = hydrateImagesFromPersisted(pending.slice(0, capacity)); - if (restoredImages.length > 0) { - addComposerDraftImages(composerDraftTarget, restoredImages); - } - } - - const missingImageReasons: string[] = []; - if (entry.droppedImageNames.length > 0) { - missingImageReasons.push( - `${entry.droppedImageNames.join(", ")} exceeded the stash size limit when this prompt was saved.`, - ); - } - if (entry.unreadableImageNames && entry.unreadableImageNames.length > 0) { - missingImageReasons.push( - `${entry.unreadableImageNames.join(", ")} could not be read when this prompt was saved.`, - ); - } - if (unrestoredImageNames.length > 0) { - missingImageReasons.push( - `${unrestoredImageNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`, - ); - } - if (unrestoredFileNames.length > 0) { - missingImageReasons.push( - `${unrestoredFileNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`, - ); - } - if (expiredFileNames.length > 0) { - missingImageReasons.push( - `${expiredFileNames.join(", ")}: stashed files are kept for 24 hours and this upload expired. Attach the file again.`, - ); - } - if (missingImageReasons.length > 0) { - toastManager.add({ - type: "warning", - title: "Some attachments were not restored", - description: missingImageReasons.join(" "), - }); - } - - if (promptChanged) { - window.requestAnimationFrame(() => { - composerEditorRef.current?.focusAtEnd(); - }); - } - }; - const restoreStashEntryStable = useStableCallback(restoreStashEntry); - - const deleteStashEntry = (entry: PromptStashEntry) => { - const { entry: removed, durable } = takeStashEntry(entry.id); - if (!stashQueue.some((candidate) => candidate.id !== entry.id)) { - setIsStashMenuOpen(false); - } - if (durable && removed) { - for (const file of removed.files ?? []) { - releasePersistedAttachmentUpload({ - id: file.id, - environmentId: file.environmentId, - attachmentId: file.attachmentId, - }); - } - } - if (!durable) { - toastManager.add({ - type: "warning", - title: "Stash entry may come back", - description: - "Browser storage rejected the delete, so this prompt could reappear after a reload.", - data: { hideCopyButton: true }, - }); - } - }; - const deleteStashEntryStable = useStableCallback(deleteStashEntry); - - const stashCurrentPrompt = async () => { - // Stashing clears the draft. A pasted attachment still downloading would then land in the - // emptied composer instead of travelling with the entry it belongs to. - if (pendingDraftWork.has(attachmentTargetKeyRef.current)) { - toastManager.add({ - type: "info", - title: "Still bringing attached context into this message.", - description: "Stash again once its chip resolves.", - }); - return; - } - const prompt = promptRef.current.trim(); - const images = [...composerImagesRef.current]; - const files = [...composerFilesRef.current]; - const stashedRecords: ComposerContextRecord[] = [ - ...composerThreadContexts, - ...composerTerminalContextsRef.current.map(terminalContextRecord), - ...composerReviewComments.map(reviewCommentContextRecord), - ...composerPreviewAnnotations.map((annotation) => - previewAnnotationContextRecord(annotation, { - screenshotContextId: images.some((image) => image.id === annotation.id) - ? annotation.id - : undefined, - }), - ), - ]; - if (prompt.length === 0 && images.length === 0 && files.length === 0) { - const entries = usePromptStashStore.getState().entries; - const entry = entries.length === 1 ? entries[0] : undefined; - if (entry && !entry.pendingImageCount) { - await restoreStashEntry(entry); - } else { - setIsStashMenuOpen((open) => !open); - } - return; - } - const stashedFiles: PersistedComposerFileAttachment[] = []; - for (const file of files) { - if (composerFileNeedsReattach(file)) { - toastManager.add({ - type: "error", - title: "Attach dropped files again or remove them before stashing", - }); - return; - } - const upload = readAttachmentUpload(file.id); - if (upload?.status !== "ready" || upload.environmentId !== environmentId) { - toastManager.add({ - type: "error", - title: "Wait for file uploads before stashing this prompt", - }); - return; - } - stashedFiles.push({ - id: file.id, - name: file.name, - mimeType: file.mimeType, - sizeBytes: file.sizeBytes, - attachmentId: upload.attachmentId, - environmentId, - ...(file.source ? { source: file.source } : {}), - }); - } - // A repeat ⌘S on the *same* still-unencoded snapshot would stash it - // twice. Guard on the snapshot itself rather than a bare boolean: once - // the composer has been cleared the user can type something genuinely - // new (or switch threads) while encoding continues, and that deserves its - // own entry. - const attachmentKey = images - .map((image) => `image:${image.id}`) - .concat(files.map((file) => `file:${file.id}`)) - .join(","); - const snapshotKey = [String(composerDraftTarget), prompt, attachmentKey].join("\n"); - if (stashInFlightRef.current.has(snapshotKey)) return; - stashInFlightRef.current.add(snapshotKey); - - const stashTarget = composerDraftTarget; - const entryId = randomUUID(); - const stashAndEncode = async () => { - // Ordering matters in both directions: writing before clearing means a - // crash or closed tab mid-encode still leaves the prompt recoverable, - // while clearing before the async image work means edits typed during - // encoding are not wiped. - const { evicted, written, durable } = stashEntryToQueue({ - id: entryId, - createdAt: new Date().toISOString(), - prompt, - attachments: [], - ...(stashedFiles.length > 0 ? { files: stashedFiles } : {}), - droppedImageNames: [], - unreadableImageNames: [], - pendingImageCount: images.length, - ...(stashedRecords.length > 0 ? { records: stashedRecords } : {}), - }); - - // If it was rejected (quota) the store has already rolled itself back, - // so leave the composer untouched rather than making it the second - // casualty of a reload. - if (!written) { - toastManager.add({ - type: "error", - title: "Could not stash this prompt", - description: - "Browser storage rejected the write, so the composer was left as-is. Free up site data and try again.", - data: { hideCopyButton: true }, - }); - return; - } - if (!durable) { - toastManager.add({ - type: "warning", - title: "Stashed prompt will not survive a reload", - description: - "Browser storage is unavailable, so this stash is kept in memory only for this session.", - data: { hideCopyButton: true }, - }); - } - - promptRef.current = ""; - clearComposerDraftPromptAndImages(stashTarget); - clearComposerDraftTerminalContexts(stashTarget); - setComposerDraftThreadContexts(stashTarget, []); - for (const comment of composerReviewComments) { - removeComposerDraftReviewComment(stashTarget, comment.id); - } - for (const annotation of composerPreviewAnnotations) { - releaseAttachmentUpload(annotation.id); - removeComposerDraftPreviewAnnotation(stashTarget, annotation.id); - } - setComposerDraftPrompt(stashTarget, ""); - for (const image of images) { - releaseAttachmentUpload(image.id); - } - setComposerCursor(0); - setComposerTrigger(null); - pulseStashBadge(); - - if (evicted) { - for (const file of evicted.files ?? []) { - releasePersistedAttachmentUpload({ - id: file.id, - environmentId: file.environmentId, - attachmentId: file.attachmentId, - }); - } - toastManager.add({ - type: "warning", - title: "Oldest stashed prompt discarded", - description: `The stash holds ${MAX_STASH_ENTRIES} prompts; the oldest was removed to make room.`, - data: { hideCopyButton: true }, - }); - } - - // Images are re-encoded for the stash rather than stored verbatim: the - // composer allows up to 10MB per image, but localStorage gives the whole - // origin ~5MB. - const candidateAttachments: PersistedComposerImageAttachment[] = []; - const oversizedImageNames: string[] = []; - const unreadableImageNames: string[] = []; - for (const image of images) { - const result = await compressImageForStash(image.file); - if (!result.ok) { - (result.reason === "too-large" ? oversizedImageNames : unreadableImageNames).push( - image.name, - ); - continue; - } - candidateAttachments.push({ - id: image.id, - name: image.name, - mimeType: result.image.mimeType, - sizeBytes: result.image.sizeBytes, - dataUrl: result.image.dataUrl, - ...(image.source - ? { source: resizeSnapShotSource(image.source, result.image.imageSize) } - : {}), - }); - } - const { kept, droppedNames } = partitionStashAttachments(candidateAttachments); - - const { attached, durable: imagesDurable } = finalizeStashEntryImages(entryId, { - attachments: kept, - droppedImageNames: [...oversizedImageNames, ...droppedNames], - unreadableImageNames, - }); - if (attached) { - if (!imagesDurable && durable && images.length > 0) { - toastManager.add({ - type: "warning", - title: "Stashed images were not saved", - description: - "The prompt was stashed, but browser storage rejected its images. They will be missing if you reload.", - data: { hideCopyButton: true }, - }); - } - } else if (kept.length > 0) { - toastManager.add({ - type: "warning", - title: "Stashed images did not attach", - description: `That prompt was restored or deleted before ${kept.length} image${kept.length === 1 ? "" : "s"} finished saving. Re-attach ${kept.length === 1 ? "it" : "them"} if you still need ${kept.length === 1 ? "it" : "them"}.`, - data: { hideCopyButton: true }, - }); - } - }; - await stashAndEncode().finally(() => stashInFlightRef.current.delete(snapshotKey)); - }; - const stashCurrentPromptStable = useStableCallback(stashCurrentPrompt); - - const toggleStashMenu = () => { - if (isComposerCollapsedMobile) { - expandMobileComposer(); - setIsStashMenuOpen(true); - return; - } - setIsStashMenuOpen((open) => !open); - }; - const toggleStashMenuStable = useStableCallback(toggleStashMenu); + const { + stashQueue, + isStashMenuOpen, + setIsStashMenuOpen, + stashPulse, + restoreStashEntryStable, + deleteStashEntryStable, + toggleStashMenuStable, + } = useComposerStash({ + environmentId, + composerDraftTarget, + promptRef, + composerImagesRef, + composerFilesRef, + composerTerminalContextsRef, + keybindings, + terminalOpen, + projectSelectionRequired, + isRevertingCheckpoint, + pendingUserInputs, + activePendingProgress, + prompt, + composerMenuOpen, + isComposerModelPickerOpen, + isComposerCollapsedMobile, + composerPreviewAnnotations, + composerReviewComments, + composerThreadContexts, + attachmentTargetKeyRef, + composerDraftTargetKeyRef, + composerEditorRef, + isRevertingCheckpointRef, + pendingThreadImportsRef, + setComposerCursor, + setComposerTrigger, + importContextRecords, + expandMobileComposer: expandMobileComposerStable, + }); const toggleTasksDrawer = () => { setIsTasksDrawerOpen((open) => !open); }; @@ -4472,179 +2542,61 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const iconOnlyBlockCount = composerControlsCollapsed ? restingControlsIconOnlyBlockCount : expandedControlsIconOnlyBlockCount; - const restingProviderTraitsPicker = renderProviderTraitsPicker({ - ...providerTraitsPickerInput, - size: composerControlsCollapsed ? "xs" : "sm", - hidden: composerControlsHidden || restingHiddenBlockCount > 1, - }); - const restingBlockDefs = [ - ...(providerTraitsPicker - ? [ - { - id: "traits", - content: ( - <> - - {restingProviderTraitsPicker} - - ), - }, - ] - : []), - { - id: "mode", - content: ( -