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