diff --git a/apps/mobile/src/features/threads/PendingUserInputCard.tsx b/apps/mobile/src/features/threads/PendingUserInputCard.tsx index ec0cfdb7c9..3d5291c2c1 100644 --- a/apps/mobile/src/features/threads/PendingUserInputCard.tsx +++ b/apps/mobile/src/features/threads/PendingUserInputCard.tsx @@ -1,16 +1,67 @@ import type { RuntimeRequestId } from "@t3tools/contracts"; -import { Pressable, View } from "react-native"; +import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests"; +import { useCallback, useRef } from "react"; +import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native"; +import Animated, { + Easing, + FadeInUp, + FadeOutDown, + LinearTransition, + useAnimatedStyle, + useSharedValue, + withTiming, + type SharedValue, +} from "react-native-reanimated"; +import { USER_INPUT_TOGGLE_DURATION_MS } from "./pendingUserInputLayout"; + +import { SymbolView } from "../../components/AppSymbol"; import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText"; +import { ControlPill } from "../../components/ControlPill"; import { cn } from "../../lib/cn"; -import type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity"; +import { useThemeColor } from "../../lib/useThemeColor"; +import { + isPendingUserInputOptionSelected, + type PendingUserInput, + type PendingUserInputDraftAnswer, +} from "../../lib/threadActivity"; export interface PendingUserInputCardProps { readonly pendingUserInput: PendingUserInput; + /** + * Constant while a request is pending (it reserves keyboard space), so the + * keyboard transition is pure translation; changes only on rare discrete + * corrections, which the layout transition smooths. + */ + readonly maxHeight: number; + readonly collapsed: boolean; + readonly onToggleCollapsed: () => void; + /** Renders a stop control on the collapsed bar, which replaces the composer. */ + readonly onStopThread?: () => void; + /** + * 0 collapsed → 1 expanded. Slides the iOS overlay card down behind the + * collapsed bar (inside a clipping window) on the UI thread; the host + * animates it directly from the tap handler so the card and the feed + * inset glide start the same frame. + */ + readonly cardProgress?: SharedValue; + /** + * Receives how far the expanded card extends above the bar footprint + * (written from onLayout with no re-render); the host adds it to the + * thread feed's end inset so the end of the chat stays visible above the + * card. + */ + readonly cardCoverage?: SharedValue; + /** Fires on custom-answer focus/blur; hosts use it to vet stale keyboard state. */ + readonly onInputFocusChange?: (focused: boolean) => void; readonly drafts: Record; - readonly answers: Record | null; + readonly answers: Record> | null; readonly respondingUserInputId: RuntimeRequestId | null; - readonly onSelectOption: (requestId: RuntimeRequestId, questionId: string, label: string) => void; + readonly onSelectOption: ( + requestId: RuntimeRequestId, + question: ThreadUserInputQuestion, + label: string, + ) => void; readonly onChangeCustomAnswer: ( requestId: RuntimeRequestId, questionId: string, @@ -19,83 +70,253 @@ export interface PendingUserInputCardProps { readonly onSubmit: () => Promise; } +/** + * On iOS the collapsed bar is the PERMANENT in-flow footprint — the expanded + * card is an absolutely-positioned overlay rising above it. The overlay's + * measured height (which drives the thread feed's bottom inset) therefore + * never changes on collapse/expand, so the transcript stays perfectly still + * while the card animates over it. + * + * Android cannot use the overlay: it does not hit-test touches outside a + * parent's bounds, which made everything above the bar-sized wrapper + * untouchable. There the expanded card renders in-flow instead (the wrapper + * grows with it, and the host skips the coverage inset since the measured + * overlay already includes the card). + */ +const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios"; + +const CARD_LAYOUT_TRANSITION = LinearTransition.duration(200); + export function PendingUserInputCard(props: PendingUserInputCardProps) { - // The surface is opaque on purpose: the card floats over the thread feed - // with no blur behind it, so a translucent background renders the questions - // on top of whatever message happens to sit underneath. + const iconSubtle = useThemeColor("--color-icon-subtle"); + const questionCount = props.pendingUserInput.questions.length; + // V2 runtime requests carry response capability: a dead provider process + // cannot accept answers, so the card reads-only until the run restarts. const canRespond = props.pendingUserInput.responseCapability === "live"; - return ( - - - User input needed - - - Fill in the pending answers - - {!canRespond ? ( - - The provider process for this request is no longer available. Interrupt or restart the run - to continue. + + const cardCoverage = props.cardCoverage; + const barHeightRef = useRef(0); + const cardHeightRef = useRef(0); + // Measured card height, written straight from onLayout: the collapse slide + // distance. Not animated — it only changes on discrete relayouts. + const cardHeight = useSharedValue(0); + const notifyCoverage = useCallback(() => { + if (!cardCoverage) { + return; + } + const coverage = Math.max(0, cardHeightRef.current - barHeightRef.current); + if (coverage === cardCoverage.value) { + return; + } + if (cardCoverage.value === 0) { + // First measurement lands while the list is doing its initial + // end-pin (thread opened onto a pending request); animating it from + // zero would move the end anchor out from under that scroll. + cardCoverage.value = coverage; + return; + } + // Animated so a coverage change at rest (discrete max-height + // corrections) glides the feed instead of stepping it; toggle timing is + // owned by the host's progress values. + cardCoverage.value = withTiming(coverage, { + duration: USER_INPUT_TOGGLE_DURATION_MS, + easing: Easing.out(Easing.cubic), + }); + }, [cardCoverage]); + const handleBarLayout = useCallback( + (event: LayoutChangeEvent) => { + barHeightRef.current = event.nativeEvent.layout.height; + notifyCoverage(); + }, + [notifyCoverage], + ); + const handleCardLayout = useCallback( + (event: LayoutChangeEvent) => { + cardHeightRef.current = event.nativeEvent.layout.height; + cardHeight.value = event.nativeEvent.layout.height; + notifyCoverage(); + }, + [cardHeight, notifyCoverage], + ); + const cardProgress = props.cardProgress; + // No opacity: fading an opaque card over the live transcript reads as a + // crossfade (card text, transcript, and bar all half-visible at once). + // Instead the card stays opaque and slides its full height down past the + // clipping window's bottom edge, so the transcript is only revealed where + // the card has physically left. + const cardAnimatedStyle = useAnimatedStyle(() => { + const progress = cardProgress === undefined ? 1 : cardProgress.value; + return { + transform: [{ translateY: (1 - progress) * cardHeight.value }], + }; + }); + + // On iOS the card stays MOUNTED while collapsed (hidden via the animated + // style): expanding animates existing views on the UI thread the same + // frame the host starts the progress timing, instead of paying a React + // mount + layout before anything moves. + const renderCard = EXPANDED_CARD_IS_OVERLAY || !props.collapsed; + const showBar = props.collapsed || EXPANDED_CARD_IS_OVERLAY; + // The bar renders UNDER the card (earlier in JSX), always opaque: while + // expanded the opaque card covers it, and during the collapse slide the + // card's top edge wipes past and reveals it — no opacity handoff, so no + // crossfade frames. + const bar = showBar ? ( + + + + User input needed + + {questionCount} question{questionCount === 1 ? "" : "s"} + + + + + {props.onStopThread ? ( + ) : null} - {props.pendingUserInput.questions.map((question) => { - const draft = props.drafts[question.id]; - return ( - - - {question.header} - - - {question.question} - - - {question.options.map((option) => { - const selected = - draft?.selectedOptionLabel === option.label && !draft.customAnswer?.trim().length; - return ( - - props.onSelectOption( - props.pendingUserInput.requestId, - question.id, - option.label, - ) - } - > - + ) : null; + const card = renderCard ? ( + // The surface is opaque on purpose: the card floats over the thread + // feed with no blur behind it, so a translucent background renders + // the questions on top of whatever message happens to sit underneath. + + + + + User input needed + + + Fill in the pending answers + + + + + + + + {!canRespond ? ( + + The provider process for this request is no longer available. Interrupt or restart the + run to continue. + + ) : null} + {props.pendingUserInput.questions.map((question) => { + const draft = props.drafts[question.id]; + return ( + + + {question.header} + + + {question.question} + + + {question.options.map((option) => { + const selected = isPendingUserInputOptionSelected(draft, option.label); + return ( + + props.onSelectOption( + props.pendingUserInput.requestId, + question, + option.label, + ) + } > - {option.label} - - - ); - })} + + {option.label} + + + ); + })} + + + props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value) + } + onFocus={() => props.onInputFocusChange?.(true)} + onBlur={() => props.onInputFocusChange?.(false)} + placeholder="Or type a custom answer" + className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50" + /> - - props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value) - } - placeholder="Or type a custom answer" - className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50" - /> - - ); - })} + ); + })} + Submit answers + + ) : null; + return ( + + {bar} + {EXPANDED_CARD_IS_OVERLAY ? ( + // Clipping window for the collapse slide: same footprint as the + // expanded card, bottom edge on the bar's bottom edge. The sliding + // card exits through the bottom edge instead of drawing over the + // composer area, wiping the bar (and the transcript) into view. + + {card} + + ) : ( + card + )} ); } diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 9f7ffea111..0daaae7bf1 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -14,6 +14,7 @@ import { serializeComposerFileLink, type ComposerTrigger, } from "@t3tools/shared/composerTrigger"; +import * as Haptics from "expo-haptics"; import type { ReactNode } from "react"; import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react"; import { @@ -51,7 +52,7 @@ import { ComposerToolbarScroller, ComposerToolbarTrigger, } from "../../components/ComposerToolbarTrigger"; -import { ControlPill } from "../../components/ControlPill"; +import { ControlPill, ControlPillMenu } from "../../components/ControlPill"; import { ProviderIcon } from "../../components/ProviderIcon"; import type { DraftComposerImageAttachment } from "../../lib/composerImages"; import { buildModelOptions, groupByProvider } from "../../lib/modelOptions"; @@ -62,9 +63,13 @@ import { normalizeSearchQuery, scoreQueryMatch, } from "@t3tools/shared/searchRanking"; -import { resolveProviderOptionDescriptors } from "../../lib/providerOptions"; +import { + applyProviderOptionSelection, + resolveProviderOptionDescriptors, +} from "../../lib/providerOptions"; import { useComposerPathSearch } from "../../state/use-composer-path-search"; import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover"; +import { buildThreadSettingsMenu } from "./thread-settings-menu"; import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet"; import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation"; @@ -114,6 +119,8 @@ export interface ThreadComposerProps { readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void; readonly onReconnectEnvironment: () => void; readonly onExpandedChange?: (expanded: boolean) => void; + /** Fires on editor focus/blur; hosts use it to vet stale keyboard state. */ + readonly onEditorFocusChange?: (focused: boolean) => void; } /** @@ -308,14 +315,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer } }, [inputRef]); + const onEditorFocusChange = props.onEditorFocusChange; const handleFocus = useCallback(() => { setIsFocused(true); - }, []); + onEditorFocusChange?.(true); + }, [onEditorFocusChange]); const handleBlur = useCallback(() => { setIsFocused(false); - onExpandedChange?.(false); - }, [onExpandedChange]); + onEditorFocusChange?.(false); + }, [onEditorFocusChange]); const showStopAction = props.canStopThread; const sendLabel = @@ -623,6 +632,61 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer interactionMode: currentInteractionMode, }); + // iOS gets a native menu on the trigger pill: the everyday adjustments + // apply without resigning the keyboard, while "All Settings…" (and the + // Android trigger) still route through the sheet, which must dismiss it. + const settingsMenu = useMemo( + () => + Platform.OS === "ios" + ? buildThreadSettingsMenu({ + providerGroups: threadProviderGroups, + selectedModel: currentModelSelection, + optionDescriptors: providerOptionDescriptors, + runtimeMode: currentRuntimeMode, + }) + : null, + [threadProviderGroups, currentModelSelection, providerOptionDescriptors, currentRuntimeMode], + ); + + const onUpdateModelSelection = props.onUpdateModelSelection; + const onUpdateRuntimeMode = props.onUpdateRuntimeMode; + const handleSettingsMenuAction = useCallback( + (eventId: string) => { + const event = settingsMenu?.events.get(eventId); + if (!event) { + return; + } + switch (event.type) { + case "select-model": + void Haptics.selectionAsync(); + onUpdateModelSelection(event.option.selection); + return; + case "set-option": { + const options = applyProviderOptionSelection(providerOptionDescriptors, { + id: event.optionId, + value: event.value, + }); + if (options) { + void Haptics.selectionAsync(); + onUpdateModelSelection({ ...currentModelSelection, options }); + } + return; + } + case "set-runtime": + void Haptics.selectionAsync(); + onUpdateRuntimeMode(event.mode); + return; + } + }, + [ + currentModelSelection, + onUpdateModelSelection, + onUpdateRuntimeMode, + providerOptionDescriptors, + settingsMenu, + ], + ); + return ( void props.onPickDraftImages()} showChevron={false} /> - - } - label={settingsSummaryLabel} - maxWidth={320} - onPress={settingsSheetPresentation.open} - /> + {settingsMenu ? ( + handleSettingsMenuAction(nativeEvent.event)} + > + + } + label={settingsSummaryLabel} + maxWidth={320} + /> + + ) : ( + + } + label={settingsSummaryLabel} + maxWidth={320} + onPress={settingsSheetPresentation.open} + /> + )} {showStopAction ? ( ; - readonly activePendingUserInputAnswers: Record | null; + readonly activePendingUserInputAnswers: Record> | null; readonly respondingUserInputId: RuntimeRequestId | null; readonly draftMessage: string; readonly draftAttachments: ReadonlyArray; @@ -94,7 +131,7 @@ export interface ThreadDetailScreenProps { ) => Promise; readonly onSelectUserInputOption: ( requestId: RuntimeRequestId, - questionId: string, + question: ThreadUserInputQuestion, label: string, ) => void; readonly onChangeUserInputCustomAnswer: ( @@ -176,8 +213,48 @@ function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray state.isVisible); + const liveKeyboardHeight = useKeyboardState((state) => state.height); + // Android can swallow the IME hide callbacks when the app is backgrounded + // mid keyboard-hide (the reported repro: send — which blurs and starts the + // hide — then Home within a second). The keyboard library's height AND + // visibility then stay frozen open, so gating the sticky translation on + // visibility alone still strands the composer after resume. Quarantine the + // translation on every Android resume instead; any sign of a live keyboard + // stream — an owned input gaining focus, or any visibility/height movement — + // lifts it. A healthy resume sees no visual difference (the translation is + // already zero while the keyboard is closed). + const [keyboardStateSuspect, setKeyboardStateSuspect] = useState(false); + useEffect(() => { + if (Platform.OS !== "android") { + return; + } + const subscription = AppState.addEventListener("change", (state) => { + if (state === "active") { + setKeyboardStateSuspect(true); + } + }); + return () => { + subscription.remove(); + }; + }, []); + useEffect(() => { + setKeyboardStateSuspect(false); + }, [isKeyboardVisible, liveKeyboardHeight]); + const handleOwnedInputFocusChange = useCallback((focused: boolean) => { + if (focused) { + setKeyboardStateSuspect(false); + } + }, []); + const windowHeight = useWindowDimensions().height; + const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + 44; const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`; const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id); const composerEditorRef = useRef(null); @@ -188,7 +265,17 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread const lastScrolledAnchorMessageIdRef = useRef(null); const [composerExpanded, setComposerExpanded] = useState(false); const [anchorMessageId, setAnchorMessageId] = useState(null); - const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12); + const [endFollowEnabled, setEndFollowEnabled] = useState(true); + // Android keys the safe-area padding on keyboard visibility (#5988): the + // back gesture closes the keyboard while the editor stays focused, and a + // focus-keyed inset would leave the toolbar under the gesture bar. iOS must + // NOT use visibility — it only flips on keyboardDidHide, after the hide + // animation, so the composer would ride down flush to the screen edge and + // then snap up into the inset. On iOS blur precedes the hide, so the + // focus-keyed inset is already in place while the composer rides down. + const composerBottomInset = (Platform.OS === "android" ? isKeyboardVisible : composerExpanded) + ? 0 + : Math.max(insets.bottom, 12); const contentPresentationKind = props.contentPresentation.kind; // The raw sync status enters "synchronizing" on every full fetch, cached or // not. Whether messages are already on screen decides the pill label: no @@ -209,6 +296,41 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread const selectedThreadFeed = props.selectedThreadFeed; const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME; const composerOverlapHeight = composerChrome + composerBottomInset; + // While a user-input request is pending, the questionnaire owns the + // composer slot outright: expanded it is the full card, collapsed it is a + // composer-style bar in the same place (with its own stop control). The + // composer never mounts into the transition, which keeps the collapse and + // keyboard animations coherent. Collapse state is keyed by request id so a + // new request re-expands automatically. + const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] = + useState(null); + const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null; + const userInputCollapsed = + activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId; + // The card's height RESERVES keyboard space at all times instead of + // tracking the keyboard: transforms (the sticky translation) apply + // same-frame on the UI thread while layout props lag a Yoga pass behind, + // so any height that follows the keyboard flashes the card over the nav + // header on the way up. With a constant height the keyboard transition is + // pure translation — frame-perfect by construction — and the resting card + // stays compact over the transcript. Before the first open the reserve is + // an estimate; once a real height is known the card corrects once, + // discretely. + const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0); + useEffect(() => { + if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) { + setLastKnownKeyboardHeight(liveKeyboardHeight); + } + }, [lastKnownKeyboardHeight, liveKeyboardHeight]); + const pendingUserInputMaxHeight = derivePendingUserInputMaxHeight({ + windowHeight, + keyboardHeight: + lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT, + navigationHeaderHeight, + // The questionnaire owns the composer slot, so only the composer's + // bottom inset still overlaps. + composerOverlapHeight: composerBottomInset, + }); const estimatedOverlayHeight = composerOverlapHeight; // The overlay's measured height includes the home-indicator inset (the // composer pads it), but contentInsetAdjustmentBehavior="automatic" makes @@ -225,7 +347,103 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread Math.max(0, estimatedOverlayHeight - nativeInsetOvercount), -nativeInsetOvercount, ); + // The expanded questionnaire is an absolute overlay on iOS, so it never + // changes the measured overlay height (that constancy is what keeps the + // feed from snapping on collapse/expand). The toggle choreography runs on + // SHARED VALUES set directly in the tap handler — one JS hop, then the + // card's rise/sink and the feed's end-inset glide animate in lockstep on + // the UI thread, keyboard-style, instead of waiting on React mount + + // onLayout + state round trips. Coverage (how far the card extends above + // the bar) is measured straight into a shared value by the card's + // onLayout, with no re-render. + const userInputCardProgress = useSharedValue(1); + const userInputInsetProgress = useSharedValue(1); + const userInputCardCoverage = useSharedValue(0); + // Android renders the expanded card in-flow (it cannot hit-test the iOS + // overlay outside the bar's bounds), so its measured overlay height already + // includes the card — the coverage extra is iOS-only. + const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null; + const combinedContentInsetEndAdjustment = useSharedValue( + Math.max(0, estimatedOverlayHeight - nativeInsetOvercount), + ); + useAnimatedReaction( + () => + contentInsetEndAdjustment.value + + (userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0), + (value) => { + combinedContentInsetEndAdjustment.value = value; + }, + [userInputCoverageApplies], + ); const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef }); + const endFollowEnabledRef = useRef(true); + endFollowEnabledRef.current = endFollowEnabled; + const userInputRepinTimerRef = useRef | null>(null); + // The list's own corrections for these inset changes drift on short + // content (and the error compounds across toggles), so deterministically + // re-pin the end once a toggle settles: a no-op when the resting position + // is already right, corrective when it is not. Follow state is re-checked + // inside the callback — the user may grab the list during the settle + // window, and yanking them back would override a live gesture. + const scheduleUserInputRepin = useCallback( + (delayMs: number) => { + if (userInputRepinTimerRef.current !== null) { + clearTimeout(userInputRepinTimerRef.current); + } + userInputRepinTimerRef.current = setTimeout(() => { + userInputRepinTimerRef.current = null; + if (!endFollowEnabledRef.current) { + return; + } + void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => { + freeze.set(false); + }); + }, delayMs); + }, + [freeze, scrollMessageToEnd], + ); + useEffect( + () => () => { + if (userInputRepinTimerRef.current !== null) { + clearTimeout(userInputRepinTimerRef.current); + } + }, + [], + ); + const handleToggleUserInputCollapsed = useCallback(() => { + if (activeUserInputRequestId === null) { + return; + } + if (userInputCollapsed) { + // Expanding: card and feed glide start NOW, on the UI thread. + userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING); + userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING); + setCollapsedUserInputRequestId(null); + scheduleUserInputRepin(USER_INPUT_TOGGLE_DURATION_MS + 50); + } else { + // Collapsing hides the custom-answer inputs; release the keyboard with + // them instead of leaving it up over a dead responder. + Keyboard.dismiss(); + userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING); + // Instant: the sinking card still covers the strip being revealed, and + // animating the inset downward is what drifted the short-content end + // anchor. + userInputInsetProgress.value = 0; + setCollapsedUserInputRequestId(activeUserInputRequestId); + scheduleUserInputRepin(60); + } + }, [ + activeUserInputRequestId, + scheduleUserInputRepin, + userInputCardProgress, + userInputCollapsed, + userInputInsetProgress, + ]); + useEffect(() => { + // A new request always arrives expanded. + userInputCardProgress.value = 1; + userInputInsetProgress.value = 1; + }, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]); const showContent = props.showContent ?? true; const layoutVariant = props.layoutVariant ?? "compact"; const isSplitLayout = layoutVariant === "split"; @@ -279,6 +497,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread useEffect(() => { setAnchorMessageId(null); lastScrolledAnchorMessageIdRef.current = null; + setEndFollowEnabled(true); freeze.set(false); }, [freeze, selectedThreadKey]); @@ -350,6 +569,16 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread composerEditorRef.current?.blur(); }, []); + const handleScrollToEnd = useCallback(() => { + void Haptics.selectionAsync(); + void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => { + freeze.set(false); + }); + }, [freeze, scrollMessageToEnd]); + + const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled; + const isDarkMode = useColorScheme() === "dark"; + const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => { feedTouchStartRef.current = { pageX: event.nativeEvent.pageX, @@ -404,7 +633,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread listRef={listRef} freeze={freeze} anchorMessageId={anchorMessageId} - contentInsetEndAdjustment={contentInsetEndAdjustment} + contentInsetEndAdjustment={combinedContentInsetEndAdjustment} contentTopInset={0} contentBottomInset={estimatedOverlayHeight} contentMaxWidth={contentMaxWidth} @@ -417,6 +646,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread layoutVariant={layoutVariant} usesAutomaticContentInsets={props.usesAutomaticContentInsets} onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange} + onEndFollowEnabledChange={setEndFollowEnabled} skills={selectedProviderSkills} /> @@ -427,6 +657,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread {/* Floating composer — sticks to keyboard via KeyboardStickyView */} {showContent ? ( @@ -434,6 +668,49 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread list's bottom inset, so any padding above the pill/composer pushes the resting content floor up by the same amount. */} + {showScrollToEndButton ? ( + + {isLiquidGlassSupported ? ( + + + + ) : ( + + )} + + ) : null} @@ -456,6 +740,13 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread {props.activePendingUserInput ? ( - + {/* Hidden (not unmounted) while a user-input request owns the + composer slot, so composer drafts and editor state survive. */} + + + ) : null} diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index fd11bc58d1..72c1c4e1ea 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -65,6 +65,7 @@ import Animated, { import { useThemeColor } from "../../lib/useThemeColor"; import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics"; import { useFontFamily } from "../../lib/useFontFamily"; +import { scopedThreadKey } from "../../lib/scopedEntities"; import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic"; import { hasWideMarkdownBlock } from "../../lib/wideMarkdownBlocks"; import { @@ -108,6 +109,10 @@ import { type ThreadFeedLatestRun, } from "../../lib/threadActivity"; import type { ThreadContentPresentation } from "./threadContentPresentation"; +import { + resolveThreadFeedLiveFollow, + type ThreadFeedLiveFollowEvent, +} from "./thread-feed-live-follow"; import { collapsedWorkLogHeight, ThreadWorkGroupToggle, @@ -188,6 +193,7 @@ export interface ThreadFeedProps { readonly layoutVariant?: LayoutVariant; readonly usesAutomaticContentInsets?: boolean; readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void; + readonly onEndFollowEnabledChange?: (enabled: boolean) => void; readonly skills?: ReadonlyArray; } @@ -1483,6 +1489,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const foldSettleFrameRef = useRef(null); const foldSettleSecondFrameRef = useRef(null); const previousLatestTurnRef = useRef(props.latestRun); + const userScrollSettleTimerRef = useRef | null>(null); const disclosureAnchorKeyRef = useRef(null); const headerMaterialVisibleRef = useRef(false); const { width: windowWidth } = useWindowDimensions(); @@ -1503,13 +1510,23 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { // momentum; only motion inside a session can break follow, so MVCP // compensations and programmatic scrolls never strand a follower. const userScrollSessionRef = useRef(false); - const setEndFollow = useCallback((enabled: boolean) => { - if (endFollowEnabledRef.current === enabled) { - return; - } - endFollowEnabledRef.current = enabled; - setEndFollowEnabled(enabled); - }, []); + const setEndFollow = useCallback( + (enabled: boolean) => { + if (endFollowEnabledRef.current === enabled) { + return; + } + endFollowEnabledRef.current = enabled; + setEndFollowEnabled(enabled); + props.onEndFollowEnabledChange?.(enabled); + }, + [props.onEndFollowEnabledChange], + ); + const transitionEndFollow = useCallback( + (event: ThreadFeedLiveFollowEvent) => { + setEndFollow(resolveThreadFeedLiveFollow(endFollowEnabledRef.current, event)); + }, + [setEndFollow], + ); const [interactionState, setInteractionState] = useState<{ readonly copiedRowId: string | null; readonly expandedWorkGroups: Record; @@ -1631,53 +1648,98 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent; nearListEnd.value = contentSize.height - layoutMeasurement.height - contentOffset.y < layoutMeasurement.height; - // Latch bookkeeping. LegendList recomputes its inset-aware end distance - // before invoking this handler, so getState() is current. Returning to - // the end re-arms follow no matter who scrolled (the user, or our own - // scroll-to-end); moving away breaks it only during a user-initiated - // scroll session, so MVCP compensations and programmatic repositioning - // can never strand a follower. + // LegendList recomputes its inset-aware end distance before invoking + // this handler, so getState() is current. Only the actual end re-arms + // follow: its broader maintain-scroll threshold is large enough for a + // streaming chunk to pull a user back before their upward drag escapes. + // A live user-scroll session still wins even if the first scroll event + // remains inside LegendList's at-end tolerance. const listState = props.listRef.current?.getState(); if (listState) { - if (listState.isWithinMaintainScrollAtEndThreshold) { - setEndFollow(true); - } else if (userScrollSessionRef.current) { - setEndFollow(false); - } + transitionEndFollow({ + type: "scroll", + isAtEnd: listState.isAtEnd, + userScrollSessionActive: userScrollSessionRef.current, + }); } }, - [reportHeaderMaterialVisibility, anchorTopInset, nearListEnd, props.listRef, setEndFollow], + [ + reportHeaderMaterialVisibility, + anchorTopInset, + nearListEnd, + props.listRef, + transitionEndFollow, + ], ); - const handleScrollBeginDrag = useCallback(() => { - userScrollSessionRef.current = true; - }, []); - // The session must survive past finger-lift so momentum that carries the - // user away from the end still breaks follow; a drag released with no - // momentum ends its session at the release itself, otherwise at momentum - // end. Leaving a session open would let a later animated maintain-scroll - // read as user motion and break follow spuriously. - const handleScrollEndDrag = useCallback((event: NativeSyntheticEvent) => { - const velocity = event.nativeEvent.velocity?.y ?? 0; - if (Math.abs(velocity) < 0.05) { - userScrollSessionRef.current = false; + const clearUserScrollSettle = useCallback(() => { + if (userScrollSettleTimerRef.current !== null) { + clearTimeout(userScrollSettleTimerRef.current); + userScrollSettleTimerRef.current = null; } }, []); + const handleScrollBeginDrag = useCallback(() => { + clearUserScrollSettle(); + userScrollSessionRef.current = true; + // 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" }); + }, [clearUserScrollSettle, transitionEndFollow]); + const finishUserScroll = useCallback( + (releaseIsAtEnd?: boolean) => { + clearUserScrollSettle(); + const userScrollSessionActive = userScrollSessionRef.current; + userScrollSessionRef.current = false; + transitionEndFollow({ + type: "user-scroll-end", + // With no momentum, preserve the finger-release position. Streaming + // growth during the native momentum-detection window must not turn a + // release at the live edge into an opt-out from follow. + isAtEnd: releaseIsAtEnd ?? props.listRef.current?.getState().isAtEnd ?? false, + userScrollSessionActive, + }); + }, + [clearUserScrollSettle, props.listRef, transitionEndFollow], + ); + // Finger-lift velocity is not a reliable momentum signal: a gentle fling + // can report zero and still decelerate. Give native momentum a short window + // to announce itself; if it does, onMomentumScrollBegin cancels this fallback + // and the session survives until the settled momentum-end position. This + // mirrors the native-event handoff used by the home thread list's scroll gate. + const handleScrollEndDrag = useCallback(() => { + clearUserScrollSettle(); + const releaseIsAtEnd = props.listRef.current?.getState().isAtEnd ?? false; + userScrollSettleTimerRef.current = setTimeout(() => finishUserScroll(releaseIsAtEnd), 160); + }, [clearUserScrollSettle, finishUserScroll, props.listRef]); + const handleMomentumScrollBegin = useCallback(() => { + if (userScrollSessionRef.current) { + clearUserScrollSettle(); + } + }, [clearUserScrollSettle]); const handleMomentumScrollEnd = useCallback(() => { - userScrollSessionRef.current = false; - }, []); + finishUserScroll(); + }, [finishUserScroll]); + + useEffect(() => clearUserScrollSettle, [clearUserScrollSettle]); + + // Thread identity is env-scoped: two environments can hold the same + // ThreadId, and keying resets (or the list mount) on the bare id would + // carry stale scroll/follow state across an environment switch. + const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId); // A thread switch opens pinned to the end; a send explicitly returns to the // live edge (ThreadDetailScreen scrolls the new message into place). Both // re-arm follow regardless of where the user had scrolled before. useEffect(() => { + clearUserScrollSettle(); userScrollSessionRef.current = false; - setEndFollow(true); - }, [props.threadId, setEndFollow]); + transitionEndFollow({ type: "reset" }); + }, [clearUserScrollSettle, feedThreadKey, transitionEndFollow]); useEffect(() => { if (props.anchorMessageId !== null) { + clearUserScrollSettle(); userScrollSessionRef.current = false; - setEndFollow(true); + transitionEndFollow({ type: "reset" }); } - }, [props.anchorMessageId, setEndFollow]); + }, [clearUserScrollSettle, props.anchorMessageId, transitionEndFollow]); // Gated variant of the 180ms feed layout slide. Instant while browsing // history: maintainVisibleContentPosition compensates the scroll offset in @@ -1715,7 +1777,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { useEffect(() => { reportHeaderMaterialVisibility(false); - }, [props.threadId, reportHeaderMaterialVisibility]); + }, [feedThreadKey, reportHeaderMaterialVisibility]); const presentedFeed = useMemo( () => @@ -1740,7 +1802,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { // initial scroll-to-end computes with a zero end inset and rests one // composer-height short of the end. Layout effect: it must land before the // list's first positioning tick or the one-shot initial scroll misses it. - const listMountKey = `${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`; + const listMountKey = `${feedThreadKey}:${props.feed.length === 0 ? "empty" : "filled"}`; useLayoutEffect(() => { const bottom = props.contentInsetEndAdjustment.value; if (bottom > 0) { @@ -2112,6 +2174,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { onScroll={handleScroll} onScrollBeginDrag={handleScrollBeginDrag} onScrollEndDrag={handleScrollEndDrag} + onMomentumScrollBegin={handleMomentumScrollBegin} onMomentumScrollEnd={handleMomentumScrollEnd} scrollEventThrottle={16} ListHeaderComponent={ diff --git a/apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx b/apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx index 569093d3c4..dec61bc94a 100644 --- a/apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx +++ b/apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx @@ -115,7 +115,10 @@ export function ThreadRelationshipsBanner(props: { setVisible(false); void Haptics.selectionAsync(); if (archivedThread) { - navigation.navigate("SettingsSheet", { screen: "SettingsArchive" }); + navigation.navigate("SettingsSheet", { + screen: "SettingsContent", + params: { screen: "SettingsArchive" }, + }); return; } navigation.navigate("Thread", { diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 38e15e4619..d9ff685c67 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -15,6 +15,10 @@ import { threadFeedRunIsUnsettled, type ThreadFeedActivity, type ThreadFeedEntry, + togglePendingUserInputOptionSelection, + setPendingUserInputCustomAnswer, + isPendingUserInputOptionSelected, + buildPendingUserInputAnswers, } from "./threadActivity"; const threadId = ThreadId.make("thread-1"); @@ -409,3 +413,94 @@ describe("buildThreadFeed", () => { expect(activity?.getCopyText().split("\n")[0]).toBe("Read a T3 thread"); }); }); + +const singleSelectQuestion = { + id: "runtime", + header: "Runtime", + question: "Which runtime should be used?", + options: [ + { label: "Go", description: "One binary" }, + { label: "Node.js", description: "Reuse TypeScript" }, + ], + multiSelect: false, +} as const; + +const multiSelectQuestion = { + id: "scope", + header: "Scope", + question: "Which data should be collected?", + options: [ + { label: "Orders", description: "Receipts" }, + { label: "Listings", description: "Inventory" }, + ], + multiSelect: true, +} as const; + +describe("pending user input answers", () => { + it("replaces single-select options and toggles multi-select options", () => { + expect( + togglePendingUserInputOptionSelection( + singleSelectQuestion, + { selectedOptionLabels: ["Go"] }, + "Node.js", + ), + ).toEqual({ customAnswer: "", selectedOptionLabels: ["Node.js"] }); + + const orders = togglePendingUserInputOptionSelection(multiSelectQuestion, undefined, "Orders"); + const ordersAndListings = togglePendingUserInputOptionSelection( + multiSelectQuestion, + orders, + "Listings", + ); + expect(ordersAndListings).toEqual({ + customAnswer: "", + selectedOptionLabels: ["Orders", "Listings"], + }); + expect( + togglePendingUserInputOptionSelection(multiSelectQuestion, ordersAndListings, "Orders"), + ).toEqual({ customAnswer: "", selectedOptionLabels: ["Listings"] }); + + const paddedOrders = togglePendingUserInputOptionSelection( + multiSelectQuestion, + undefined, + " Orders ", + ); + expect(paddedOrders).toEqual({ customAnswer: "", selectedOptionLabels: ["Orders"] }); + expect( + togglePendingUserInputOptionSelection(multiSelectQuestion, paddedOrders, " Orders "), + ).toEqual({ customAnswer: "" }); + }); + + it("builds array answers for multi-select questions", () => { + expect( + buildPendingUserInputAnswers([singleSelectQuestion, multiSelectQuestion], { + runtime: { selectedOptionLabels: ["Go"] }, + scope: { selectedOptionLabels: ["Orders", "Listings"] }, + }), + ).toEqual({ + runtime: "Go", + scope: ["Orders", "Listings"], + }); + }); + + it("clears selected options while a custom answer is active", () => { + expect( + setPendingUserInputCustomAnswer( + { selectedOptionLabels: ["Orders", "Listings"] }, + "Orders first", + ), + ).toEqual({ customAnswer: "Orders first" }); + }); + + it("matches selected chips against normalized option labels", () => { + expect( + isPendingUserInputOptionSelected({ selectedOptionLabels: ["Orders"] }, " Orders "), + ).toBe(true); + expect( + isPendingUserInputOptionSelected( + { selectedOptionLabels: ["Orders"], customAnswer: "Orders first" }, + " Orders ", + ), + ).toBe(false); + }); +}); diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 6742b60bf0..93b29eded2 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -30,7 +30,7 @@ export type PendingUserInput = ThreadPendingUserInput; const MAX_VISIBLE_WORK_LOG_ENTRIES = 1; export interface PendingUserInputDraftAnswer { - readonly selectedOptionLabel?: string; + readonly selectedOptionLabels?: ReadonlyArray; readonly customAnswer?: string; } @@ -141,14 +141,34 @@ function normalizeDraftAnswer(value: string | undefined): string | null { return trimmed.length > 0 ? trimmed : null; } -function resolvePendingUserInputAnswer( - draft: PendingUserInputDraftAnswer | undefined, -): string | null { - return ( - normalizeDraftAnswer(draft?.customAnswer) ?? normalizeDraftAnswer(draft?.selectedOptionLabel) +function normalizeSelectedOptionLabels( + value: ReadonlyArray | undefined, +): ReadonlyArray { + if (!Array.isArray(value)) { + return []; + } + + return Array.from( + new Set(value.map((entry) => entry.trim()).filter((entry) => entry.length > 0)), ); } +function resolvePendingUserInputAnswer( + question: ThreadUserInputQuestion, + draft: PendingUserInputDraftAnswer | undefined, +): string | ReadonlyArray | null { + const customAnswer = normalizeDraftAnswer(draft?.customAnswer); + if (customAnswer) { + return customAnswer; + } + + const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels); + if (question.multiSelect) { + return selectedOptionLabels.length > 0 ? selectedOptionLabels : null; + } + return selectedOptionLabels[0] ?? null; +} + function capitalizePhrase(value: string): string { const trimmed = value.trim(); return trimmed.length === 0 ? value : `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`; @@ -655,19 +675,65 @@ export function setPendingUserInputCustomAnswer( draft: PendingUserInputDraftAnswer | undefined, customAnswer: string, ): PendingUserInputDraftAnswer { - const selectedOptionLabel = - customAnswer.trim().length > 0 ? undefined : draft?.selectedOptionLabel; - return { customAnswer, ...(selectedOptionLabel ? { selectedOptionLabel } : {}) }; + const selectedOptionLabels = + customAnswer.trim().length > 0 + ? undefined + : normalizeSelectedOptionLabels(draft?.selectedOptionLabels); + return { + customAnswer, + ...(selectedOptionLabels && selectedOptionLabels.length > 0 ? { selectedOptionLabels } : {}), + }; +} + +export function isPendingUserInputOptionSelected( + draft: PendingUserInputDraftAnswer | undefined, + optionLabel: string, +): boolean { + if (normalizeDraftAnswer(draft?.customAnswer)) { + return false; + } + + return normalizeSelectedOptionLabels(draft?.selectedOptionLabels).includes(optionLabel.trim()); +} + +export function togglePendingUserInputOptionSelection( + question: ThreadUserInputQuestion, + draft: PendingUserInputDraftAnswer | undefined, + optionLabel: string, +): PendingUserInputDraftAnswer { + const normalizedOptionLabel = optionLabel.trim(); + + if (question.multiSelect) { + const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels); + const nextSelectedOptionLabels = selectedOptionLabels.includes(normalizedOptionLabel) + ? selectedOptionLabels.filter((label) => label !== normalizedOptionLabel) + : [...selectedOptionLabels, normalizedOptionLabel]; + + return { + customAnswer: "", + ...(nextSelectedOptionLabels.length > 0 + ? { selectedOptionLabels: nextSelectedOptionLabels } + : {}), + }; + } + + return { + customAnswer: "", + selectedOptionLabels: [normalizedOptionLabel], + }; } export function buildPendingUserInputAnswers( questions: ReadonlyArray, draftAnswers: Record, -): Record | null { - const answers: Record = {}; +): Record> | null { + const answers: Record> = {}; + for (const question of questions) { - const answer = resolvePendingUserInputAnswer(draftAnswers[question.id]); - if (!answer) return null; + const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]); + if (!answer) { + return null; + } answers[question.id] = answer; } return answers; diff --git a/apps/mobile/src/state/use-selected-thread-requests.ts b/apps/mobile/src/state/use-selected-thread-requests.ts index d15646a24f..c7c6c02fa2 100644 --- a/apps/mobile/src/state/use-selected-thread-requests.ts +++ b/apps/mobile/src/state/use-selected-thread-requests.ts @@ -2,7 +2,10 @@ import { useAtomValue } from "@effect/atom-react"; import { useCallback, useMemo, useState } from "react"; import { type ProviderApprovalDecision, type RuntimeRequestId } from "@t3tools/contracts"; -import { derivePendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests"; +import { + derivePendingThreadRequests, + type ThreadUserInputQuestion, +} from "@t3tools/client-runtime/state/thread-requests"; import { Atom } from "effect/unstable/reactivity"; import { threadEnvironment } from "../state/threads"; @@ -10,6 +13,7 @@ import { scopedRequestKey } from "../lib/scopedEntities"; import { buildPendingUserInputAnswers, setPendingUserInputCustomAnswer, + togglePendingUserInputOptionSelection, type PendingUserInputDraftAnswer, } from "../lib/threadActivity"; import { appAtomRegistry } from "./atom-registry"; @@ -21,15 +25,21 @@ const userInputDraftsByRequestKeyAtom = Atom.make< Record> >({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts")); -function setUserInputDraftOption(requestKey: string, questionId: string, label: string): void { +function setUserInputDraftOption( + requestKey: string, + question: ThreadUserInputQuestion, + label: string, +): void { const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom); appAtomRegistry.set(userInputDraftsByRequestKeyAtom, { ...current, [requestKey]: { ...current[requestKey], - [questionId]: { - selectedOptionLabel: label, - }, + [question.id]: togglePendingUserInputOptionSelection( + question, + current[requestKey]?.[question.id], + label, + ), }, }); } @@ -89,13 +99,13 @@ export function useSelectedThreadRequests() { : null; const onSelectUserInputOption = useCallback( - (requestId: RuntimeRequestId, questionId: string, label: string) => { + (requestId: RuntimeRequestId, question: ThreadUserInputQuestion, label: string) => { if (!selectedThreadShell) { return; } const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId); - setUserInputDraftOption(requestKey, questionId, label); + setUserInputDraftOption(requestKey, question, label); }, [selectedThreadShell], ); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 695adb0674..22fa9f17c0 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -278,8 +278,6 @@ import { import { resolveThreadPr } from "./ThreadStatusIndicators"; import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack"; import { QueuedRunsControl } from "./chat/QueuedRunsControl"; -import { resolveThreadPr } from "./ThreadStatusIndicators"; -import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack"; import { DRAFT_HERO_TRANSITION_ANIMATION_ID, DRAFT_HERO_TRANSITION_DURATION_MS, diff --git a/apps/web/src/components/chat/ComposerPrimaryActions.test.ts b/apps/web/src/components/chat/ComposerPrimaryActions.test.ts index 3dbcd39e9d..bae8a88f71 100644 --- a/apps/web/src/components/chat/ComposerPrimaryActions.test.ts +++ b/apps/web/src/components/chat/ComposerPrimaryActions.test.ts @@ -32,7 +32,6 @@ function renderPendingActions(isRunning: boolean) { showPlanFollowUpPrompt: false, promptHasText: false, isSendBusy: false, - sendDisabledReason: null, isConnecting: false, isEnvironmentUnavailable: false, isPreparingWorktree: false, @@ -53,7 +52,6 @@ function renderStandaloneStop() { showPlanFollowUpPrompt: false, promptHasText: false, isSendBusy: false, - sendDisabledReason: null, isConnecting: false, isEnvironmentUnavailable: false, isPreparingWorktree: false, @@ -74,7 +72,6 @@ function renderSendButton() { showPlanFollowUpPrompt: false, promptHasText: true, isSendBusy: false, - sendDisabledReason: null, isConnecting: false, isEnvironmentUnavailable: false, isPreparingWorktree: false, @@ -216,3 +213,46 @@ describe("ComposerPrimaryActions", () => { expect(markup).toContain("bg-message-action text-message-action-foreground"); }); }); + +const activeTurnProps = { + compact: false, + pendingAction: null, + showPlanFollowUpPrompt: false, + promptHasText: false, + isSendBusy: false, + isConnecting: false, + isEnvironmentUnavailable: false, + isPreparingWorktree: false, + preserveComposerFocusOnPointerDown: false, + onPreviousPendingQuestion: () => {}, + onInterrupt: () => {}, + onImplementPlanInNewThread: () => {}, +} as const; + +describe("active-turn primary action", () => { + it("shows stop while the active composer is empty", () => { + const markup = renderToStaticMarkup( + createElement(ComposerPrimaryActions, { + ...activeTurnProps, + isRunning: true, + hasSendableContent: false, + }), + ); + + expect(markup).toContain('aria-label="Stop generation"'); + expect(markup).not.toContain("steer active turn"); + }); + + it("replaces stop with send while the active composer has content", () => { + const markup = renderToStaticMarkup( + createElement(ComposerPrimaryActions, { + ...activeTurnProps, + isRunning: true, + hasSendableContent: true, + }), + ); + + expect(markup).toContain('aria-label="Send message to steer active turn"'); + expect(markup).not.toContain('aria-label="Stop generation"'); + }); +}); diff --git a/apps/web/src/components/chat/ComposerPrimaryActions.tsx b/apps/web/src/components/chat/ComposerPrimaryActions.tsx index 88d7f8d680..5880f3f894 100644 --- a/apps/web/src/components/chat/ComposerPrimaryActions.tsx +++ b/apps/web/src/components/chat/ComposerPrimaryActions.tsx @@ -75,7 +75,6 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ ? { onPointerDown: preventPointerFocus } : undefined; const environmentIdentificationMode = useEnvironmentIdentificationMode(); - const isSendDisabled = sendDisabledReason !== null; const stageBackdropVariant = useSidebarStageBackdropVariant( environmentIdentificationMode === "artwork", ); @@ -150,19 +149,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ } if (isRunning && !hasSendableContent) { - return ( - - ); + return renderStopGenerationButton(false); } if (showPlanFollowUpPrompt) { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8dfe5aff5e..fa05c09ee1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -11813,11 +11813,6 @@ snapshots: '@cursor/sdk-linux-x64': 1.0.22 '@cursor/sdk-win32-x64': 1.0.22 - '@develar/schema-utils@2.6.5': - dependencies: - ajv: 6.15.0 - ajv-keywords: 3.5.2(ajv@6.15.0) - '@distilled.cloud/aws@0.30.2(effect@4.0.0-beta.103(patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))': dependencies: '@aws-crypto/crc32': 5.2.0