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 type { ReactNode } from "react";
18import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
19import {
20 ActivityIndicator,
21 Image,
22 Pressable,
23 useColorScheme,
24 View,
25 type ViewStyle,
26} from "react-native";
27import ImageViewing from "react-native-image-viewing";
28import { useThemeColor } from "../../lib/useThemeColor";
29
30import { AppText as Text } from "../../components/AppText";
31import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
32import {
33 ComposerEditor,
34 type ComposerEditorHandle,
35 type ComposerEditorSelection,
36} from "../../components/ComposerEditor";
37import {
38 ComposerToolbarButton,
39 ComposerToolbarRow,
40 ComposerToolbarScroller,
41 ComposerToolbarTrigger,
42} from "../../components/ComposerToolbarTrigger";
43import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
44import { ProviderIcon } from "../../components/ProviderIcon";
45import type { DraftComposerImageAttachment } from "../../lib/composerImages";
46import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
47import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
48import type { RemoteClientConnectionState } from "../../lib/connection";
49import {
50 insertRankedSearchResult,
51 normalizeSearchQuery,
52 scoreQueryMatch,
53} from "@t3tools/shared/searchRanking";
54import {
55 applyProviderOptionMenuEvent,
56 buildProviderOptionMenuActions,
57 providerOptionsConfigurationLabel,
58 resolveProviderOptionDescriptors,
59} from "../../lib/providerOptions";
60import { useComposerPathSearch } from "../../state/use-composer-path-search";
61import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
62
63/**
64 * Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
65 * Exported so the parent can compute feed overlap / content insets.
66 */
67export const COMPOSER_COLLAPSED_CHROME = 60;
68
69/**
70 * Height of the expanded composer (card + toolbar + vertical padding, excluding safe-area inset).
71 * Used by the parent to compute the larger feed bottom inset when the composer is focused.
72 */
73export const COMPOSER_EXPANDED_CHROME = 174;
74
75export interface ThreadComposerProps {
76 readonly draftMessage: string;
77 readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
78 readonly placeholder: string;
79 readonly bottomInset?: number;
80 readonly connectionState: RemoteClientConnectionState;
81 readonly connectionError: string | null;
82 readonly environmentLabel: string | null;
83 readonly selectedThread: OrchestrationThreadShell;
84 readonly serverConfig: T3ServerConfig | null;
85 readonly queueCount: number;
86 readonly activeThreadBusy: boolean;
87 readonly environmentId: EnvironmentId;
88 readonly projectCwd: string | null;
89 readonly editorRef?: RefObject<ComposerEditorHandle | null>;
90 readonly onChangeDraftMessage: (value: string) => void;
91 readonly onPickDraftImages: () => Promise<void>;
92 readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
93 readonly onRemoveDraftImage: (imageId: string) => void;
94 readonly onStopThread: () => void;
95 readonly onSendMessage: () => Promise<MessageId | null>;
96 readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
97 readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
98 readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
99 readonly onReconnectEnvironment: () => void;
100 readonly onExpandedChange?: (expanded: boolean) => void;
101}
102
103/**
104 * The pill / card container — renders as LiquidGlassView on supported
105 * iOS 26+ devices (progressive blur, native morph), opaque View otherwise.
106 */
107function ComposerSurface(props: {
108 readonly children: ReactNode;
109 readonly style: ViewStyle;
110 readonly isDarkMode: boolean;
111}) {
112 if (isLiquidGlassSupported) {
113 return (
114 <LiquidGlassView
115 effect="clear"
116 interactive
117 tintColor={props.isDarkMode ? "rgba(44,44,46,0.5)" : "rgba(255,255,255,0.45)"}
118 colorScheme={props.isDarkMode ? "dark" : "light"}
119 style={props.style}
120 >
121 {props.children}
122 </LiquidGlassView>
123 );
124 }
125
126 return (
127 <View
128 style={[
129 props.style,
130 {
131 backgroundColor: props.isDarkMode ? "rgba(44,44,46,0.96)" : "rgba(255,255,255,0.96)",
132 borderWidth: 1,
133 borderColor: props.isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)",
134 },
135 ]}
136 >
137 {props.children}
138 </View>
139 );
140}
141
142function composerConnectionStatus(input: {
143 readonly connectionError: string | null;
144 readonly connectionState: RemoteClientConnectionState;
145 readonly environmentLabel: string | null;
146}): { readonly kind: "unavailable" | "reconnecting"; readonly label: string } | null {
147 const environmentLabel = input.environmentLabel ?? "Environment";
148
149 switch (input.connectionState) {
150 case "connecting":
151 case "reconnecting":
152 return {
153 kind: "reconnecting",
154 label:
155 input.connectionError === null
156 ? `Reconnecting to ${environmentLabel}...`
157 : `Failed to connect. Retrying ${environmentLabel}...`,
158 };
159 case "offline":
160 return { kind: "unavailable", label: "You are offline" };
161 case "error":
162 return {
163 kind: "unavailable",
164 label: input.connectionError
165 ? `Failed to connect to ${environmentLabel}: ${input.connectionError}`
166 : `Failed to connect to ${environmentLabel}`,
167 };
168 case "available":
169 return { kind: "unavailable", label: `${environmentLabel} is not connected` };
170 case "connected":
171 return null;
172 }
173}
174
175const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(props: {
176 readonly onPress: () => void;
177 readonly status: { readonly kind: "unavailable" | "reconnecting"; readonly label: string };
178}) {
179 const isReconnecting = props.status.kind === "reconnecting";
180
181 return (
182 <View className="items-center pb-2">
183 <Pressable
184 accessibilityRole="button"
185 onPress={props.onPress}
186 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"
187 >
188 {isReconnecting ? (
189 <ActivityIndicator size="small" color="#8e8e93" />
190 ) : (
191 <View className="h-2 w-2 rounded-full bg-red-500" />
192 )}
193 <Text
194 className="max-w-[260px] text-sm font-t3-bold leading-[17px] text-foreground"
195 numberOfLines={1}
196 >
197 {props.status.label}
198 </Text>
199 </Pressable>
200 </View>
201 );
202});
203
204export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
205 const isDarkMode = useColorScheme() === "dark";
206 const foregroundColor = useThemeColor("--color-foreground");
207 const fallbackInputRef = useRef<ComposerEditorHandle>(null);
208 const inputRef = props.editorRef ?? fallbackInputRef;
209 const [isFocused, setIsFocused] = useState(false);
210 const wasExpandedBeforePreviewRef = useRef(false);
211 const { onExpandedChange } = props;
212
213 const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
214 const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
215 const isExpanded = isFocused;
216 const canSend = hasContent;
217
218 const onPressImage = useCallback(
219 (uri: string) => {
220 wasExpandedBeforePreviewRef.current = isFocused;
221 setPreviewImageUri(uri);
222 },
223 [isFocused],
224 );
225
226 const closePreview = useCallback(() => {
227 setPreviewImageUri(null);
228 if (wasExpandedBeforePreviewRef.current) {
229 setTimeout(() => inputRef.current?.focus(), 100);
230 }
231 }, [inputRef]);
232
233 const handleFocus = useCallback(() => {
234 setIsFocused(true);
235 onExpandedChange?.(true);
236 }, [onExpandedChange]);
237
238 const handleBlur = useCallback(() => {
239 setIsFocused(false);
240 onExpandedChange?.(false);
241 }, [onExpandedChange]);
242 const showStopAction =
243 props.selectedThread.session?.status === "running" ||
244 props.selectedThread.session?.status === "starting";
245
246 const sendLabel =
247 props.connectionState !== "connected" || props.activeThreadBusy || props.queueCount > 0
248 ? "Queue"
249 : "Send";
250 const currentModelSelection = props.selectedThread.modelSelection;
251 const currentRuntimeMode = props.selectedThread.runtimeMode;
252 const currentInteractionMode = props.selectedThread.interactionMode ?? "default";
253 const connectionStatus = composerConnectionStatus({
254 connectionError: props.connectionError,
255 connectionState: props.connectionState,
256 environmentLabel: props.environmentLabel,
257 });
258 const toolbarFadeOpaque = isDarkMode ? "rgba(0,0,0,0.95)" : "rgba(255,255,255,0.95)";
259 const toolbarFadeTransparent = isDarkMode ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)";
260 const selectedProviderStatus = useMemo(() => {
261 if (!props.serverConfig) return null;
262 return (
263 props.serverConfig.providers.find(
264 (p) => p.instanceId === props.selectedThread.modelSelection.instanceId,
265 ) ?? null
266 );
267 }, [props.serverConfig, props.selectedThread.modelSelection.instanceId]);
268
269 // ── Trigger detection ────────────────────────────────────
270 const [composerSelection, setComposerSelection] = useState(() => ({
271 start: props.draftMessage.length,
272 end: props.draftMessage.length,
273 }));
274
275 const handleSelectionChange = useCallback((selection: ComposerEditorSelection) => {
276 setComposerSelection(selection);
277 }, []);
278 useEffect(() => {
279 const end = props.draftMessage.length;
280 setComposerSelection((selection) => {
281 const start = Math.min(selection.start, end);
282 const selectionEnd = Math.min(selection.end, end);
283 if (start === selection.start && selectionEnd === selection.end) {
284 return selection;
285 }
286 return { start, end: selectionEnd };
287 });
288 }, [props.draftMessage.length]);
289
290 const composerTrigger = useMemo<ComposerTrigger | null>(() => {
291 if (composerSelection.start !== composerSelection.end) {
292 return null;
293 }
294 return detectComposerTrigger(props.draftMessage, composerSelection.end);
295 }, [composerSelection, props.draftMessage]);
296 const pathSearch = useComposerPathSearch({
297 environmentId: props.environmentId,
298 cwd: composerTrigger?.kind === "path" ? props.projectCwd : null,
299 query: composerTrigger?.kind === "path" ? composerTrigger.query : null,
300 });
301
302 const composerMenuItems: ComposerCommandItem[] = useMemo(() => {
303 if (!composerTrigger) return [];
304
305 if (composerTrigger.kind === "slash-command") {
306 const q = composerTrigger.query.toLowerCase();
307 const allBuiltIn = [
308 {
309 id: "cmd:model",
310 type: "slash-command" as const,
311 command: "model",
312 label: "/model",
313 description: "Switch model",
314 },
315 {
316 id: "cmd:plan",
317 type: "slash-command" as const,
318 command: "plan",
319 label: "/plan",
320 description: "Switch to plan mode",
321 },
322 {
323 id: "cmd:default",
324 type: "slash-command" as const,
325 command: "default",
326 label: "/default",
327 description: "Switch to default mode",
328 },
329 ];
330 const builtIn = allBuiltIn.filter((item) => item.command.includes(q));
331
332 const providerCommands: ComposerCommandItem[] = [];
333 for (const cmd of selectedProviderStatus?.slashCommands ?? []) {
334 if (!cmd.name.toLowerCase().includes(q)) continue;
335 providerCommands.push({
336 id: `pcmd:${cmd.name}`,
337 type: "provider-slash-command" as const,
338 command: cmd,
339 label: `/${cmd.name}`,
340 description: cmd.description ?? "",
341 });
342 }
343
344 return [...builtIn, ...providerCommands];
345 }
346
347 if (composerTrigger.kind === "skill") {
348 const enabledSkills = (selectedProviderStatus?.skills ?? []).filter((s) => s.enabled);
349 const normalizedQuery = normalizeSearchQuery(composerTrigger.query, {
350 trimLeadingPattern: /^\$+/,
351 });
352
353 if (!normalizedQuery) {
354 return enabledSkills.slice(0, 20).map((skill) => ({
355 id: `skill:${skill.name}`,
356 type: "skill" as const,
357 skill,
358 label: skill.displayName ?? skill.name,
359 description: skill.shortDescription ?? skill.description ?? "",
360 }));
361 }
362
363 const ranked: Array<{
364 item: (typeof enabledSkills)[number];
365 score: number;
366 tieBreaker: string;
367 }> = [];
368 for (const skill of enabledSkills) {
369 const displayLabel = (skill.displayName ?? skill.name).toLowerCase();
370 const scores = [
371 scoreQueryMatch({
372 value: skill.name.toLowerCase(),
373 query: normalizedQuery,
374 exactBase: 0,
375 prefixBase: 2,
376 boundaryBase: 4,
377 includesBase: 6,
378 fuzzyBase: 100,
379 boundaryMarkers: ["-", "_", "/"],
380 }),
381 scoreQueryMatch({
382 value: displayLabel,
383 query: normalizedQuery,
384 exactBase: 1,
385 prefixBase: 3,
386 boundaryBase: 5,
387 includesBase: 7,
388 fuzzyBase: 110,
389 }),
390 scoreQueryMatch({
391 value: skill.shortDescription?.toLowerCase() ?? "",
392 query: normalizedQuery,
393 exactBase: 20,
394 prefixBase: 22,
395 boundaryBase: 24,
396 includesBase: 26,
397 }),
398 scoreQueryMatch({
399 value: skill.description?.toLowerCase() ?? "",
400 query: normalizedQuery,
401 exactBase: 30,
402 prefixBase: 32,
403 boundaryBase: 34,
404 includesBase: 36,
405 }),
406 ].filter((s): s is number => s !== null);
407
408 if (scores.length > 0) {
409 insertRankedSearchResult(
410 ranked,
411 {
412 item: skill,
413 score: Math.min(...scores),
414 tieBreaker: `${displayLabel}\u0000${skill.name}`,
415 },
416 20,
417 );
418 }
419 }
420
421 return ranked.map(({ item: skill }) => ({
422 id: `skill:${skill.name}`,
423 type: "skill" as const,
424 skill,
425 label: skill.displayName ?? skill.name,
426 description: skill.shortDescription ?? skill.description ?? "",
427 }));
428 }
429
430 if (composerTrigger.kind === "path") {
431 return pathSearch.entries.map((entry) => {
432 const parts = entry.path.split("/");
433 return {
434 id: `path:${entry.path}`,
435 type: "path" as const,
436 path: entry.path,
437 kind: entry.kind,
438 label: parts[parts.length - 1] ?? entry.path,
439 description: parts.length > 1 ? parts.slice(0, -1).join("/") : "",
440 };
441 });
442 }
443
444 return [];
445 }, [composerTrigger, pathSearch.entries, selectedProviderStatus]);
446
447 // ── Handle command selection ──────────────────────────────
448 const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
449
450 const handleSend = useCallback(() => {
451 void onSendMessage();
452 }, [onSendMessage]);
453 const handleCommandSelect = useCallback(
454 (item: ComposerCommandItem) => {
455 if (!composerTrigger) return;
456
457 if (
458 item.type === "slash-command" &&
459 (item.command === "plan" || item.command === "default")
460 ) {
461 const result = replaceTextRange(
462 draftMessage,
463 composerTrigger.rangeStart,
464 composerTrigger.rangeEnd,
465 "",
466 );
467 setComposerSelection({ start: result.cursor, end: result.cursor });
468 onChangeDraftMessage(result.text);
469 onUpdateInteractionMode(item.command);
470 return;
471 }
472
473 let replacement = "";
474 if (item.type === "path") {
475 replacement = `${serializeComposerFileLink(item.path)} `;
476 } else if (item.type === "skill") {
477 replacement = `$${item.skill.name} `;
478 } else if (item.type === "slash-command") {
479 replacement = `/${item.command} `;
480 } else if (item.type === "provider-slash-command") {
481 replacement = `/${item.command.name} `;
482 }
483
484 const result = replaceTextRange(
485 draftMessage,
486 composerTrigger.rangeStart,
487 composerTrigger.rangeEnd,
488 replacement,
489 );
490 setComposerSelection({ start: result.cursor, end: result.cursor });
491 onChangeDraftMessage(result.text);
492 },
493 [composerTrigger, draftMessage, onChangeDraftMessage, onUpdateInteractionMode],
494 );
495
496 // ── Model menu ───────────────────────────────────────────
497 const modelOptions = useMemo(
498 () => buildModelOptions(props.serverConfig, currentModelSelection),
499 [props.serverConfig, currentModelSelection],
500 );
501 const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
502 const currentModelOption =
503 modelOptions.find(
504 (option) =>
505 option.selection.instanceId === currentModelSelection.instanceId &&
506 option.selection.model === currentModelSelection.model,
507 ) ?? null;
508 const providerOptionDescriptors = useMemo(
509 () =>
510 resolveProviderOptionDescriptors({
511 capabilities: currentModelOption?.capabilities,
512 selections: currentModelSelection.options,
513 }),
514 [currentModelOption?.capabilities, currentModelSelection.options],
515 );
516 const configurationLabel = useMemo(
517 () => providerOptionsConfigurationLabel(providerOptionDescriptors),
518 [providerOptionDescriptors],
519 );
520 const modelMenuActions = useMemo(
521 () =>
522 providerGroups.map((group) => ({
523 id: `provider:${group.providerKey}`,
524 title: group.providerLabel,
525 subtitle: group.models.find(
526 (model) =>
527 model.selection.instanceId === currentModelSelection.instanceId &&
528 model.selection.model === currentModelSelection.model,
529 )?.label,
530 subactions: group.models.map((option) => ({
531 id: `model:${option.key}`,
532 title: option.label,
533 state:
534 option.selection.instanceId === currentModelSelection.instanceId &&
535 option.selection.model === currentModelSelection.model
536 ? ("on" as const)
537 : undefined,
538 })),
539 })),
540 [providerGroups, currentModelSelection],
541 );
542
543 // ── Options menu ─────────────────────────────────────────
544 const optionsMenuActions = useMemo(
545 () => [
546 ...buildProviderOptionMenuActions(providerOptionDescriptors),
547 {
548 id: "options-runtime",
549 title: "Runtime",
550 subtitle:
551 currentRuntimeMode === "approval-required"
552 ? "Approve actions"
553 : currentRuntimeMode === "auto-accept-edits"
554 ? "Auto-accept edits"
555 : "Full access",
556 subactions: [
557 { id: "options:runtime:approval-required", title: "Approve actions" },
558 { id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
559 { id: "options:runtime:full-access", title: "Full access" },
560 ].map((option) => {
561 const value = option.id.replace("options:runtime:", "");
562 return {
563 id: option.id,
564 title: option.title,
565 state: currentRuntimeMode === value ? ("on" as const) : undefined,
566 };
567 }),
568 },
569 {
570 id: "options-interaction",
571 title: "Interaction",
572 subtitle: currentInteractionMode === "plan" ? "Plan" : "Default",
573 subactions: [
574 { id: "options:interaction:default", title: "Default" },
575 { id: "options:interaction:plan", title: "Plan" },
576 ].map((option) => {
577 const value = option.id.replace("options:interaction:", "");
578 return {
579 id: option.id,
580 title: option.title,
581 state: currentInteractionMode === value ? ("on" as const) : undefined,
582 };
583 }),
584 },
585 ],
586 [currentInteractionMode, currentRuntimeMode, providerOptionDescriptors],
587 );
588
589 // ── Menu handlers ────────────────────────────────────────
590 function handleModelMenuAction(event: string) {
591 if (!event.startsWith("model:")) {
592 return;
593 }
594 const modelKey = event.slice("model:".length);
595 const option = modelOptions.find((o) => o.key === modelKey);
596 if (option) {
597 props.onUpdateModelSelection(option.selection);
598 }
599 }
600
601 function handleOptionsMenuAction(event: string) {
602 const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
603 if (providerOptions) {
604 props.onUpdateModelSelection({
605 ...currentModelSelection,
606 options: providerOptions,
607 });
608 return;
609 }
610 if (event.startsWith("options:runtime:")) {
611 const runtimeMode = event.slice("options:runtime:".length) as RuntimeMode;
612 props.onUpdateRuntimeMode(runtimeMode);
613 return;
614 }
615 if (event.startsWith("options:interaction:")) {
616 const interactionMode = event.slice("options:interaction:".length) as ProviderInteractionMode;
617 props.onUpdateInteractionMode(interactionMode);
618 }
619 }
620
621 return (
622 <View
623 style={{
624 paddingHorizontal: 16,
625 paddingTop: isExpanded ? 8 : 6,
626 paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
627 experimental_backgroundImage: isDarkMode
628 ? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.85) 40%, rgba(0,0,0,0.95) 100%)"
629 : "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.85) 40%, rgba(255,255,255,0.95) 100%)",
630 }}
631 >
632 <View className="w-full" style={{ position: "relative" }}>
633 {composerTrigger && composerMenuItems.length > 0 ? (
634 <View
635 style={{
636 position: "absolute",
637 bottom: "100%",
638 left: 0,
639 right: 0,
640 marginBottom: 8,
641 zIndex: 10,
642 }}
643 >
644 <ComposerCommandPopover
645 items={composerMenuItems}
646 triggerKind={composerTrigger.kind}
647 isLoading={pathSearch.isPending}
648 onSelect={handleCommandSelect}
649 />
650 </View>
651 ) : null}
652
653 {connectionStatus ? (
654 <ComposerConnectionStatusPill
655 status={connectionStatus}
656 onPress={props.onReconnectEnvironment}
657 />
658 ) : null}
659
660 <ComposerSurface
661 isDarkMode={isDarkMode}
662 style={
663 isExpanded
664 ? {
665 borderRadius: 20,
666 overflow: "hidden" as const,
667 paddingHorizontal: 14,
668 paddingVertical: 12,
669 }
670 : {
671 borderRadius: 999,
672 overflow: "hidden" as const,
673 flexDirection: "row" as const,
674 alignItems: "center" as const,
675 paddingLeft: 18,
676 paddingRight: 5,
677 paddingVertical: 5,
678 }
679 }
680 >
681 {/* Attachment strip — inside the card, above the text input */}
682 {isExpanded ? (
683 <View style={{ paddingBottom: props.draftAttachments.length > 0 ? 10 : 0 }}>
684 <ComposerAttachmentStrip
685 attachments={props.draftAttachments}
686 onRemove={props.onRemoveDraftImage}
687 onPressImage={onPressImage}
688 />
689 </View>
690 ) : null}
691
692 <View style={isExpanded ? undefined : { flex: 1, minWidth: 0 }}>
693 <ComposerEditor
694 ref={inputRef}
695 multiline
696 value={props.draftMessage}
697 skills={selectedProviderStatus?.skills ?? []}
698 selection={composerSelection}
699 onChangeText={props.onChangeDraftMessage}
700 onSelectionChange={handleSelectionChange}
701 onPasteImages={(uris) => void props.onNativePasteImages(uris)}
702 placeholder={props.placeholder}
703 onFocus={handleFocus}
704 onBlur={handleBlur}
705 scrollEnabled={isExpanded}
706 contentInsetVertical={isExpanded ? 0 : 6}
707 style={
708 isExpanded
709 ? {
710 minHeight: 80,
711 maxHeight: 160,
712 paddingHorizontal: 4,
713 paddingVertical: 4,
714 }
715 : {
716 height: 36,
717 }
718 }
719 textStyle={{
720 ...MOBILE_TYPOGRAPHY.composer,
721 color: foregroundColor,
722 fontFamily: "DMSans_400Regular",
723 }}
724 />
725 </View>
726 {!isExpanded && props.draftAttachments.length > 0 ? (
727 <View style={{ flexDirection: "row", gap: 4, paddingLeft: 4 }}>
728 {props.draftAttachments.slice(0, 3).map((image) => (
729 <Pressable key={image.id} onPress={() => onPressImage(image.previewUri)}>
730 <Image
731 source={{ uri: image.previewUri }}
732 className="bg-subtle"
733 style={{
734 width: 30,
735 height: 30,
736 borderRadius: 8,
737 }}
738 resizeMode="cover"
739 />
740 </Pressable>
741 ))}
742 {props.draftAttachments.length > 3 ? (
743 <View
744 className="bg-subtle-strong"
745 style={{
746 width: 30,
747 height: 30,
748 borderRadius: 8,
749 alignItems: "center",
750 justifyContent: "center",
751 }}
752 >
753 <Text className="text-foreground-muted text-2xs font-t3-bold">
754 +{props.draftAttachments.length - 3}
755 </Text>
756 </View>
757 ) : null}
758 </View>
759 ) : null}
760 {!isExpanded ? (
761 showStopAction ? (
762 <ControlPill icon="stop.fill" variant="danger" onPress={props.onStopThread} />
763 ) : (
764 <ControlPill
765 icon="arrow.up"
766 variant="primary"
767 disabled={!canSend}
768 onPress={handleSend}
769 />
770 )
771 ) : null}
772 </ComposerSurface>
773
774 {/* Toolbar row — matches draft page layout (expanded only) */}
775 {isExpanded ? (
776 <ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
777 <ComposerToolbarScroller
778 fadeOpaque={toolbarFadeOpaque}
779 fadeTransparent={toolbarFadeTransparent}
780 >
781 <ComposerToolbarButton
782 icon="plus"
783 onPress={() => void props.onPickDraftImages()}
784 showChevron={false}
785 />
786 <ControlPillMenu
787 actions={modelMenuActions}
788 onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
789 >
790 <ComposerToolbarTrigger
791 accessibilityLabel="Model"
792 iconNode={
793 <ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
794 }
795 label={currentModelOption?.label ?? currentModelSelection.model}
796 />
797 </ControlPillMenu>
798 <ControlPillMenu
799 actions={optionsMenuActions}
800 onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
801 >
802 <ComposerToolbarTrigger
803 accessibilityLabel="Configuration"
804 icon="slider.horizontal.3"
805 label={configurationLabel}
806 />
807 </ControlPillMenu>
808 {showStopAction ? (
809 <ComposerToolbarButton
810 icon="stop.fill"
811 variant="danger"
812 onPress={props.onStopThread}
813 showChevron={false}
814 />
815 ) : null}
816 </ComposerToolbarScroller>
817 <ComposerToolbarButton
818 accessibilityLabel={sendLabel}
819 icon="arrow.up"
820 variant="primary"
821 disabled={!canSend}
822 onPress={handleSend}
823 showChevron={false}
824 />
825 </ComposerToolbarRow>
826 ) : null}
827
828 {/* Queue count */}
829 {props.queueCount > 0 ? (
830 <Text
831 className="text-foreground-muted"
832 style={{
833 ...MOBILE_TYPOGRAPHY.label,
834 paddingTop: 8,
835 }}
836 >
837 {props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
838 automatically.
839 </Text>
840 ) : null}
841 </View>
842
843 <ImageViewing
844 images={previewImageUri ? [{ uri: previewImageUri }] : []}
845 imageIndex={0}
846 visible={previewImageUri !== null}
847 onRequestClose={closePreview}
848 swipeToCloseEnabled
849 doubleTapToZoomEnabled
850 />
851 </View>
852 );
853});