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