import type { EnvironmentId, MessageId, ModelSelection, OrchestrationThreadShell, ProviderInteractionMode, RuntimeMode, ServerConfig as T3ServerConfig, } from "@t3tools/contracts"; import { detectComposerTrigger, replaceTextRange, serializeComposerFileLink, type ComposerTrigger, } from "@t3tools/shared/composerTrigger"; import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native"; import type { ReactNode } from "react"; import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react"; import { ActivityIndicator, Image, Platform, Pressable, StyleSheet, View, type ViewStyle, } from "react-native"; import ImageViewing from "react-native-image-viewing"; import Animated, { FadeIn, FadeInDown, FadeOut, FadeOutDown, LinearTransition, } from "react-native-reanimated"; import { useThemeColor } from "../../lib/useThemeColor"; import { themeColorWithAlpha } from "../../lib/mobileTheme"; import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration"; import { scopedThreadKey } from "../../lib/scopedEntities"; import { AppText as Text } from "../../components/AppText"; import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip"; import { GlassSurface } from "../../components/GlassSurface"; import { ComposerEditor, type ComposerEditorHandle, type ComposerEditorSelection, } from "../../components/ComposerEditor"; import { ComposerInlineControl, ComposerToolbarButton, ComposerToolbarRow, ComposerToolbarScroller, } from "../../components/ComposerToolbar"; import { ControlPill } from "../../components/ControlPill"; import { ProviderIcon } from "../../components/ProviderIcon"; import type { DraftComposerImageAttachment } from "../../lib/composerImages"; import { buildModelOptions, groupByProvider } from "../../lib/modelOptions"; import { useScaledTextRole } from "../settings/appearance/useScaledTextRole"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; import type { RemoteClientConnectionState } from "../../lib/connection"; import { insertRankedSearchResult, normalizeSearchQuery, scoreQueryMatch, } from "@t3tools/shared/searchRanking"; import { resolveProviderOptionDescriptors } from "../../lib/providerOptions"; import { useComposerPathSearch } from "../../state/use-composer-path-search"; import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover"; import { type ExistingThreadSettingsRouteSession, useExistingThreadSettingsRoutePresentation, } from "./ThreadSettingsSheet"; import { useThreadSettingsSheetPresentation, type NavigationWithFinishTransitioning, } from "./use-thread-settings-sheet-presentation"; /** * Height of the collapsed composer (pill + vertical padding, excluding safe-area inset). * Exported so the parent can compute feed overlap / content insets. */ export const COMPOSER_COLLAPSED_CHROME = 60; /** * Height of the expanded composer (card + toolbar + vertical padding, excluding safe-area inset). * Used by the parent to compute the larger feed bottom inset when the composer is focused. */ export const COMPOSER_EXPANDED_CHROME = 156; export interface ThreadComposerProps { readonly draftMessage: string; readonly draftAttachments: ReadonlyArray; readonly placeholder: string; readonly contentMaxWidth?: number; readonly bottomInset?: number; readonly connectionState: RemoteClientConnectionState; readonly connectionError: string | null; readonly environmentLabel: string | null; /** * Message sync phase for the selected thread (drives the status pill): * "loading" = first fetch, nothing to show yet; "syncing" = cached messages * are on screen while they reconcile with the server. */ readonly threadSyncPhase?: "loading" | "syncing" | null; readonly selectedThread: OrchestrationThreadShell; readonly serverConfig: T3ServerConfig | null; readonly queueCount: number; readonly environmentId: EnvironmentId; readonly projectCwd: string | null; readonly editorRef?: RefObject; readonly onChangeDraftMessage: (value: string) => void; readonly onPickDraftImages: () => Promise; readonly onNativePasteImages: (uris: ReadonlyArray) => Promise; readonly onRemoveDraftImage: (imageId: string) => void; readonly onStopThread: () => void; readonly onSendMessage: () => Promise; readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void; readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void; 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; } /** * The pill / card container — renders with Expo's native GlassView on supported * iOS 26+ devices and keeps the existing opaque fallback elsewhere. * Exported so NewTaskDraftScreen can render the same composer chrome. */ // One timing for every piece of the expanded↔compact morph so the surface, // toolbar, and siblings move together instead of popping between layouts. // Android gets NO layout transition: the composer rides the keyboard via // KeyboardStickyView (frame-synced to the IME), and a time-based morph // running alongside that translate reads as jitter. Snapping the layout and // letting the keyboard-synced slide be the only motion looks native there. const COMPOSER_LAYOUT_TRANSITION = Platform.OS === "android" ? undefined : LinearTransition.duration(220); export function ComposerSurface(props: { readonly children: ReactNode; readonly style: ViewStyle; readonly isDarkMode: boolean; /** Existing thread composers morph between pill and card layouts. */ readonly animateLayout?: boolean; }) { const cardColor = useThemeColor("--color-card-translucent"); const borderColor = useThemeColor("--color-border"); const shadowColor = useThemeColor("--color-primary-shadow"); // Drop shadow lives on a wrapper: `overflow: "hidden"` on the surface itself // (needed to clip content to the pill shape) would clip the shadow on iOS. const shadowStyle: ViewStyle = { borderRadius: props.style.borderRadius, shadowColor, shadowOpacity: props.isDarkMode ? 0.35 : 0.12, shadowRadius: 14, shadowOffset: { width: 0, height: 6 }, elevation: 10, }; return ( {props.children} ); } type ComposerStatusPillState = { readonly kind: "unavailable" | "reconnecting" | "syncing"; readonly label: string; }; function composerConnectionStatus(input: { readonly connectionError: string | null; readonly connectionState: RemoteClientConnectionState; readonly environmentLabel: string | null; readonly threadSyncPhase?: "loading" | "syncing" | null; }): ComposerStatusPillState | null { const environmentLabel = input.environmentLabel ?? "Environment"; switch (input.connectionState) { case "connecting": case "reconnecting": return { kind: "reconnecting", label: input.connectionError === null ? `Reconnecting to ${environmentLabel}...` : `Failed to connect. Retrying ${environmentLabel}...`, }; case "offline": return { kind: "unavailable", label: "You are offline" }; case "error": return { kind: "unavailable", label: input.connectionError ? `Failed to connect to ${environmentLabel}: ${input.connectionError}` : `Failed to connect to ${environmentLabel}`, }; case "available": return { kind: "unavailable", label: `${environmentLabel} is not connected` }; case "connected": break; } // Connected: the pill is the single loading/sync indicator. One stable // label per open — "Loading" when starting from scratch, "Syncing" when // cached messages are already visible. switch (input.threadSyncPhase) { case "loading": return { kind: "syncing", label: "Loading messages..." }; case "syncing": return { kind: "syncing", label: "Syncing messages..." }; default: return null; } } const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(props: { readonly onPress: () => void; readonly status: ComposerStatusPillState; }) { const isReconnecting = props.status.kind !== "unavailable"; const indicatorColor = useThemeColor("--color-icon-muted"); return ( {isReconnecting ? ( ) : ( )} {props.status.label} ); }); export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) { const navigation = useNavigation(); const { themeAppearance } = useAppearancePreferences(); const isDarkMode = themeAppearance === "dark"; const foregroundColor = useThemeColor("--color-foreground"); const bodyText = useScaledTextRole("body"); const fallbackInputRef = useRef(null); const inputRef = props.editorRef ?? fallbackInputRef; const [isFocused, setIsFocused] = useState(false); const settingsSheetPresentation = useThreadSettingsSheetPresentation({ editorRef: inputRef, isEditorFocused: isFocused, }); const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation(); const settingsRoutePresentedRef = useRef(false); const wasExpandedBeforePreviewRef = useRef(false); const inFlightThreadIdsRef = useRef(new Set()); const { onExpandedChange } = props; const [previewImageUri, setPreviewImageUri] = useState(null); const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0; // Opening and presentation count as active so the composer stays expanded // while focus moves between its native editor and the settings picker. const isExpanded = isFocused || settingsSheetPresentation.isActive; const canSend = hasContent; // Notify the parent from the derived value, not focus events: the parent // sizes the feed inset from this, and blur-during-sheet would otherwise // report collapsed while the composer still renders expanded. useEffect(() => { onExpandedChange?.(isExpanded); }, [isExpanded, onExpandedChange]); const onPressImage = useCallback( (uri: string) => { wasExpandedBeforePreviewRef.current = isFocused; setPreviewImageUri(uri); }, [isFocused], ); const closePreview = useCallback(() => { setPreviewImageUri(null); if (wasExpandedBeforePreviewRef.current) { setTimeout(() => inputRef.current?.focus(), 100); } }, [inputRef]); const onEditorFocusChange = props.onEditorFocusChange; const handleFocus = useCallback(() => { setIsFocused(true); onEditorFocusChange?.(true); }, [onEditorFocusChange]); const handleBlur = useCallback(() => { setIsFocused(false); onEditorFocusChange?.(false); }, [onEditorFocusChange]); const showStopAction = props.selectedThread.session?.status === "running" || props.selectedThread.session?.status === "starting"; const sendLabel = props.connectionState !== "connected" || props.queueCount > 0 ? "Queue" : "Send"; const currentModelSelection = props.selectedThread.modelSelection; const currentRuntimeMode = props.selectedThread.runtimeMode; const connectionStatus = composerConnectionStatus({ connectionError: props.connectionError, connectionState: props.connectionState, environmentLabel: props.environmentLabel, threadSyncPhase: props.threadSyncPhase, }); const toolbarSurface = String(useThemeColor("--color-card")); const backdropSurface = String(useThemeColor("--color-screen")); const toolbarFadeOpaque = themeColorWithAlpha(toolbarSurface, 0.95); const toolbarFadeTransparent = themeColorWithAlpha(toolbarSurface, 0); const backdropGradient = `linear-gradient(to bottom, ${themeColorWithAlpha(backdropSurface, 0)} 0%, ${themeColorWithAlpha(backdropSurface, 0.6)} 55%, ${themeColorWithAlpha(backdropSurface, 0.9)} 100%)`; const selectedProviderStatus = useMemo(() => { if (!props.serverConfig) return null; return ( props.serverConfig.providers.find( (p) => p.instanceId === props.selectedThread.modelSelection.instanceId, ) ?? null ); }, [props.serverConfig, props.selectedThread.modelSelection.instanceId]); // ── Trigger detection ──────────────────────────────────── const [composerSelection, setComposerSelection] = useState(() => ({ start: props.draftMessage.length, end: props.draftMessage.length, })); const handleSelectionChange = useCallback((selection: ComposerEditorSelection) => { setComposerSelection(selection); }, []); useEffect(() => { const end = props.draftMessage.length; setComposerSelection((selection) => { const start = Math.min(selection.start, end); const selectionEnd = Math.min(selection.end, end); if (start === selection.start && selectionEnd === selection.end) { return selection; } return { start, end: selectionEnd }; }); }, [props.draftMessage.length]); const composerTrigger = useMemo(() => { if (composerSelection.start !== composerSelection.end) { return null; } return detectComposerTrigger(props.draftMessage, composerSelection.end); }, [composerSelection, props.draftMessage]); const pathSearch = useComposerPathSearch({ environmentId: props.environmentId, cwd: composerTrigger?.kind === "path" ? props.projectCwd : null, query: composerTrigger?.kind === "path" ? composerTrigger.query : null, }); const composerMenuItems: ComposerCommandItem[] = useMemo(() => { if (!composerTrigger) return []; if (composerTrigger.kind === "slash-command") { const q = composerTrigger.query.toLowerCase(); const allBuiltIn = [ { id: "cmd:model", type: "slash-command" as const, command: "model", label: "/model", description: "Switch model", }, { id: "cmd:plan", type: "slash-command" as const, command: "plan", label: "/plan", description: "Switch to plan mode", }, { id: "cmd:default", type: "slash-command" as const, command: "default", label: "/default", description: "Switch to default mode", }, ]; const builtIn = allBuiltIn.filter((item) => item.command.includes(q)); const providerCommands: ComposerCommandItem[] = []; for (const cmd of selectedProviderStatus?.slashCommands ?? []) { if (!cmd.name.toLowerCase().includes(q)) continue; providerCommands.push({ id: `pcmd:${cmd.name}`, type: "provider-slash-command" as const, command: cmd, label: `/${cmd.name}`, description: cmd.description ?? "", }); } return [...builtIn, ...providerCommands]; } if (composerTrigger.kind === "skill") { const enabledSkills = (selectedProviderStatus?.skills ?? []).filter((s) => s.enabled); const normalizedQuery = normalizeSearchQuery(composerTrigger.query, { trimLeadingPattern: /^\$+/, }); if (!normalizedQuery) { return enabledSkills.slice(0, 20).map((skill) => ({ id: `skill:${skill.name}`, type: "skill" as const, skill, label: skill.displayName ?? skill.name, description: skill.shortDescription ?? skill.description ?? "", })); } const ranked: Array<{ item: (typeof enabledSkills)[number]; score: number; tieBreaker: string; }> = []; for (const skill of enabledSkills) { const displayLabel = (skill.displayName ?? skill.name).toLowerCase(); const scores = [ scoreQueryMatch({ value: skill.name.toLowerCase(), query: normalizedQuery, exactBase: 0, prefixBase: 2, boundaryBase: 4, includesBase: 6, fuzzyBase: 100, boundaryMarkers: ["-", "_", "/"], }), scoreQueryMatch({ value: displayLabel, query: normalizedQuery, exactBase: 1, prefixBase: 3, boundaryBase: 5, includesBase: 7, fuzzyBase: 110, }), scoreQueryMatch({ value: skill.shortDescription?.toLowerCase() ?? "", query: normalizedQuery, exactBase: 20, prefixBase: 22, boundaryBase: 24, includesBase: 26, }), scoreQueryMatch({ value: skill.description?.toLowerCase() ?? "", query: normalizedQuery, exactBase: 30, prefixBase: 32, boundaryBase: 34, includesBase: 36, }), ].filter((s): s is number => s !== null); if (scores.length > 0) { insertRankedSearchResult( ranked, { item: skill, score: Math.min(...scores), tieBreaker: `${displayLabel}\u0000${skill.name}`, }, 20, ); } } return ranked.map(({ item: skill }) => ({ id: `skill:${skill.name}`, type: "skill" as const, skill, label: skill.displayName ?? skill.name, description: skill.shortDescription ?? skill.description ?? "", })); } if (composerTrigger.kind === "path") { return pathSearch.entries.map((entry) => { const parts = entry.path.split("/"); return { id: `path:${entry.path}`, type: "path" as const, path: entry.path, kind: entry.kind, label: parts[parts.length - 1] ?? entry.path, description: parts.length > 1 ? parts.slice(0, -1).join("/") : "", }; }); } return []; }, [composerTrigger, pathSearch.entries, selectedProviderStatus]); // ── Handle command selection ────────────────────────────── const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props; const handleSend = useCallback(async () => { const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id); if (inFlightThreadIdsRef.current.has(threadKey)) return; inFlightThreadIdsRef.current.add(threadKey); try { await onSendMessage(); // Sending a prompt starts agent work: arm the lock-screen card while the // app is foregrounded and the activity token can be registered. Armed // after the send so its preference read and native Activity start don't // contend with the queued-message feedback on the tap frame. armAgentAwarenessLiveActivityForLocalWork({ environmentId: props.environmentId, threadTitle: props.selectedThread.title, projectTitle: props.environmentLabel ?? "T3 Code", }); } finally { inFlightThreadIdsRef.current.delete(threadKey); } }, [ onSendMessage, props.environmentId, props.environmentLabel, props.selectedThread.id, props.selectedThread.title, ]); const handleCommandSelect = useCallback( (item: ComposerCommandItem) => { if (!composerTrigger) return; if ( item.type === "slash-command" && (item.command === "plan" || item.command === "default") ) { const result = replaceTextRange( draftMessage, composerTrigger.rangeStart, composerTrigger.rangeEnd, "", ); setComposerSelection({ start: result.cursor, end: result.cursor }); onChangeDraftMessage(result.text); onUpdateInteractionMode(item.command); return; } let replacement = ""; if (item.type === "path") { replacement = `${serializeComposerFileLink(item.path)} `; } else if (item.type === "skill") { replacement = `$${item.skill.name} `; } else if (item.type === "slash-command") { replacement = `/${item.command} `; } else if (item.type === "provider-slash-command") { replacement = `/${item.command.name} `; } const result = replaceTextRange( draftMessage, composerTrigger.rangeStart, composerTrigger.rangeEnd, replacement, ); setComposerSelection({ start: result.cursor, end: result.cursor }); onChangeDraftMessage(result.text); }, [composerTrigger, draftMessage, onChangeDraftMessage, onUpdateInteractionMode], ); // ── Model menu ─────────────────────────────────────────── const modelOptions = useMemo( () => buildModelOptions(props.serverConfig, currentModelSelection), [props.serverConfig, currentModelSelection], ); const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]); // An existing thread is bound to its harness: sessions can't move between // provider instances, so the picker only offers the thread's own group. const threadProviderGroups = useMemo( () => providerGroups.filter((group) => group.providerKey === currentModelSelection.instanceId), [providerGroups, currentModelSelection.instanceId], ); const currentModelOption = modelOptions.find( (option) => option.selection.instanceId === currentModelSelection.instanceId && option.selection.model === currentModelSelection.model, ) ?? null; const providerOptionDescriptors = useMemo( () => resolveProviderOptionDescriptors({ capabilities: currentModelOption?.capabilities, selections: currentModelSelection.options, }), [currentModelOption?.capabilities, currentModelSelection.options], ); const settingsOwnerId = scopedThreadKey(props.environmentId, props.selectedThread.id); const settingsRouteSession = useMemo( () => ({ ownerId: settingsOwnerId, providerGroups: threadProviderGroups, selectedModel: currentModelSelection, onSelectModel: (option) => props.onUpdateModelSelection(option.selection), optionDescriptors: providerOptionDescriptors, onUpdateOptionSelections: (options) => props.onUpdateModelSelection({ ...currentModelSelection, options }), runtimeMode: currentRuntimeMode, onUpdateRuntimeMode: props.onUpdateRuntimeMode, }), [ currentModelSelection, currentRuntimeMode, props.onUpdateModelSelection, props.onUpdateRuntimeMode, providerOptionDescriptors, settingsOwnerId, threadProviderGroups, ], ); const openSettings = useCallback(() => { settingsRoutePresentation.present(settingsRouteSession); settingsSheetPresentation.open(); }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.open]); useEffect(() => { if (settingsSheetPresentation.isActive) { settingsRoutePresentation.present(settingsRouteSession); } }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]); useEffect(() => { if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) { return; } settingsRoutePresentedRef.current = true; navigation.dispatch(StackActions.push("ThreadSettingsSheet")); }, [navigation, settingsSheetPresentation.isVisible]); useFocusEffect( useCallback(() => { if (!settingsRoutePresentedRef.current) { return; } settingsRoutePresentedRef.current = false; settingsSheetPresentation.onDismissed(); settingsRoutePresentation.clear(settingsOwnerId); }, [settingsOwnerId, settingsRoutePresentation.clear, settingsSheetPresentation.onDismissed]), ); useEffect( () => // UIKit's completion callback for the sheet dismissal, surfaced by the // native-stack patch. This is when the queued keyboard restore runs. (navigation as unknown as NavigationWithFinishTransitioning).addListener( "finishTransitioning", settingsSheetPresentation.onStackTransitionsFinished, ), [navigation, settingsSheetPresentation.onStackTransitionsFinished], ); return ( {/* The backdrop gradient lives on a plain View: Reanimated's Animated.View silently drops experimental_backgroundImage on Android, which left this strip fully transparent and the feed text legible through the composer. */} {composerTrigger && composerMenuItems.length > 0 ? ( ) : null} {connectionStatus ? ( ) : null} {/* Attachment strip — inside the card, above the text input */} {isExpanded ? ( 0 ? "pb-2.5" : undefined} entering={FadeIn.duration(160)} exiting={FadeOut.duration(120)} > ) : null} void props.onNativePasteImages(uris)} placeholder={props.placeholder} onFocus={handleFocus} onBlur={handleBlur} onSubmit={handleSend} scrollEnabled={isExpanded} // Android: collapsed single line centers natively (gravity) in // a pill-height box matching the send button; iOS keeps insets. singleLineCentered={!isExpanded} contentInsetVertical={isExpanded || Platform.OS === "android" ? 0 : 6} style={ isExpanded ? { minHeight: 72, maxHeight: 160, paddingHorizontal: 4, paddingVertical: 4, } : { height: 36, } } textStyle={{ ...bodyText, color: foregroundColor, }} /> {!isExpanded && props.draftAttachments.length > 0 ? ( {props.draftAttachments.slice(0, 3).map((image) => ( onPressImage(image.previewUri)}> ))} {props.draftAttachments.length > 3 ? ( +{props.draftAttachments.length - 3} ) : null} ) : null} {!isExpanded ? ( {showStopAction ? ( ) : ( )} ) : null} {isExpanded ? ( void props.onPickDraftImages()} showChevron={false} /> } label={currentModelOption?.label ?? currentModelSelection.model} maxWidth={152} onPress={openSettings} /> {showStopAction ? ( ) : null} ) : null} {/* Queue count */} {props.queueCount > 0 ? ( {props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send automatically. ) : null} ); });