Open History to see the last commit
1import type {
2 EnvironmentId,
3 MessageId,
4 ModelSelection,
5 OrchestrationThreadShell,
6 ProviderInteractionMode,
7 RuntimeMode,
8 ServerConfig as T3ServerConfig,
9} from "@t3tools/contracts";
10import {
11 detectComposerTrigger,
12 replaceTextRange,
13 serializeComposerFileLink,
14 type ComposerTrigger,
15} from "@t3tools/shared/composerTrigger";
16import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
17import type { ReactNode } from "react";
18import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
19import {
20 ActivityIndicator,
21 Image,
22 Platform,
23 Pressable,
24 StyleSheet,
25 useColorScheme,
26 View,
27 type ViewStyle,
28} from "react-native";
29import ImageViewing from "react-native-image-viewing";
30import Animated, {
31 FadeIn,
32 FadeInDown,
33 FadeOut,
34 FadeOutDown,
35 LinearTransition,
36} from "react-native-reanimated";
37import { useThemeColor } from "../../lib/useThemeColor";
38import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
39import { scopedThreadKey } from "../../lib/scopedEntities";
40
41import { AppText as Text } from "../../components/AppText";
42import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
43import { GlassSurface } from "../../components/GlassSurface";
44import {
45 ComposerEditor,
46 type ComposerEditorHandle,
47 type ComposerEditorSelection,
48} from "../../components/ComposerEditor";
49import {
50 ComposerInlineControl,
51 ComposerToolbarButton,
52 ComposerToolbarRow,
53 ComposerToolbarScroller,
54} from "../../components/ComposerToolbar";
55import { ControlPill } from "../../components/ControlPill";
56import { ProviderIcon } from "../../components/ProviderIcon";
57import type { DraftComposerImageAttachment } from "../../lib/composerImages";
58import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
59import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
60import type { RemoteClientConnectionState } from "../../lib/connection";
61import {
62 insertRankedSearchResult,
63 normalizeSearchQuery,
64 scoreQueryMatch,
65} from "@t3tools/shared/searchRanking";
66import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
67import { useComposerPathSearch } from "../../state/use-composer-path-search";
68import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
69import {
70 type ExistingThreadSettingsRouteSession,
71 useExistingThreadSettingsRoutePresentation,
72} from "./ThreadSettingsSheet";
73import {
74 useThreadSettingsSheetPresentation,
75 type NavigationWithFinishTransitioning,
76} from "./use-thread-settings-sheet-presentation";
77
78/**
79 * Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
80 * Exported so the parent can compute feed overlap / content insets.
81 */
82export const COMPOSER_COLLAPSED_CHROME = 60;
83
84/**
85 * Height of the expanded composer (card + toolbar + vertical padding, excluding safe-area inset).
86 * Used by the parent to compute the larger feed bottom inset when the composer is focused.
87 */
88export const COMPOSER_EXPANDED_CHROME = 156;
89
90export interface ThreadComposerProps {
91 readonly draftMessage: string;
92 readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
93 readonly placeholder: string;
94 readonly contentMaxWidth?: number;
95 readonly bottomInset?: number;
96 readonly connectionState: RemoteClientConnectionState;
97 readonly connectionError: string | null;
98 readonly environmentLabel: string | null;
99 /**
100 * Message sync phase for the selected thread (drives the status pill):
101 * "loading" = first fetch, nothing to show yet; "syncing" = cached messages
102 * are on screen while they reconcile with the server.
103 */
104 readonly threadSyncPhase?: "loading" | "syncing" | null;
105 readonly selectedThread: OrchestrationThreadShell;
106 readonly serverConfig: T3ServerConfig | null;
107 readonly queueCount: number;
108 readonly environmentId: EnvironmentId;
109 readonly projectCwd: string | null;
110 readonly editorRef?: RefObject<ComposerEditorHandle | null>;
111 readonly onChangeDraftMessage: (value: string) => void;
112 readonly onPickDraftImages: () => Promise<void>;
113 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
114 readonly onRemoveDraftImage: (imageId: string) => void;
115 readonly onStopThread: () => void;
116 readonly onSendMessage: () => Promise<MessageId | null>;
117 readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
118 readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
119 readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
120 readonly onReconnectEnvironment: () => void;
121 readonly onExpandedChange?: (expanded: boolean) => void;
122 /** Fires on editor focus/blur; hosts use it to vet stale keyboard state. */
123 readonly onEditorFocusChange?: (focused: boolean) => void;
124}
125
126/**
127 * The pill / card container — renders with Expo's native GlassView on supported
128 * iOS 26+ devices and keeps the existing opaque fallback elsewhere.
129 * Exported so NewTaskDraftScreen can render the same composer chrome.
130 */
131// One timing for every piece of the expanded↔compact morph so the surface,
132// toolbar, and siblings move together instead of popping between layouts.
133// Android gets NO layout transition: the composer rides the keyboard via
134// KeyboardStickyView (frame-synced to the IME), and a time-based morph
135// running alongside that translate reads as jitter. Snapping the layout and
136// letting the keyboard-synced slide be the only motion looks native there.
137const COMPOSER_LAYOUT_TRANSITION =
138 Platform.OS === "android" ? undefined : LinearTransition.duration(220);
139
140export function ComposerSurface(props: {
141 readonly children: ReactNode;
142 readonly style: ViewStyle;
143 readonly isDarkMode: boolean;
144 /** Existing thread composers morph between pill and card layouts. */
145 readonly animateLayout?: boolean;
146}) {
147 // Drop shadow lives on a wrapper: `overflow: "hidden"` on the surface itself
148 // (needed to clip content to the pill shape) would clip the shadow on iOS.
149 const shadowStyle: ViewStyle = {
150 borderRadius: props.style.borderRadius,
151 shadowColor: "#000000",
152 shadowOpacity: props.isDarkMode ? 0.35 : 0.12,
153 shadowRadius: 14,
154 shadowOffset: { width: 0, height: 6 },
155 elevation: 10,
156 };
157
158 return (
159 <Animated.View
160 layout={props.animateLayout === false ? undefined : COMPOSER_LAYOUT_TRANSITION}
161 style={shadowStyle}
162 >
163 <GlassSurface
164 chrome="none"
165 fallbackStyle={{
166 backgroundColor: props.isDarkMode ? "rgba(44,44,46,0.96)" : "rgba(255,255,255,0.96)",
167 borderWidth: 1,
168 borderColor: props.isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)",
169 }}
170 glassEffectStyle="regular"
171 // The composer is a passive material containing interactive controls.
172 // Expo GlassView defaults to non-interactive and both layouts share it.
173 tintColor="transparent"
174 style={props.style}
175 >
176 {props.children}
177 </GlassSurface>
178 </Animated.View>
179 );
180}
181
182type ComposerStatusPillState = {
183 readonly kind: "unavailable" | "reconnecting" | "syncing";
184 readonly label: string;
185};
186
187function composerConnectionStatus(input: {
188 readonly connectionError: string | null;
189 readonly connectionState: RemoteClientConnectionState;
190 readonly environmentLabel: string | null;
191 readonly threadSyncPhase?: "loading" | "syncing" | null;
192}): ComposerStatusPillState | null {
193 const environmentLabel = input.environmentLabel ?? "Environment";
194
195 switch (input.connectionState) {
196 case "connecting":
197 case "reconnecting":
198 return {
199 kind: "reconnecting",
200 label:
201 input.connectionError === null
202 ? `Reconnecting to ${environmentLabel}...`
203 : `Failed to connect. Retrying ${environmentLabel}...`,
204 };
205 case "offline":
206 return { kind: "unavailable", label: "You are offline" };
207 case "error":
208 return {
209 kind: "unavailable",
210 label: input.connectionError
211 ? `Failed to connect to ${environmentLabel}: ${input.connectionError}`
212 : `Failed to connect to ${environmentLabel}`,
213 };
214 case "available":
215 return { kind: "unavailable", label: `${environmentLabel} is not connected` };
216 case "connected":
217 break;
218 }
219
220 // Connected: the pill is the single loading/sync indicator. One stable
221 // label per open — "Loading" when starting from scratch, "Syncing" when
222 // cached messages are already visible.
223 switch (input.threadSyncPhase) {
224 case "loading":
225 return { kind: "syncing", label: "Loading messages..." };
226 case "syncing":
227 return { kind: "syncing", label: "Syncing messages..." };
228 default:
229 return null;
230 }
231}
232
233const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(props: {
234 readonly onPress: () => void;
235 readonly status: ComposerStatusPillState;
236}) {
237 const isReconnecting = props.status.kind !== "unavailable";
238
239 return (
240 <Animated.View
241 className="absolute inset-x-0 bottom-full items-center pb-2"
242 entering={FadeInDown.duration(180)}
243 exiting={FadeOutDown.duration(140)}
244 pointerEvents="box-none"
245 >
246 <Pressable
247 accessibilityRole="button"
248 onPress={props.onPress}
249 className="max-w-full flex-row items-center gap-2 rounded-full bg-white/90 px-3 py-2 shadow-sm active:opacity-70 dark:bg-neutral-900/90"
250 >
251 {isReconnecting ? (
252 <ActivityIndicator size="small" color="#8e8e93" />
253 ) : (
254 <View className="h-2 w-2 rounded-full bg-red-500" />
255 )}
256 <Text
257 className="max-w-[260px] text-sm font-t3-bold leading-snug text-foreground"
258 numberOfLines={1}
259 >
260 {props.status.label}
261 </Text>
262 </Pressable>
263 </Animated.View>
264 );
265});
266
267export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
268 const navigation = useNavigation();
269 const isDarkMode = useColorScheme() === "dark";
270 const foregroundColor = useThemeColor("--color-foreground");
271 const bodyText = useScaledTextRole("body");
272 const fallbackInputRef = useRef<ComposerEditorHandle>(null);
273 const inputRef = props.editorRef ?? fallbackInputRef;
274 const [isFocused, setIsFocused] = useState(false);
275 const settingsSheetPresentation = useThreadSettingsSheetPresentation({
276 editorRef: inputRef,
277 isEditorFocused: isFocused,
278 });
279 const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation();
280 const settingsRoutePresentedRef = useRef(false);
281 const wasExpandedBeforePreviewRef = useRef(false);
282 const inFlightThreadIdsRef = useRef(new Set<string>());
283 const { onExpandedChange } = props;
284
285 const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
286 const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
287 // Opening and presentation count as active so the composer stays expanded
288 // while focus moves between its native editor and the settings picker.
289 const isExpanded = isFocused || settingsSheetPresentation.isActive;
290 const canSend = hasContent;
291
292 // Notify the parent from the derived value, not focus events: the parent
293 // sizes the feed inset from this, and blur-during-sheet would otherwise
294 // report collapsed while the composer still renders expanded.
295 useEffect(() => {
296 onExpandedChange?.(isExpanded);
297 }, [isExpanded, onExpandedChange]);
298
299 const onPressImage = useCallback(
300 (uri: string) => {
301 wasExpandedBeforePreviewRef.current = isFocused;
302 setPreviewImageUri(uri);
303 },
304 [isFocused],
305 );
306
307 const closePreview = useCallback(() => {
308 setPreviewImageUri(null);
309 if (wasExpandedBeforePreviewRef.current) {
310 setTimeout(() => inputRef.current?.focus(), 100);
311 }
312 }, [inputRef]);
313
314 const onEditorFocusChange = props.onEditorFocusChange;
315 const handleFocus = useCallback(() => {
316 setIsFocused(true);
317 onEditorFocusChange?.(true);
318 }, [onEditorFocusChange]);
319
320 const handleBlur = useCallback(() => {
321 setIsFocused(false);
322 onEditorFocusChange?.(false);
323 }, [onEditorFocusChange]);
324 const showStopAction =
325 props.selectedThread.session?.status === "running" ||
326 props.selectedThread.session?.status === "starting";
327
328 const sendLabel =
329 props.connectionState !== "connected" || props.queueCount > 0 ? "Queue" : "Send";
330 const currentModelSelection = props.selectedThread.modelSelection;
331 const currentRuntimeMode = props.selectedThread.runtimeMode;
332 const connectionStatus = composerConnectionStatus({
333 connectionError: props.connectionError,
334 connectionState: props.connectionState,
335 environmentLabel: props.environmentLabel,
336 threadSyncPhase: props.threadSyncPhase,
337 });
338 const toolbarFadeOpaque = isDarkMode ? "rgba(0,0,0,0.95)" : "rgba(255,255,255,0.95)";
339 const toolbarFadeTransparent = isDarkMode ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)";
340 const selectedProviderStatus = useMemo(() => {
341 if (!props.serverConfig) return null;
342 return (
343 props.serverConfig.providers.find(
344 (p) => p.instanceId === props.selectedThread.modelSelection.instanceId,
345 ) ?? null
346 );
347 }, [props.serverConfig, props.selectedThread.modelSelection.instanceId]);
348
349 // ── Trigger detection ────────────────────────────────────
350 const [composerSelection, setComposerSelection] = useState(() => ({
351 start: props.draftMessage.length,
352 end: props.draftMessage.length,
353 }));
354
355 const handleSelectionChange = useCallback((selection: ComposerEditorSelection) => {
356 setComposerSelection(selection);
357 }, []);
358 useEffect(() => {
359 const end = props.draftMessage.length;
360 setComposerSelection((selection) => {
361 const start = Math.min(selection.start, end);
362 const selectionEnd = Math.min(selection.end, end);
363 if (start === selection.start && selectionEnd === selection.end) {
364 return selection;
365 }
366 return { start, end: selectionEnd };
367 });
368 }, [props.draftMessage.length]);
369
370 const composerTrigger = useMemo<ComposerTrigger | null>(() => {
371 if (composerSelection.start !== composerSelection.end) {
372 return null;
373 }
374 return detectComposerTrigger(props.draftMessage, composerSelection.end);
375 }, [composerSelection, props.draftMessage]);
376 const pathSearch = useComposerPathSearch({
377 environmentId: props.environmentId,
378 cwd: composerTrigger?.kind === "path" ? props.projectCwd : null,
379 query: composerTrigger?.kind === "path" ? composerTrigger.query : null,
380 });
381
382 const composerMenuItems: ComposerCommandItem[] = useMemo(() => {
383 if (!composerTrigger) return [];
384
385 if (composerTrigger.kind === "slash-command") {
386 const q = composerTrigger.query.toLowerCase();
387 const allBuiltIn = [
388 {
389 id: "cmd:model",
390 type: "slash-command" as const,
391 command: "model",
392 label: "/model",
393 description: "Switch model",
394 },
395 {
396 id: "cmd:plan",
397 type: "slash-command" as const,
398 command: "plan",
399 label: "/plan",
400 description: "Switch to plan mode",
401 },
402 {
403 id: "cmd:default",
404 type: "slash-command" as const,
405 command: "default",
406 label: "/default",
407 description: "Switch to default mode",
408 },
409 ];
410 const builtIn = allBuiltIn.filter((item) => item.command.includes(q));
411
412 const providerCommands: ComposerCommandItem[] = [];
413 for (const cmd of selectedProviderStatus?.slashCommands ?? []) {
414 if (!cmd.name.toLowerCase().includes(q)) continue;
415 providerCommands.push({
416 id: `pcmd:${cmd.name}`,
417 type: "provider-slash-command" as const,
418 command: cmd,
419 label: `/${cmd.name}`,
420 description: cmd.description ?? "",
421 });
422 }
423
424 return [...builtIn, ...providerCommands];
425 }
426
427 if (composerTrigger.kind === "skill") {
428 const enabledSkills = (selectedProviderStatus?.skills ?? []).filter((s) => s.enabled);
429 const normalizedQuery = normalizeSearchQuery(composerTrigger.query, {
430 trimLeadingPattern: /^\$+/,
431 });
432
433 if (!normalizedQuery) {
434 return enabledSkills.slice(0, 20).map((skill) => ({
435 id: `skill:${skill.name}`,
436 type: "skill" as const,
437 skill,
438 label: skill.displayName ?? skill.name,
439 description: skill.shortDescription ?? skill.description ?? "",
440 }));
441 }
442
443 const ranked: Array<{
444 item: (typeof enabledSkills)[number];
445 score: number;
446 tieBreaker: string;
447 }> = [];
448 for (const skill of enabledSkills) {
449 const displayLabel = (skill.displayName ?? skill.name).toLowerCase();
450 const scores = [
451 scoreQueryMatch({
452 value: skill.name.toLowerCase(),
453 query: normalizedQuery,
454 exactBase: 0,
455 prefixBase: 2,
456 boundaryBase: 4,
457 includesBase: 6,
458 fuzzyBase: 100,
459 boundaryMarkers: ["-", "_", "/"],
460 }),
461 scoreQueryMatch({
462 value: displayLabel,
463 query: normalizedQuery,
464 exactBase: 1,
465 prefixBase: 3,
466 boundaryBase: 5,
467 includesBase: 7,
468 fuzzyBase: 110,
469 }),
470 scoreQueryMatch({
471 value: skill.shortDescription?.toLowerCase() ?? "",
472 query: normalizedQuery,
473 exactBase: 20,
474 prefixBase: 22,
475 boundaryBase: 24,
476 includesBase: 26,
477 }),
478 scoreQueryMatch({
479 value: skill.description?.toLowerCase() ?? "",
480 query: normalizedQuery,
481 exactBase: 30,
482 prefixBase: 32,
483 boundaryBase: 34,
484 includesBase: 36,
485 }),
486 ].filter((s): s is number => s !== null);
487
488 if (scores.length > 0) {
489 insertRankedSearchResult(
490 ranked,
491 {
492 item: skill,
493 score: Math.min(...scores),
494 tieBreaker: `${displayLabel}\u0000${skill.name}`,
495 },
496 20,
497 );
498 }
499 }
500
501 return ranked.map(({ item: skill }) => ({
502 id: `skill:${skill.name}`,
503 type: "skill" as const,
504 skill,
505 label: skill.displayName ?? skill.name,
506 description: skill.shortDescription ?? skill.description ?? "",
507 }));
508 }
509
510 if (composerTrigger.kind === "path") {
511 return pathSearch.entries.map((entry) => {
512 const parts = entry.path.split("/");
513 return {
514 id: `path:${entry.path}`,
515 type: "path" as const,
516 path: entry.path,
517 kind: entry.kind,
518 label: parts[parts.length - 1] ?? entry.path,
519 description: parts.length > 1 ? parts.slice(0, -1).join("/") : "",
520 };
521 });
522 }
523
524 return [];
525 }, [composerTrigger, pathSearch.entries, selectedProviderStatus]);
526
527 // ── Handle command selection ──────────────────────────────
528 const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
529
530 const handleSend = useCallback(async () => {
531 const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
532 if (inFlightThreadIdsRef.current.has(threadKey)) return;
533 inFlightThreadIdsRef.current.add(threadKey);
534 try {
535 await onSendMessage();
536 // Sending a prompt starts agent work: arm the lock-screen card while the
537 // app is foregrounded and the activity token can be registered. Armed
538 // after the send so its preference read and native Activity start don't
539 // contend with the queued-message feedback on the tap frame.
540 armAgentAwarenessLiveActivityForLocalWork({
541 environmentId: props.environmentId,
542 threadTitle: props.selectedThread.title,
543 projectTitle: props.environmentLabel ?? "T3 Code",
544 });
545 } finally {
546 inFlightThreadIdsRef.current.delete(threadKey);
547 }
548 }, [
549 onSendMessage,
550 props.environmentId,
551 props.environmentLabel,
552 props.selectedThread.id,
553 props.selectedThread.title,
554 ]);
555 const handleCommandSelect = useCallback(
556 (item: ComposerCommandItem) => {
557 if (!composerTrigger) return;
558
559 if (
560 item.type === "slash-command" &&
561 (item.command === "plan" || item.command === "default")
562 ) {
563 const result = replaceTextRange(
564 draftMessage,
565 composerTrigger.rangeStart,
566 composerTrigger.rangeEnd,
567 "",
568 );
569 setComposerSelection({ start: result.cursor, end: result.cursor });
570 onChangeDraftMessage(result.text);
571 onUpdateInteractionMode(item.command);
572 return;
573 }
574
575 let replacement = "";
576 if (item.type === "path") {
577 replacement = `${serializeComposerFileLink(item.path)} `;
578 } else if (item.type === "skill") {
579 replacement = `$${item.skill.name} `;
580 } else if (item.type === "slash-command") {
581 replacement = `/${item.command} `;
582 } else if (item.type === "provider-slash-command") {
583 replacement = `/${item.command.name} `;
584 }
585
586 const result = replaceTextRange(
587 draftMessage,
588 composerTrigger.rangeStart,
589 composerTrigger.rangeEnd,
590 replacement,
591 );
592 setComposerSelection({ start: result.cursor, end: result.cursor });
593 onChangeDraftMessage(result.text);
594 },
595 [composerTrigger, draftMessage, onChangeDraftMessage, onUpdateInteractionMode],
596 );
597
598 // ── Model menu ───────────────────────────────────────────
599 const modelOptions = useMemo(
600 () => buildModelOptions(props.serverConfig, currentModelSelection),
601 [props.serverConfig, currentModelSelection],
602 );
603 const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
604 // An existing thread is bound to its harness: sessions can't move between
605 // provider instances, so the picker only offers the thread's own group.
606 const threadProviderGroups = useMemo(
607 () => providerGroups.filter((group) => group.providerKey === currentModelSelection.instanceId),
608 [providerGroups, currentModelSelection.instanceId],
609 );
610 const currentModelOption =
611 modelOptions.find(
612 (option) =>
613 option.selection.instanceId === currentModelSelection.instanceId &&
614 option.selection.model === currentModelSelection.model,
615 ) ?? null;
616 const providerOptionDescriptors = useMemo(
617 () =>
618 resolveProviderOptionDescriptors({
619 capabilities: currentModelOption?.capabilities,
620 selections: currentModelSelection.options,
621 }),
622 [currentModelOption?.capabilities, currentModelSelection.options],
623 );
624 const settingsOwnerId = scopedThreadKey(props.environmentId, props.selectedThread.id);
625 const settingsRouteSession = useMemo<ExistingThreadSettingsRouteSession>(
626 () => ({
627 ownerId: settingsOwnerId,
628 providerGroups: threadProviderGroups,
629 selectedModel: currentModelSelection,
630 onSelectModel: (option) => props.onUpdateModelSelection(option.selection),
631 optionDescriptors: providerOptionDescriptors,
632 onUpdateOptionSelections: (options) =>
633 props.onUpdateModelSelection({ ...currentModelSelection, options }),
634 runtimeMode: currentRuntimeMode,
635 onUpdateRuntimeMode: props.onUpdateRuntimeMode,
636 }),
637 [
638 currentModelSelection,
639 currentRuntimeMode,
640 props.onUpdateModelSelection,
641 props.onUpdateRuntimeMode,
642 providerOptionDescriptors,
643 settingsOwnerId,
644 threadProviderGroups,
645 ],
646 );
647 const openSettings = useCallback(() => {
648 settingsRoutePresentation.present(settingsRouteSession);
649 settingsSheetPresentation.open();
650 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.open]);
651
652 useEffect(() => {
653 if (settingsSheetPresentation.isActive) {
654 settingsRoutePresentation.present(settingsRouteSession);
655 }
656 }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]);
657
658 useEffect(() => {
659 if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
660 return;
661 }
662
663 settingsRoutePresentedRef.current = true;
664 navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
665 }, [navigation, settingsSheetPresentation.isVisible]);
666
667 useFocusEffect(
668 useCallback(() => {
669 if (!settingsRoutePresentedRef.current) {
670 return;
671 }
672
673 settingsRoutePresentedRef.current = false;
674 settingsSheetPresentation.onDismissed();
675 settingsRoutePresentation.clear(settingsOwnerId);
676 }, [settingsOwnerId, settingsRoutePresentation.clear, settingsSheetPresentation.onDismissed]),
677 );
678
679 useEffect(
680 () =>
681 // UIKit's completion callback for the sheet dismissal, surfaced by the
682 // native-stack patch. This is when the queued keyboard restore runs.
683 (navigation as unknown as NavigationWithFinishTransitioning).addListener(
684 "finishTransitioning",
685 settingsSheetPresentation.onStackTransitionsFinished,
686 ),
687 [navigation, settingsSheetPresentation.onStackTransitionsFinished],
688 );
689
690 return (
691 <Animated.View
692 className="px-4"
693 layout={COMPOSER_LAYOUT_TRANSITION}
694 style={{
695 paddingTop: isExpanded ? 8 : 6,
696 paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
697 }}
698 >
699 {/* The backdrop gradient lives on a plain View: Reanimated's Animated.View
700 silently drops experimental_backgroundImage on Android, which left this
701 strip fully transparent and the feed text legible through the composer. */}
702 <View
703 pointerEvents="none"
704 style={[
705 StyleSheet.absoluteFill,
706 {
707 experimental_backgroundImage: isDarkMode
708 ? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.6) 55%, rgba(0,0,0,0.9) 100%)"
709 : "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.6) 55%, rgba(255,255,255,0.9) 100%)",
710 },
711 ]}
712 />
713 <Animated.View
714 className="relative w-full self-center"
715 layout={COMPOSER_LAYOUT_TRANSITION}
716 style={{ maxWidth: props.contentMaxWidth }}
717 >
718 {composerTrigger && composerMenuItems.length > 0 ? (
719 <View className="absolute inset-x-0 bottom-full z-10 mb-2">
720 <ComposerCommandPopover
721 items={composerMenuItems}
722 triggerKind={composerTrigger.kind}
723 isLoading={pathSearch.isPending}
724 onSelect={handleCommandSelect}
725 />
726 </View>
727 ) : null}
728
729 {connectionStatus ? (
730 <ComposerConnectionStatusPill
731 status={connectionStatus}
732 onPress={props.onReconnectEnvironment}
733 />
734 ) : null}
735
736 <ComposerSurface
737 isDarkMode={isDarkMode}
738 style={
739 isExpanded
740 ? {
741 borderRadius: 26,
742 minHeight: 140,
743 overflow: "hidden" as const,
744 paddingBottom: 6,
745 paddingHorizontal: 14,
746 paddingTop: 14,
747 }
748 : {
749 borderRadius: 999,
750 overflow: "hidden" as const,
751 flexDirection: "row" as const,
752 alignItems: "center" as const,
753 paddingLeft: 18,
754 paddingRight: 5,
755 paddingVertical: 5,
756 }
757 }
758 >
759 {/* Attachment strip — inside the card, above the text input */}
760 {isExpanded ? (
761 <Animated.View
762 className={props.draftAttachments.length > 0 ? "pb-2.5" : undefined}
763 entering={FadeIn.duration(160)}
764 exiting={FadeOut.duration(120)}
765 >
766 <ComposerAttachmentStrip
767 attachments={props.draftAttachments}
768 onRemove={props.onRemoveDraftImage}
769 onPressImage={onPressImage}
770 />
771 </Animated.View>
772 ) : null}
773
774 <View className={isExpanded ? undefined : "min-w-0 flex-1"}>
775 <ComposerEditor
776 ref={inputRef}
777 multiline
778 value={props.draftMessage}
779 skills={selectedProviderStatus?.skills ?? []}
780 selection={composerSelection}
781 onChangeText={props.onChangeDraftMessage}
782 onSelectionChange={handleSelectionChange}
783 onPasteImages={(uris) => void props.onNativePasteImages(uris)}
784 placeholder={props.placeholder}
785 onFocus={handleFocus}
786 onBlur={handleBlur}
787 onSubmit={handleSend}
788 scrollEnabled={isExpanded}
789 // Android: collapsed single line centers natively (gravity) in
790 // a pill-height box matching the send button; iOS keeps insets.
791 singleLineCentered={!isExpanded}
792 contentInsetVertical={isExpanded || Platform.OS === "android" ? 0 : 6}
793 style={
794 isExpanded
795 ? {
796 minHeight: 72,
797 maxHeight: 160,
798 paddingHorizontal: 4,
799 paddingVertical: 4,
800 }
801 : {
802 height: 36,
803 }
804 }
805 textStyle={{
806 ...bodyText,
807 color: foregroundColor,
808 }}
809 />
810 </View>
811 {!isExpanded && props.draftAttachments.length > 0 ? (
812 <View className="flex-row gap-1 pl-1">
813 {props.draftAttachments.slice(0, 3).map((image) => (
814 <Pressable key={image.id} onPress={() => onPressImage(image.previewUri)}>
815 <Image
816 source={{ uri: image.previewUri }}
817 className="size-[30px] rounded-lg bg-subtle"
818 resizeMode="cover"
819 />
820 </Pressable>
821 ))}
822 {props.draftAttachments.length > 3 ? (
823 <View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
824 <Text className="text-foreground-muted text-2xs font-t3-bold">
825 +{props.draftAttachments.length - 3}
826 </Text>
827 </View>
828 ) : null}
829 </View>
830 ) : null}
831 {!isExpanded ? (
832 <Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(100)}>
833 {showStopAction ? (
834 <ControlPill icon="stop.fill" variant="danger" onPress={props.onStopThread} />
835 ) : (
836 <ControlPill
837 icon="arrow.up"
838 variant="primary"
839 disabled={!canSend}
840 onPress={handleSend}
841 />
842 )}
843 </Animated.View>
844 ) : null}
845 {isExpanded ? (
846 <ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={4}>
847 <ComposerToolbarScroller
848 fadeOpaque={toolbarFadeOpaque}
849 fadeTransparent={toolbarFadeTransparent}
850 contentPaddingRight={8}
851 >
852 <ComposerToolbarButton
853 accessibilityLabel="Add attachment"
854 icon="plus"
855 onPress={() => void props.onPickDraftImages()}
856 showChevron={false}
857 />
858 <ComposerInlineControl
859 accessibilityLabel="Model and reasoning settings"
860 emphasized
861 iconNode={
862 <ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
863 }
864 label={currentModelOption?.label ?? currentModelSelection.model}
865 maxWidth={152}
866 onPress={openSettings}
867 />
868 {showStopAction ? (
869 <ComposerToolbarButton
870 accessibilityLabel="Stop"
871 icon="stop.fill"
872 variant="danger"
873 onPress={props.onStopThread}
874 showChevron={false}
875 />
876 ) : null}
877 </ComposerToolbarScroller>
878 <ComposerToolbarButton
879 accessibilityLabel={sendLabel}
880 icon="arrow.up"
881 variant="primary"
882 disabled={!canSend}
883 onPress={handleSend}
884 showChevron={false}
885 />
886 </ComposerToolbarRow>
887 ) : null}
888 </ComposerSurface>
889
890 {/* Queue count */}
891 {props.queueCount > 0 ? (
892 <Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(120)}>
893 <Text className="pt-2 text-xs text-foreground-muted">
894 {props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
895 automatically.
896 </Text>
897 </Animated.View>
898 ) : null}
899 </Animated.View>
900
901 <ImageViewing
902 images={previewImageUri ? [{ uri: previewImageUri }] : []}
903 imageIndex={0}
904 visible={previewImageUri !== null}
905 onRequestClose={closePreview}
906 swipeToCloseEnabled
907 doubleTapToZoomEnabled
908 />
909 </Animated.View>
910 );
911});